content
stringlengths
7
1.05M
name = 'exit' usage = 'EXIT' description = 'Exits Diplomat.' def execute(query): return 'Exiting Diplomat.'
"""Args: param1 (int): byte as int value in binary Returns: True if input indicates a meta event, False if otherwise. """ def is_meta(n): # hex status byte 0xFF # dec value 255 dec_val = int(n, 2) if dec_val == 255: return True else: return False
#!/usr/bin/env python """version of the sdk """ __version__ = "1.0.0"
success = { "uuid": "8bf7e570-67cd-4670-a37c-0999fd07f9bf", "action": "EventsRouter", "result": { "success": True }, "tid": 1, "type": "rpc", "method": "detail" } fail = { "uuid": "8bf7e570-67cd-4670-a37c-0999fd07f9bf", "action": "EventsRouter", "result": { "msg": "ServiceResponseError: Not Found", "type": "exception", "success": False }, "tid": 1, "type": "rpc", "method": "detail" } events_query = { "uuid": "eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6", "action": "EventsRouter", "result": { "totalCount": 50, "events": [ { "prodState": "Production", "firstTime": 1505865565.822, "facility": None, "eventClassKey": "csm.sessionFailed", "agent": "zenpython", "dedupid": "test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3", "Location": [ { "uid": "/zport/dmd/Locations/Moon Base Alpha", "name": "/Moon Base Alpha" } ], "ownerid": "zenoss", "eventClass": { "text": "/Status", "uid": "/zport/dmd/Events/Status" }, "id": "02420a11-0015-98b9-11e7-9d96ae351999", "DevicePriority": "Normal", "monitor": "localhost", "priority": None, "details": { "node": [ "test-01" ], "recvtime": [ "1508797427" ], "zenoss.device.location": [ "/Moon Base Alpha" ], "zenoss.device.priority": [ "3" ], "zenoss.device.device_class": [ "/Storage/NetApp/C-Mode" ], "seq-num": [ "647604" ], "source": [ "CsmMpAgentThread" ], "manager": [ "13a1a22ff067" ], "message-name": [ "csm.sessionFailed" ], "resolution": [ "If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. " ], "eventClassMapping": [ "/Status/failureNoFrames" ], "time": [ "1508797427" ], "zenoss.device.production_state": [ "1000" ], "zenoss.device.ip_address": [ "1.2.3.4" ], "event": [ "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. " ] }, "DeviceClass": [ { "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode", "name": "/Storage/NetApp/C-Mode" } ], "eventKey": "ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug", "evid": "02420a11-0015-98b9-11e7-9d96ae351999", "eventClassMapping": { "uuid": "1337d66f-d5fa-4c3b-8198-bcfedf83d040", "name": "failureNoFrames" }, "component": { "url": "/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733", "text": "test-01", "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com/systemnodes/test-01", "uuid": "08c40deb-1009-4634-a529-d66631391733" }, "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": { "url": "/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932", "text": "test.example.com", "uuid": "02e21618-b30a-47bf-8591-471c70570932", "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com" }, "message": "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. \nResolution: If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. ", "severity": 3, "count": 66, "stateChange": 1507054918.83, "ntevid": None, "summary": "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ", "eventState": "Acknowledged", "lastTime": 1508797479.194, "ipAddress": [ "1.2.3.4" ], "Systems": [] } ], "success": True, "asof": 1508797504.409547 }, "tid": 1, "type": "rpc", "method": "query" } events_query_evid = { "uuid": "eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6", "action": "EventsRouter", "result": { "totalCount": 50, "events": [ { "evid": "02420a11-0015-98b9-11e7-9d96ae351999" } ], "success": True, "asof": 1508797504.409547 }, "tid": 1, "type": "rpc", "method": "query" } event_detail = { "uuid": "23f0bbd9-b6a3-46bb-909f-aa53891dfbf5", "action": "EventsRouter", "result": { "event": [ { "prodState": "Production", "firstTime": 1505865565.822, "device_uuid": "02e21618-b30a-47bf-8591-471c70570932", "eventClassKey": "smc.snapmir.unexpected.err", "agent": "zenpython", "dedupid": "test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3", "Location": [ { "uid": "/zport/dmd/Locations/Moon Base Alpha", "name": "/Moon Base Alpha" } ], "component_url": "/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733", "ownerid": "zenoss", "eventClassMapping_url": "/zport/dmd/goto?guid=1337d66f-d5fa-4c3b-8198-bcfedf83d040", "eventClass": "/Status", "id": "02420a11-0015-98b9-11e7-9d96ae351999", "device_title": "test.example.com", "DevicePriority": "Normal", "log": [ [ "zenoss", 1507054918830, "state changed to Acknowledged" ] ], "facility": None, "eventClass_url": "/zport/dmd/Events/Status", "monitor": "localhost", "priority": None, "device_url": "/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932", "details": [ { "key": "event", "value": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. " }, { "key": "eventClassMapping", "value": "/Status/failureNoFrames" }, { "key": "manager", "value": "13a1a22ff067" }, { "key": "message-name", "value": "smc.snapmir.unexpected.err" }, { "key": "node", "value": "test-01" }, { "key": "recvtime", "value": "1508798161" }, { "key": "resolution", "value": "If the problem persists, contact NetApp technical support. " }, { "key": "seq-num", "value": "647654" }, { "key": "source", "value": "sm_logger_main" }, { "key": "time", "value": "1508798161" }, { "key": "zenoss.device.device_class", "value": "/Storage/NetApp/C-Mode" }, { "key": "zenoss.device.ip_address", "value": "1.2.3.4" }, { "key": "zenoss.device.location", "value": "/Moon Base Alpha" }, { "key": "zenoss.device.priority", "value": "3" }, { "key": "zenoss.device.production_state", "value": "1000" } ], "DeviceClass": [ { "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode", "name": "/Storage/NetApp/C-Mode" } ], "eventKey": "ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug", "evid": "02420a11-0015-98b9-11e7-9d96ae351999", "eventClassMapping": "failureNoFrames", "component": "test-01", "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": "test.example.com", "Systems": [], "component_title": "test-01", "severity": 3, "count": 66, "stateChange": 1507054918.83, "ntevid": None, "summary": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. ", "message": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. \nResolution: If the problem persists, contact NetApp technical support. ", "eventState": "Acknowledged", "lastTime": 1508798199.186, "ipAddress": [ "1.2.3.4" ], "component_uuid": "08c40deb-1009-4634-a529-d66631391733" } ], "success": True }, "tid": 1, "type": "rpc", "method": "detail" } events_config = { "uuid": "7f7109f2-1a6f-41f5-a12f-bbd95f280b9c", "action": "EventsRouter", "result": { "data": [ { "xtype": "eventageseverity", "defaultValue": 4, "id": "event_age_disable_severity", "value": 4, "name": "Don't Age This Severity and Above" }, { "defaultValue": False, "id": "event_age_severity_inclusive", "value": False, "xtype": "hidden" } ], "success": True }, "tid": 1, "type": "rpc", "method": "getConfig" } add_event_evid_query = { "uuid": "6700ab59-c559-42ec-959b-ebc33bc52257", "action": "EventsRouter", "result": { "totalCount": 1, "events": [ { "evid": "02420a11-000c-a561-11e7-ba9b510182b3", } ], "success": True, "asof": 1509056503.945677 }, "tid": 1, "type": "rpc", "method": "query" } add_event_detail = { "uuid": "c54074e8-af8b-4e40-a679-7dbe314709ed", "action": "EventsRouter", "result": { "event": [ { "prodState": None, "firstTime": 1509056189.91, "device_uuid": None, "eventClassKey": None, "agent": None, "dedupid": "Heart of Gold|Arthur Dent|/Status|3|Out of Tea", "Location": [], "component_url": None, "ownerid": None, "eventClassMapping_url": None, "eventClass": "/Status", "id": "02420a11-000c-a561-11e7-ba9b510182b3", "device_title": "Heart of Gold", "DevicePriority": None, "log": [ [ "zenoss", 1509057815980, "<p>Test log entry</p>" ] ], "facility": None, "eventClass_url": "/zport/dmd/Events/Status", "monitor": None, "priority": None, "device_url": None, "details": [], "DeviceClass": [], "eventKey": "", "evid": "02420a11-000c-a561-11e7-ba9b510182b3", "eventClassMapping": None, "component": "Arthur Dent", "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": "Heart of Gold", "Systems": [], "component_title": "Arthur Dent", "severity": 3, "count": 1, "stateChange": 1509056189.91, "ntevid": None, "summary": "Out of Tea", "message": "Out of Tea", "eventState": "New", "lastTime": 1509056189.91, "ipAddress": "", "component_uuid": None } ], "success": True }, "tid": 1, "type": "rpc", "method": "detail" }
settings = { # add provider-specific survey settings here # e.g. how to abbreviate questions }
# coding: utf-8 s = "The string ends in escape: " s += chr(27) # add an escape character at the end of $str print(repr(s))
SERVICE_NAME = "org.bluez" AGENT_IFACE = SERVICE_NAME + '.Agent1' ADAPTER_IFACE = SERVICE_NAME + ".Adapter1" DEVICE_IFACE = SERVICE_NAME + ".Device1" PLAYER_IFACE = SERVICE_NAME + '.MediaPlayer1' TRANSPORT_IFACE = SERVICE_NAME + '.MediaTransport1' OBJECT_IFACE = "org.freedesktop.DBus.ObjectManager" PROPERTIES_IFACE = "org.freedesktop.DBus.Properties" INTROSPECT_IFACE = "org.freedesktop.DBus.Introspectable"
class Cliente: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome.title() def get_nome(self): print('[INFO] Getting value...') print('[INFO] Name "{}" getted sucessfully'.format(self.__nome)) return self.__nome.title() @nome.setter def nome(self, value): print('[INFO] Setting new value...') self.__nome = value print('[INFO] New value: {}'.format(value)) if __name__ == '__main__': cliente = Cliente('thiago') cliente.nome cliente.nome = 'Thiago Kasper'
class ChartModel: def score_keywords(self, dep_keywords): #mock (@todo: update after integrating training a model) keyword_scores = [] for kw in dep_keywords: keyword_scores.append({ 'keyword': kw, 'score': 0.7 }) return keyword_scores
def word_permutation(s): return word_permutation_helper(list(s)) def word_permutation_helper(input_list): if len(input_list) ==0: return '' ret = [] for i in range(len(input_list)): base = input_list[i] remainder = input_list[:i]+input_list[i+1:] out = word_permutation_helper(remainder) if isinstance(out,list): ret.extend([out[i]+base for i in range(len(out))]) continue else: out+=base ret.append(out) return ret
def solution(participant, completion): answer = "" temp = 0 dic = {} for p in participant: dic[hash(p)] = p temp += hash(p) for c in completion: temp -= hash(c) return dic[temp]
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: mat = [[0] * n for _ in range(n)] left, top, right, bottom = 0, 0, n, n val = 1 while left < right and top < bottom: for i in range(left, right): mat[top][i] = val val += 1 top += 1 for i in range(top, bottom): mat[i][right - 1] = val val += 1 right -= 1 for i in range(right - 1, left - 1, -1): mat[bottom - 1][i] = val val += 1 bottom -= 1 for i in range(bottom - 1, top - 1, -1): mat[i][left] = val val += 1 left += 1 return mat
# DROP TABLES songplay_table_drop = "DROP TABLE songplays" user_table_drop = "DROP TABLE users" song_table_drop = "DROP TABLE songs" artist_table_drop = "DROP TABLE artists" time_table_drop = "DROP TABLE time" # CREATE TABLES songplay_table_create = (""" CREATE TABLE IF NOT EXISTS songplays ( songplay_id SERIAL PRIMARY KEY, start_time timestamp NOT NULL REFERENCES time(start_time), user_id int NOT NULL REFERENCES users(user_id), level varchar, song_id varchar, artist_id varchar, session_id int, location varchar, user_agent varchar ); """) user_table_create = (""" CREATE TABLE IF NOT EXISTS users ( user_id int PRIMARY KEY, first_name varchar NOT NULL, last_name varchar NOT NULL, gender varchar, level varchar ); """) song_table_create = (""" CREATE TABLE IF NOT EXISTS songs ( song_id varchar PRIMARY KEY, title varchar NOT NULL, artist_id varchar NOT NULL REFERENCES artists(artist_id), year int, duration numeric(10,5) ); """) artist_table_create = (""" CREATE TABLE IF NOT EXISTS artists ( artist_id varchar PRIMARY KEY, name varchar NOT NULL, location varchar, latitude numeric, longitude numeric ); """) time_table_create = (""" CREATE TABLE IF NOT EXISTS time ( start_time timestamp PRIMARY KEY, hour int, day int, week int, month int, year int, weekday int ); """) # INSERT RECORDS songplay_table_insert = (""" INSERT INTO songplays(songplay_id,start_time,user_id,level,song_id,artist_id,session_id,location,user_agent) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT (songplay_id) DO NOTHING; """) user_table_insert = (""" INSERT INTO users(user_id,first_name,last_name,gender,level) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (user_id) DO UPDATE SET level=EXCLUDED.level; """) song_table_insert = (""" INSERT INTO songs(song_id,title,artist_id,year,duration) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (song_id) DO NOTHING; """) artist_table_insert = (""" INSERT INTO artists(artist_id,name,location,latitude,longitude) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (artist_id) DO NOTHING; """) time_table_insert = (""" INSERT INTO time(start_time,hour,day,week,month,year,weekday) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (start_time) DO NOTHING; """) # FIND SONGS song_select = (""" SELECT song_id, artists.artist_id FROM songs JOIN artists ON songs.artist_id = artists.artist_id WHERE songs.title = %s AND artists.name = %s AND songs.duration = %s """) # QUERY LISTS create_table_queries = [time_table_create, artist_table_create, user_table_create, songplay_table_create, song_table_create, ] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
class Solution(object): def findCircleNum(self, M): def dfs(node): visited.add(node) for person, is_friend in enumerate(M[node]): if is_friend and person not in visited: dfs(person) circle = 0 visited = set() for node in range(len(M)): if node not in visited: circle += 1 dfs(node) return circle
a = [1,5,4,6,8,11,3,12] even = list(filter(lambda x: (x%2 == 0), a)) print(even) third = list(filter(lambda x: (x%3 == 0), a)) print(third) b = [[0,1,8],[7,2,2],[5,3,10],[1,4,5]] b.sort(key = lambda x: x[2]) print(b) b.sort(key = lambda x: x[0]+x[1]) print(b)
""" 36. How to import only specified columns from a csv file? """ """ Difficulty Level: L1 """ """ Import ‘crim’ and ‘medv’ columns of the BostonHousing dataset as a dataframe. """ """ """
# -*- coding: utf-8 -*- """ Created on Wed Feb 5 11:02:42 2020 @author: Arthur """
# # @lc app=leetcode id=111 lang=python3 # # [111] Minimum Depth of Binary Tree # # https://leetcode.com/problems/minimum-depth-of-binary-tree/description/ # # algorithms # Easy (34.89%) # Likes: 730 # Dislikes: 394 # Total Accepted: 298.5K # Total Submissions: 844K # Testcase Example: '[3,9,20,null,null,15,7]' # # Given a binary tree, find its minimum depth. # # The minimum depth is the number of nodes along the shortest path from the # root node down to the nearest leaf node. # # Note: A leaf is a node with no children. # # Example: # # Given binary tree [3,9,20,null,null,15,7], # # # ⁠ 3 # ⁠ / \ # ⁠ 9 20 # ⁠ / \ # ⁠ 15 7 # # return its minimum depth = 2. # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 left, right = self.minDepth(root.left), self.minDepth(root.right) return 1 + (min(left, right) if min(left, right) != 0 else max(left, right))
#!/usr/bin/env python3 def path_combinations(): a, b, c = 0, 1, 1 while True: yield a a, b, c = b, c, a+b+c if __name__ == '__main__': with open('input.txt', 'r') as f: adapters = sorted( int(l.strip()) for l in f.readlines() ) # part 1 difs, prev = [], 0 for joltage in adapters: difs.append(joltage-prev) prev = joltage difs.append(3) print(difs.count(1) * difs.count(3)) # part 2 # possible 1 2 3 4 5 6 ... # combinations 1 1 2 4 7 13 ... # formula nk = n↓k-1 + n↓k-2 + n↓k-3 pcs_gen = path_combinations() count, total, pcs = 0, 1, [] for dif in difs: count += 1 if dif == 3: while len(pcs) <= count: pcs.append(next(pcs_gen)) total *= pcs[count] count = 0 print(total)
def word(str): j=len(str)-1 for i in range(int(len(str)/2)): if str[i]!=str[j]: return False j=j-1 return True str=input("Enter the string :") ans=word(str) if(ans): print("string is palindrome") else: print("string is not palindrome")
class RowMenuItem: def __init__(self, widget): # Item can have an optional id self.id = None # Item may specify a parent id (for rendering purposes, like display = 'with-parent,' perhaps) self.parent_id = None # If another item chooses to display with this item, then that other item (the with-parent item) # becomes a "friend" of this item (sharing focus and blur events) self.friend_ids = [] # The widget container within this RowMenuItem self.item = widget # I typically track visibility within the lowest level widgets (<label />, etc.). # For RowMenuItems, though, I'll permit this wrapper to also have a "visibility" setting, # separate from the standard "display" attribute of low-level widgets. self.visibility = "visible" # An item may be entirely hidden from view (no height, no rendering, nothing) # Primarily used for static dialogue panels, etc., to serve as a "hidden input" field # (i.e. key listener) self.hidden = False # An item might not be selectable by the user self.disabled = False # Perhaps the single item (within a group) has an individual border? self.individual_border = False # Shrinkwrap to rnder only necessary border width? self.shrinkwrap = False # Perhaps we'll render a glowing highlight behind the text of the active selection? self.glow = False # Occasionally we'll hard-code the height for a given item self.explicit_height = None # Sometimes a row menu item will have a tooltip (which is basically a simple GridMenuCell) self.tooltip = None # A RowMenuItem may have other special properties if they begin with a - self.additional_properties = {} def configure(self, options): if ( "id" in options ): self.id = options["id"] if ( "parent-id" in options ): self.parent_id = options["parent-id"] if ( "visibility" in options ): self.visibility = options["visibility"] if ( "hidden" in options ): self.hidden = options["hidden"] if ( "disabled" in options ): self.disabled = int( options["disabled"] ) if ( "individual-border" in options ): self.individual_border = int( options["individual-border"] ) if ( "shrinkwrap" in options ): self.shrinkwrap = int( options["shrinkwrap"] ) if ( "glow" in options ): self.glow = int( options["glow"] ) if ( "explicit-height" in options ): self.explicit_height = int( options["explicit-height"] ) # Check for special additional properties for key in options: # Must start with a - if ( key.startswith("-") ): # Save it self.additional_properties[key] = options[key] #print "..." #print options #print self.additional_properties #print 5/0 # For chaining return self # Get a special property def get_property(self, key): # Validate if (key in self.additional_properties): return self.additional_properties[key] else: return None def get_widget_container(self): return self.item # Event callbacks def while_awake(self): # Forward message self.get_widget().while_awake() def while_asleep(self): # Forward message self.get_widget().while_asleep() def on_blur(self): # Forward message self.get_widget().on_blur() def get_widget(self): return self.item # used in widget height calculations (e.g. overall RowMenu height) def get_box_height(self, text_renderer): # Hidden items have no height if (self.hidden): return 0 elif (self.explicit_height != None): return (self.explicit_height) else: #print "Advance, check box height for %s" % self.item return (self.item.get_box_height(text_renderer)) # Used to determine render region for backgrounds and the like def get_render_height(self, text_renderer): # Hidden items have no height if (self.hidden): return 0 elif (self.explicit_height != None): return self.explicit_height else: return self.item.get_render_height(text_renderer) def get_min_x(self, text_renderer): return self.item.get_min_x(text_renderer) def add_tooltip(self):#, width, align, delay, lifespan, margin_x = 20, margin_y = 0): self.tooltip = RowMenuTooltip()#RowMenuItemTooltip(width, align, delay = delay, lifespan = lifespan, margin_x = margin_x, margin_y = margin_y) return self.tooltip
nome = str(input('Digite seu nome completo: ')).strip() print(nome.upper()) print(nome.lower()) print(len(nome))
#!/usr/bin/env python # encoding=utf-8 def test(): print('utils_gao, making for ml')
class Config(object): """This is the basic configuration class for BorgWeb.""" #: builtin web server configuration HOST = '127.0.0.1' # use 0.0.0.0 to bind to all interfaces PORT = 9087 # ports < 1024 need root DEBUG = True # if True, enable reloader and debugger LOG_FILE = 'prombot.log' # Telegram bot config TELEGRAM_BOT_USERNAME = "dwarferie_bot" TELEGRAM_BOT_TOKEN = "1110478838:AAGZVZaDmjUPffFTIxpgLVIKI5r7yg5h_8g" TELEGRAM_BOT_CHAT_ID = "-489291168"
def _gen_k8s_file(ctx): odir = ctx.actions.declare_directory("tmp") ctx.actions.run( inputs = [], outputs = [odir], arguments = [], progress_message = "Converting", env = { "CDK8S_OUTDIR": odir.path, }, executable = ctx.executable.tool, tools = [ctx.executable.tool], ) runfiles = ctx.runfiles( files = [odir, ctx.executable._concat], ) ctx.actions.run( inputs = [odir], outputs = [ctx.outputs.out], arguments = [odir.path, ctx.outputs.out.path], executable = ctx.executable._concat, tools = [ctx.executable._concat], ) gen_to_stdout = ctx.actions.declare_file(ctx.label.name + ".gen") ctx.actions.write( output = gen_to_stdout, content = "%s %s" % (ctx.executable._concat.short_path, odir.short_path), is_executable = True, ) # gen_to_file = ctx.actions.declare_file("gen_to_file") # ctx.actions.write( # output = gen_to_file, # content = (base_gen_cmd + "> %s") % (odir.path, ctx.outputs.out.path), # is_executable = True, # ) # ctx.actions.run( # inputs = [odir, gen_to_stdout], # executable = gen_to_file, # outputs = [ctx.outputs.out], # ) return [DefaultInfo( files = depset([ctx.outputs.out]), runfiles = runfiles, executable = gen_to_stdout, )] gen_k8s_file = rule( _gen_k8s_file, attrs = { "tool": attr.label( executable = True, allow_files = True, cfg = "exec", ), "_concat": attr.label( executable = True, allow_single_file = True, cfg = "exec", default = "//rules:concat.sh", ) }, executable = True, outputs = { "out": "%{name}.yaml", }, )
# # This file contains the Python code from Program 2.9 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm02_09.txt # def geometricSeriesSum(x, n): return (power(x, n + 1) - 1) / (x - 1)
N, K = map(int, input().split()) a_list = list(map(int, input().split())) sum_list = [] for i in range(N): for j in range(i, N): sum_list.append(sum(a_list[i:j+1])) ans = 0 count = 0 tmp = [] for i in range(40, -1, -1): for s in sum_list: check_num = 1 << i logical_and = check_num & s if logical_and != 0: count += 1 if count >= K: ans += 1 << i tmp = [x for x in sum_list if (1 << i) & x != 0] sum_list = tmp[:] count = 0 print(ans)
# Reads config/config.ini and performs sanity checks class Config(object): config = None def __init__(self, path='config/config.ini'): if not self.config: print("[WARNING] Loading placeholder config") # this has to be replaced by reading the actual .ini config file with open(path, 'r') as cfg: token = cfg.readline().rstrip() initial_channel = cfg.readline().rstrip() default_playlist = cfg.readline().rstrip() Config.config = { 'token': token, 'initial_channel': initial_channel, 'default_playlist': default_playlist } def __getattr__(self, name): return self.config[name] def __setattr__(self, name, value): print("[WARNING] Overriding config value") self.config[name] = value conf = Config()
''' Set data type lst = [varname, varname1, varname2] dictionary = { "key": "value", } ''' set = {"Item1", "Item2", "Item3"} print(set) # {'Item1', 'Item2', 'Item3'} # Sets do not care about the order # {'Item2', 'Item3', 'Item1'} # Sets do not care about the order s = {"Item1", "Item2", "Item2", "Item3"} print(s) # {'Item3', 'Item2', 'Item1'} ## Second item2 considered a duplicate s.add("item 4") print(s) #{'Item2', 'Item1', 'item 4', 'Item3'} s.remove("item 4") print(s) # {'Item1', 'Item2', 'Item3'}
""" gen123.py generate sequences from a base list, repeating each element one more time than the last. """ def gen123(m): #yield None n = 0 for item in m: n += 1 for i in range(n): yield item
class SlidingAverage: def __init__(self, window_size): self.index = 0 self.values = [0] * window_size def _previous(self): return self.values[(self.index + len(self.values) - 1) % len(self.values)] def update(self, value): self.values[self.index] = self._previous() + value self.index = (self.index + 1) % len(self.values) def get(self): return (self._previous() - self.values[self.index]) / (len(self.values) - 1)
palavras = ('Doidera', 'Calipso', 'Yoda', 'Axt', 'Jovirone', 'Matilda', 'Schwarzenneger', 'Mustefaga', 'Instinct', 'Kobayashi', 'Ludgero', 'Salcicha', 'Scooby', 'Turtle', 'Lily', 'Toast') for palavra in palavras: print(f'Na palavra {palavra.upper()} temos ', end='') for c in range(0, len(palavra)): if palavra[c] in 'AaEeIiOoUu': print(palavra[c].lower(), end=' ') print()
def specificSummator(): counter = 0 for i in range(0, 10000): if (i % 7) == 0: counter += i elif (i % 9) == 0: counter += i return counter print(specificSummator())
# WAP to accept a file from user and print shortest and longest line from that file. def PrintShortestLongestLines(inputFile): line = inputFile.readline() maxLine = line minLine = line while line != "": line = inputFile.readline() if line == "\n" or line == "": continue if len(line) < len(minLine): minLine = line elif len(line) > len(maxLine): maxLine = line return minLine, maxLine def PrintShortestLongestLinesDict(inputFile): line = inputFile.readline() maxline = len(line) minline = len(line) resultDict = dict({ "MinLen": line, "MaxLen": line }) while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < minline: resultDict["MinLen"] = line elif len(line) > maxline: resultDict["MaxLen"] = line return resultDict def main(): inputFilePath = input("Please enter a filename to be read: ") fd = open(inputFilePath) if fd != None: # print(PrintShortestLongestLines(fd)) minLenLin, maxLenLine = PrintShortestLongestLines(fd) print("Min Length {}\nMax Length {}".format(minLenLin, maxLenLine)) else: print("File does not exist") if __name__ == "__main__": main()
# 로또의 최고순위와 최저순위 def solution(lottos, win_nums): correct = 0 zero_cnt = lottos.count(0) rank = {6:1,5:2,4:3,3:4,2:5,1:6,0:6} for number in lottos: if number != 0 and number in win_nums: correct += 1 return [rank[correct+zero_cnt],rank[correct]] ''' 테스트 1 〉 통과 (0.01ms, 10.2MB) 테스트 2 〉 통과 (0.00ms, 10.2MB) 테스트 3 〉 통과 (0.01ms, 10.3MB) 테스트 4 〉 통과 (0.01ms, 10.2MB) 테스트 5 〉 통과 (0.01ms, 10.2MB) 테스트 6 〉 통과 (0.00ms, 10.2MB) 테스트 7 〉 통과 (0.01ms, 10.2MB) 테스트 8 〉 통과 (0.01ms, 10.1MB) 테스트 9 〉 통과 (0.01ms, 10.1MB) 테스트 10 〉 통과 (0.01ms, 10.1MB) 테스트 11 〉 통과 (0.01ms, 10.1MB) 테스트 12 〉 통과 (0.01ms, 10.2MB) 테스트 13 〉 통과 (0.00ms, 10.2MB) 테스트 14 〉 통과 (0.01ms, 10.2MB) 테스트 15 〉 통과 (0.00ms, 9.96MB) '''
# Much of the code in this file was ported from ev3dev-lang-python so we # are including the license for ev3dev-lang-python. # ----------------------------------------------------------------------------- # Copyright (c) 2015 Ralph Hempel # # 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. # ----------------------------------------------------------------------------- CENTIMETER_MM = 10 DECIMETER_MM = 100 METER_MM = 1000 INCH_MM = 25.4 FOOT_MM = 304.8 YARD_MM = 914.4 STUD_MM = 8 class DistanceValue: """ A base class for ``Distance`` classes. Do not use this directly. Use one of: * :class:`DistanceMillimeters` * :class:`DistanceCentimeters` * :class:`DistanceDecimeters` * :class:`DistanceMeters` * :class:`DistanceInches` * :class:`DistanceFeet` * :class:`DistanceYards` * :class:`DistanceStuds`. """ # This allows us to sort lists of DistanceValue objects def __lt__(self, other): return self.mm < other.mm def __rmul__(self, other): return self.__mul__(other) class DistanceMillimeters(DistanceValue): """ Distance in millimeters Args: millimeters (int): the number of millimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceMillimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 600 millimeters md.run_for_distance(DistanceMillimeters(600), MotorSpeedDPS(100)) """ def __init__(self, millimeters): self.millimeters = millimeters def __str__(self): return str(self.millimeters) + "mm" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceMillimeters(self.millimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.millimeters class DistanceCentimeters(DistanceValue): """ Distance in centimeters Args: centimeters (int): the number of centimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceCentimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 60 centimeters md.run_for_distance(DistanceCentimeters(60), MotorSpeedDPS(100)) """ def __init__(self, centimeters): self.centimeters = centimeters def __str__(self): return str(self.centimeters) + "cm" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceCentimeters(self.centimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.centimeters * CENTIMETER_MM class DistanceDecimeters(DistanceValue): """ Distance in decimeters Args: decimeters (int): the number of decimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceDecimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 6 decimeters md.run_for_distance(DistanceDecimeters(6), MotorSpeedDPS(100)) """ def __init__(self, decimeters): self.decimeters = decimeters def __str__(self): return str(self.decimeters) + "dm" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceDecimeters(self.decimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.decimeters * DECIMETER_MM class DistanceMeters(DistanceValue): """ Distance in meters Args: meters (int): the number of meters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceMeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 meters md.run_for_distance(DistanceMeters(2), MotorSpeedDPS(100)) """ def __init__(self, meters): self.meters = meters def __str__(self): return str(self.meters) + "m" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceMeters(self.meters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.meters * METER_MM class DistanceInches(DistanceValue): """ Distance in inches Args: inches (int): the number of inches Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceInches, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 6 inches md.run_for_distance(DistanceInches(6), MotorSpeedDPS(100)) """ def __init__(self, inches): self.inches = inches def __str__(self): return str(self.inches) + "in" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceInches(self.inches * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.inches * INCH_MM class DistanceFeet(DistanceValue): """ Distance in feet Args: feet (int): the number of feet Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceFeet, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 3 feet md.run_for_distance(DistanceFeet(3), MotorSpeedDPS(100)) """ def __init__(self, feet): self.feet = feet def __str__(self): return str(self.feet) + "ft" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceFeet(self.feet * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.feet * FOOT_MM class DistanceYards(DistanceValue): """ Distance in yards Args: yards (int): the number of yards Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceYards, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 yards md.run_for_distance(DistanceYards(2), MotorSpeedDPS(100)) """ def __init__(self, yards): self.yards = yards def __str__(self): return str(self.yards) + "yd" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceYards(self.yards * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.yards * YARD_MM class DistanceStuds(DistanceValue): """ Distance in studs Args: studs (int): the number of LEGO studs Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 studs md.run_for_distance(DistanceStuds(6), MotorSpeedDPS(100)) """ def __init__(self, studs): self.studs = studs def __str__(self): return str(self.studs) + "stud" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceStuds(self.studs * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.studs * STUD_MM def distance_in_mm(distance): """ Args: distance (DistanceValue, int): the distance to convert to millimeters Returns: int: ``distance`` converted to millimeters Example: .. code:: python from spikedev.unit import DistanceFeet two_feet_in_mm = distance_in_mm(DistanceFeet(2)) """ if isinstance(distance, DistanceValue): return distance.mm # If distance is not a DistanceValue object, treat it as an int of mm elif isinstance(distance, (float, int)): return distance else: raise TypeError(type(distance))
students = [] class Student: school_name = "Springfied Elementary" def __init__(self, name, student_id=332): self.name = name self.student_id = student_id students.append(self) def __str__(self): return "Student " + self.name def get_name_capitalize(self): return self.name.capitalize() def get_school_name(self): return self.school_name class HighSchoolStudent(Student): school_name = "Springfirld High School" def get_school_name(self): return "This is a high school student" def get_name_capitalize(self): original_value = super().get_name_capitalize() return original_value + "-HS" james = HighSchoolStudent("james") print(james.get_name_capitalize())
data_A = [1,2,3,6,7,8,9] data_B = [1,2,7,8] count = 0 for number1 in data_A: for number2 in data_B: if number1 == number2: print('{} is also appeared in {}'.format(number1,number2)) count += 1 else: pass print('There are only {} matching numbers between Data A and Data B.'.format(count))
class Solution(object): def rotate(self, matrix): """ :type m: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m = matrix side = len(m) max_i = side - 1 for i in range(side // 2): y = i for j in range(max_i - i * 2): x = i + j m[y][x], m[x][max_i - y], m[max_i - y][max_i - x], m[max_i - x][y] = \ m[max_i - x][y], m[y][x], m[x][max_i - y], m[max_i - y][max_i - x]
# Publised to Explorer in private.py # Also used in measurement.py TEST_GROUPS = { "websites": ["web_connectivity"], "im": ["facebook_messenger", "signal", "telegram", "whatsapp"], "middlebox": ["http_invalid_request_line", "http_header_field_manipulation"], "performance": ["ndt", "dash"], "circumvention": [ "bridge_reachability", "meek_fronted_requests_test", "vanilla_tor", "tcp_connect", "psiphon", "tor", "torsf", "riseupvpn", ], "legacy": [ "http_requests", "dns_consistency", "http_host", "multi_protocol_traceroute", ], "experimental": [ "urlgetter", "dnscheck", ], } TEST_NAMES = [] for v in TEST_GROUPS.values(): assert isinstance(v, list) TEST_NAMES.extend(v) def get_test_group_case(): """ Returns a postgres CASE statement to return the test_group based on the value of test_name. """ c = "CASE\n" for tg_name, tests in TEST_GROUPS.items(): c += "WHEN test_name = ANY('{{{}}}') THEN '{}'\n".format( ",".join(tests), tg_name ) c += "ELSE 'unknown'\n" c += "END\n" return c
# -*- coding: utf-8 -*- class VertexNotReachableException(Exception): """ Exception for vertex distance and path """ pass
class Node: def __init__(self, value): self.value = value self.l = None self.r = None class BinaryTree: def __init__(self): self.root = None def draw(self): '''Prints a preorder traversal of the tree''' self._draw(self.root) print() def _draw(self, node): print("(", end="") if node != None: print(str(node.value) + ", ", end="") self._draw(node.l) print(", ", end="") self._draw(node.r) print(")", end="") def invert(self): self.root = self._invert(self.root) def _invert(self, node): # find lowest point where nodes can be swapped # swap nodes if node: node.l = self._invert(node.l) node.r = self._invert(node.r) temp = node.l node.l = node.r node.r = temp return node def add(self, vals): for val in vals: if self.root == None: self.root = Node(val) else: self._add(self.root, val) def _add(self, node, val): if val < node.value: if node.l == None: node.l = Node(val) else: self._add(node.l, val) else: if node.r == None: node.r = Node(val) else: self._add(node.r, val) def main(): t = BinaryTree() t.add([4, 2, 7, 1, 3, 6, 9, 11]) t.draw() t.invert() t.draw() if __name__ == "__main__": main()
# 1, 2, 3, 4, 5, 6, 7, 8, 9 # 0, 1, 1, -1, -1, 2, 2, -2, -2 # 0, 0, 1, 1, -1, -1, 2, 2, -2, -2 def seq(n): a = (n - 1) // 2 b = (n + 1) // 4 if a % 2 == 0: return -b else: return b n = int(input()) x = seq(n + 1) y = seq(n) print(x, y)
# 参考大佬的代码 class Solution: def trap(self, heights: List[int]) -> int: # left是左边最高的高度 # right是右边最高的高度 left_max = right_max = water = 0 left, right = 0, len(heights) - 1 while left <= right: left_max, right_max = max(left_max, heights[left]), max(right_max, heights[right]) while left <= right and heights[left] <= left_max <= right_max: water += left_max - heights[left] left += 1 while left <= right and heights[right] <= right_max <= left_max: water += right_max - heights[right] right -= 1 return water
W = [] S = str(input('')) for i in S: if i not in W: W.append(i) if len(W) % 2 == 0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
worldLists = { "desk": { "sets": ["desk"], "assume": ["des", "de"], }, "laptop": { "sets": ["laptop"], "assume": ["lapto", "lapt", "lap", "la"], }, "wall": { "sets": ["wall"], "assume": ["wal", "wa"] }, "sign": { "sets": ["sign"], "assume": ["sig", "si"], }, "door": { "sets": ["door"], "assume": ["doo", "do"], }, "chair": { "sets": ["chair"], "assume": ["chai", "cha", "ch",] }, "window": { "sets": ["window"], "assume": ["windo", "wind", "win", "wi"] }, "floor": { "sets": ["floor"], "assume": ["floo", "flo", "fl"] }, }
# Prova Mundo 02 # Rascunhos da Prova do Mundo 2 #Nota: 90% n = ' nilseia'.upper().strip()[0] print(n) for c in range(0, 10): print(c)
dnas = [ ['hY?9', 56, 25, 8.21, 47, 21, -2.56, {'ott_len': 43, 'ott_percent': 196, 'ott_bw': 124, 'tps_qty_index': 215}], ['st7M', 67, 43, 17.72, 55, 29, 5.52, {'ott_len': 49, 'ott_percent': 299, 'ott_bw': 84, 'tps_qty_index': 468}], ]
# This program contains a tuple stores the months of the year and # another tuple from it with just summer months # and prints out the summer months ine at a time. month = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") summer = month[4:7] for month in summer: print(month)
default_players = { 'hungergames': [ ("Marvel", True), ("Glimmer", False), ("Cato", True), ("Clove", False), ("Foxface", False), ("Jason", True), ("Rue", False), ("Thresh", True), ("Peeta", True), ("Katniss", False) ], 'melee': [ ("Dr. Mario", True), ("Mario", True), ("Luigi", True), ("Bowser", True), ("Peach", False), ("Yoshi", True), ("Donkey Kong", True), ("Captain Falcon", True), ("Ganondorf", True), ("Falco", True), ("Fox", True), ("Ness", True), ("Nana", False), ("Popo", True), ("Kirby", True), ("Samus", False), ("Zelda", False), ("Link", True), ("Young Link", True), ("Pichu", None), ("Pikachu", None), ("Jigglypuff", None), ("Mewtwo", True), ("Mr. Game & Watch", True), ("Marth", True), ("Roy", True) ] }
""" 7510. 고급 수학 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 88 ms 해결 날짜: 2020년 9월 24일 """ def main(): for i in range(1, int(input()) + 1): a, b, c = sorted(map(int, input().split())) print('Scenario #{}:\n{}\n'.format(i, 'yes' if a ** 2 + b ** 2 == c ** 2 else 'no')) if __name__ == '__main__': main()
def main(): N, M = map(int,input().split()) for i in range(1,N,2): print(("." + "|.."*int((i-1)/2) + "|" + "..|"*int((i-1)/2) + ".").center(M,'-')) print("WELCOME".center(M,"-")) for i in range(N-2,-1,-2): print(("." + "|.."*int((i-1)/2) + "|" + "..|"*int((i-1)/2) + ".").center(M,'-')) if __name__=='__main__': main()
""" Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Example 3: Input: s = "a" Output: "a" Example 4: Input: s = "ac" Output: "a" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters. """ def longestPalindrome(s: str) -> str: """ Time: O(n^2) Space: O(1) """ n = len(s) res = s[0] for i in range(1, n): left = i - 1 mid = i while s[left] == s[mid] and left >= 0 and mid < n: left -= 1 mid += 1 res = max(res, s[left + 1:mid], key=len) left = i - 1 right = i + 1 while left >= 0 and right < n and s[left] == s[right]: left -= 1 right += 1 res = max(res, s[left + 1:right], key=len) return res if __name__ == '__main__': # Test 1 s = "babad" print(longestPalindrome(s)) # Test 2 s = "cbbd" print(longestPalindrome(s)) # Test 3 s = "a" print(longestPalindrome(s)) # Test 4 s = "ac" print(longestPalindrome(s))
#!/usr/bin/env python3 tls_cnt = 0 ssl_cnt = 0 with open("input.txt",'r') as f: for line in f: bracket = 0 tls_flag = 0 ABAs = [[],[]] for i in range(len(line)-2): if line[i] == '[': bracket = 1 elif line[i] == ']': bracket = 0 else: if line[i] == line[i+2] and line[i+1] not in "]": ABAs[bracket].append(line[i:i+3]) if i < len(line)-3 and line[i:i+2] == line[i+3:i+1:-1] and line[i] != line[i+1]: if not bracket and tls_flag != 2: tls_flag = 1 else: tls_flag = 2 else: # for exited normally if tls_flag == 1: tls_cnt += 1 ABAs[0] = map(lambda s: s[1:]+s[1], ABAs[0]) if len(set(ABAs[0]).intersection(ABAs[1])) > 0: ssl_cnt += 1 print("TLS: {}".format(tls_cnt)) print("SSL: {}".format(ssl_cnt))
"""This module defines Ubuntu Bionic dependencies.""" load("@rules_deb_packages//:deb_packages.bzl", "deb_packages") def ubuntu_bionic_amd64(): deb_packages( name = "ubuntu_bionic_amd64", arch = "amd64", packages = { "base-files": "pool/main/b/base-files/base-files_10.1ubuntu2.11_amd64.deb", "bash": "pool/main/b/bash/bash_4.4.18-2ubuntu1.2_amd64.deb", "ca-certificates": "pool/main/c/ca-certificates/ca-certificates_20210119~18.04.2_all.deb", "coreutils": "pool/main/c/coreutils/coreutils_8.28-1ubuntu1_amd64.deb", "dash": "pool/main/d/dash/dash_0.5.8-2.10_amd64.deb", "fontconfig-config": "pool/main/f/fontconfig/fontconfig-config_2.12.6-0ubuntu2_all.deb", "fonts-dejavu-core": "pool/main/f/fonts-dejavu/fonts-dejavu-core_2.37-1_all.deb", "gzip": "pool/main/g/gzip/gzip_1.6-5ubuntu1.1_amd64.deb", "less": "pool/main/l/less/less_487-0.1_amd64.deb", "libacl1": "pool/main/a/acl/libacl1_2.2.52-3build1_amd64.deb", "libaio1": "pool/main/liba/libaio/libaio1_0.3.110-5ubuntu0.1_amd64.deb", "libattr1": "pool/main/a/attr/libattr1_2.4.47-2build1_amd64.deb", "libbz2-1.0": "pool/main/b/bzip2/libbz2-1.0_1.0.6-8.1ubuntu0.2_amd64.deb", "libc-bin": "pool/main/g/glibc/libc-bin_2.27-3ubuntu1.4_amd64.deb", "libc6": "pool/main/g/glibc/libc6_2.27-3ubuntu1.4_amd64.deb", "libdb5.3": "pool/main/d/db5.3/libdb5.3_5.3.28-13.1ubuntu1.1_amd64.deb", "libexpat1": "pool/main/e/expat/libexpat1_2.2.5-3ubuntu0.2_amd64.deb", "libffi6": "pool/main/libf/libffi/libffi6_3.2.1-8_amd64.deb", "libfontconfig1": "pool/main/f/fontconfig/libfontconfig1_2.12.6-0ubuntu2_amd64.deb", "libfreetype6": "pool/main/f/freetype/libfreetype6_2.8.1-2ubuntu2.1_amd64.deb", "libgcc1": "pool/main/g/gcc-8/libgcc1_8.4.0-1ubuntu1~18.04_amd64.deb", "libgcrypt20": "pool/main/libg/libgcrypt20/libgcrypt20_1.8.1-4ubuntu1.3_amd64.deb", "libgomp1": "pool/main/g/gcc-8/libgomp1_8.4.0-1ubuntu1~18.04_amd64.deb", "libgpg-error0": "pool/main/libg/libgpg-error/libgpg-error0_1.27-6_amd64.deb", "libjpeg-turbo8": "pool/main/libj/libjpeg-turbo/libjpeg-turbo8_1.5.2-0ubuntu5.18.04.4_amd64.deb", "liblcms2-2": "pool/main/l/lcms2/liblcms2-2_2.9-1ubuntu0.1_amd64.deb", "liblz4-1": "pool/main/l/lz4/liblz4-1_0.0~r131-2ubuntu3.1_amd64.deb", "liblzma5": "pool/main/x/xz-utils/liblzma5_5.2.2-1.3_amd64.deb", "libmpdec2": "pool/main/m/mpdecimal/libmpdec2_2.4.2-1ubuntu1_amd64.deb", "libncurses5": "pool/main/n/ncurses/libncurses5_6.1-1ubuntu1.18.04_amd64.deb", "libncursesw5": "pool/main/n/ncurses/libncursesw5_6.1-1ubuntu1.18.04_amd64.deb", "libpcre2-8-0": "pool/universe/p/pcre2/libpcre2-8-0_10.31-2_amd64.deb", "libpmem1": "pool/universe/p/pmdk/libpmem1_1.4.1-0ubuntu1~18.04.1_amd64.deb", "libpng16-16": "pool/main/libp/libpng1.6/libpng16-16_1.6.34-1ubuntu0.18.04.2_amd64.deb", "libpython3.6-minimal": "pool/main/p/python3.6/libpython3.6-minimal_3.6.9-1~18.04ubuntu1.6_amd64.deb", "libpython3.6-stdlib": "pool/main/p/python3.6/libpython3.6-stdlib_3.6.9-1~18.04ubuntu1.6_amd64.deb", "libreadline5": "pool/main/r/readline5/libreadline5_5.2+dfsg-3build1_amd64.deb", "libreadline7": "pool/main/r/readline/libreadline7_7.0-3_amd64.deb", "libselinux1": "pool/main/libs/libselinux/libselinux1_2.7-2build2_amd64.deb", "libsqlite3-0": "pool/main/s/sqlite3/libsqlite3-0_3.22.0-1ubuntu0.4_amd64.deb", "libssl1.1": "pool/main/o/openssl/libssl1.1_1.1.1-1ubuntu2.1~18.04.14_amd64.deb", "libstdc++6": "pool/main/g/gcc-8/libstdc++6_8.4.0-1ubuntu1~18.04_amd64.deb", "libsystemd0": "pool/main/s/systemd/libsystemd0_237-3ubuntu10.53_amd64.deb", "libtinfo5": "pool/main/n/ncurses/libtinfo5_6.1-1ubuntu1.18.04_amd64.deb", "libuuid1": "pool/main/u/util-linux/libuuid1_2.31.1-0.4ubuntu3.7_amd64.deb", "mime-support": "pool/main/m/mime-support/mime-support_3.60ubuntu1_all.deb", "ncurses-bin": "pool/main/n/ncurses/ncurses-bin_6.1-1ubuntu1.18.04_amd64.deb", "netbase": "pool/main/n/netbase/netbase_5.4_all.deb", "openssl": "pool/main/o/openssl/openssl_1.1.1-1ubuntu2.1~18.04.14_amd64.deb", "python3-distutils": "pool/main/p/python3-stdlib-extensions/python3-distutils_3.6.9-1~18.04_all.deb", "python3.6-minimal": "pool/main/p/python3.6/python3.6-minimal_3.6.9-1~18.04ubuntu1.6_amd64.deb", "readline-common": "pool/main/r/readline/readline-common_7.0-3_all.deb", "tar": "pool/main/t/tar/tar_1.29b-2ubuntu0.2_amd64.deb", "tzdata": "pool/main/t/tzdata/tzdata_2021e-0ubuntu0.18.04_all.deb", "zlib1g": "pool/main/z/zlib/zlib1g_1.2.11.dfsg-0ubuntu2_amd64.deb", }, packages_sha256 = { "base-files": "b103b55f80cc703af636cb111d80b733c71ba4c39a138ebe8926356d88173142", "bash": "4f95ed6e11435fccaa9731eaeb7688fed8cc1fd8a25d44640e2f7a25f871ae08", "ca-certificates": "911c7e57ad1ef49958f28dcc27bb19e0103465486cc7766023a68e78344b8c10", "coreutils": "24541a48e25dfb17c98ce77dda61800e6cd68d74c25725753613fbcc00f2418f", "dash": "51fe28b98b8e023325ae8868f29807cdb53f6f2eac943723b5e6bd47cde0cb2c", "fontconfig-config": "ba4dbb3b4c173c1d97b6112d736da25d2dc7fab0c7408eb3cb49207f43dd5630", "fonts-dejavu-core": "f2b3f7f51e23e0493e8e642c82003fe75cf42bc95fda545cc96b725a69adb515", "gzip": "46286e914cad985cfe8cb3f196b7fce48146d3b329d45673b6ad62e8ced034cb", "less": "00d9c5e56b81c95a14e3fd148ff464acaf3fe757d3e4b4d1e54990b28c54eb57", "libacl1": "adbe1a5b37daf02f7bbd645c3a0baf63f6607e207567574c609493c32d5d57a5", "libaio1": "01d780036ab15752b939637daa200517bafbd62ff73f91be5f94e77f42f7a7b0", "libattr1": "91ef5319ee1f0173a6c5d16ba364e79c90f74b94b5d7daed1a2674a92f4f9c78", "libbz2-1.0": "897850ec11aab3280ce2755eb552995a5aa9b16a70453934828c6418591ea87b", "libc-bin": "438aa7dc40dfa7c5ab51c1e726d63414bd5dad44954c8cbb75d6c3d73bbc0efe", "libc6": "46d39b8965f35457ce5db62662832c095fd7e01e72093da99ae025eb8e12bbe5", "libdb5.3": "abb7f569252604af9b123cd6c73195cbd54d7b7664479a85fd5fd12fe8ba3b5d", "libexpat1": "d700a358e8139b5f31c96a3caef452d62388c05f7cf4d6e4f448a06c2c2da122", "libffi6": "fa26945b0aadfc72ec623c68be9cc59235a7fe42e2388f7015fd131f4fb06dc9", "libfontconfig1": "647bb8f09e751a39d488b0260db6015ce1118c56114cc771dd5bf907180f0c80", "libfreetype6": "7f4afc6a8e7023ed51f15caf4d082e44e0f3926161afaeb7c4bb6326955255bd", "libgcc1": "116dadf4ceaba7150eb46a6598dd3defa62b1b2a6578fb494f4c932878634994", "libgcrypt20": "079025d334873844bba2aae474fe78f3eff3e04673302c91e4167916fd03efd2", "libgomp1": "2fb511a931d0510d22313fad065c951e04431d75d4e6160e1d80d29e88748c8a", "libgpg-error0": "afcf8629c4de6946d73661126ae4e0a28f9718c8720900201d46fd963e0b5ccf", "libjpeg-turbo8": "57f9879f3a23128ba3e9c348eb250b83996fa9ef16de947ab8eff74100f898da", "liblcms2-2": "a08e5e734bcb5a827772e326dad7c0411bbac9399f0f635edfa6b1f09ad80bdb", "liblz4-1": "deed1dc6d2c5b492b136fe23b0c6563f9fe9a9a016bd0c93abdb253cc97cfe67", "liblzma5": "92704fce1ad9af92d59052705d2e0e258789a1718afeca9c0fb0a0d37112b27a", "libmpdec2": "2962dbb81413ad47fee589bb6663589e38b84d80b4d55d8019f0b305025c5eb6", "libncurses5": "928109886a9c8a1a1504e5460632ba49cc0854176a90c16dcd95eb7ebd8d240d", "libncursesw5": "d1a7a32fe88181d6f5adf7c52cb981359aa35b01bdbbf7218ddc240a4fdabd87", "libpcre2-8-0": "37898dba2cc2cf5b87b47b1efb6cb2fda65f3a556f237bd3c30d5c2a8aa48fdd", "libpmem1": "25d3bf2e7c76d8588967e411667f3c2a6d442f6bb4c0bcdb8fa018891e782e06", "libpng16-16": "4d484ba67be62e7bb450ff41c88d06e65d564f9180daccc4a2640760493804bc", "libpython3.6-minimal": "ba0ae4d8a896e433124f462ceffc41009cfddae1e7006f49200d9776f7f21495", "libpython3.6-stdlib": "6b8b2dbb1e838808ae362de266b79ade1d7a78bdfd5be91031583df211f53bf2", "libreadline5": "dd851f543f3061d07c31fd44917865c3173ae9018ae331716787fbfcf1988bec", "libreadline7": "8706403267e95615f1b70db31ff16709361982728b308466346e01c20a743dd5", "libselinux1": "6b6c70f809e8b13f0b1f27006e125abb3a8c3195f5c888dce0df1a5d3f211c0d", "libsqlite3-0": "cde7a26502ecfeede865ce054763f4b6d3aa151bd8dcc5696e2725cfda5ceb07", "libssl1.1": "edeeb202b67936376e8fe483d7bc8d769a456eba2d100b272bb195b6e6d38cb3", "libstdc++6": "4dbd1ffa20011329608f584ff329a10507cfa78c3f76fa34e6f479f9680b64f4", "libsystemd0": "12ba25ece07fed5dae27e33daf701786d0b2589df141d751a25a99f136d8c9e2", "libtinfo5": "bb4d4d80720149692ea0d5bca1a5dac57737afe447810ce69dd4a95107121da5", "libuuid1": "c04350aa8dc1bd73712716f9826b0f02fa10b77058c990a406445020970c2eaa", "mime-support": "98e05aa03538c5f182ed14cbb59cfe64b30592d77e602abd2442a9f1c72532b3", "ncurses-bin": "336af3c372b6a7d083e6c6053670781369d8ae713fd098c9dab8fc5432458015", "netbase": "cbda1c8035cd1fe0b1fb09b456892c0bb868657bfe02da82f0b16207d391145e", "openssl": "c938fa9fb3a00e89a868e95c0faa76adafa0a53f1de122f22ccdfb4e4a074986", "python3-distutils": "f836b1e22923fa175c1968b9dbd916ae5639c9250e21bcfb88f9df2dc289f65c", "python3.6-minimal": "e30011c605816ab1d371c9f096caabaff8dabf87850207fd146aa05845b912c9", "readline-common": "84cb3642c82114496d2fc17011db13655bd661cf4641098c03c168ddde367908", "tar": "6bdbb90c9c073f8e8f92da231a2e553410ce397489f2f1f77d1ae8ddbd0c7bc4", "tzdata": "8ff68141a56b3fe97588a4e8ee02de7dfdacf2abbd4c23ed9ea793ba181ee479", "zlib1g": "2e6dafb986ee8ebbc4e1c344fab090a41710cab878fc9cd89336cdd1740518c5", }, sources = [ "http://us.archive.ubuntu.com/ubuntu bionic main universe", "http://us.archive.ubuntu.com/ubuntu bionic-updates main universe", "http://us.archive.ubuntu.com/ubuntu bionic-backports main universe", "http://security.ubuntu.com/ubuntu bionic-security main universe", ], urls = [ "http://us.archive.ubuntu.com/ubuntu/$(package_path)", "http://security.ubuntu.com/ubuntu/$(package_path)", "https://launchpad.net/ubuntu/+archive/primary/+files/$(package_file)", # Needed in case of superseded archive no more available on the mirrors ], )
# Configuration file for the Sphinx documentation builder. project = 'wwt_api_client' author = 'Peter K. G. Williams' copyright = '2019 ' + author release = '0.1.0dev0' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx_automodapi.automodapi', 'sphinx_automodapi.smart_resolver', 'numpydoc', ] master_doc = 'index' templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] numpydoc_class_members_toctree = False html_theme = 'alabaster' html_static_path = ['_static'] html_logo = 'images/logo.png'
class ConfigException(Exception): pass class AuthException(Exception): pass class AuthEngineFailedException(AuthException): pass class UnauthorizedAccountException(AuthException): pass class LockedUserException(UnauthorizedAccountException): pass class InvalidAuthEngineException(AuthException): pass class UserNotFoundException(AuthException): pass class NeedsOTPException(AuthException): pass class InvalidCredentialsException(AuthException): pass
def tick(nums): """ Simulate one tick of passage of time nums is a list of timer counts of all fish """ # Iterate over a copy of nums as it will be modified within the loop for i, j in enumerate(nums[:]): if j == 0: nums[i] = 6 nums.append(8) else: nums[i] -= 1 return nums def part1(): nums = list(map(int, open("in.txt").read().strip().split(","))) for i in range(80): nums = tick(nums) print(len(nums)) part1()
""" Copyright 2020 Tianshu AI Platform. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================= """ class FeatureHook(): def __init__(self, module): self.module = module self.feat_in = None self.feat_out = None self.register() def register(self): self._hook = self.module.register_forward_hook(self.hook_fn_forward) def remove(self): self._hook.remove() def hook_fn_forward(self, module, fea_in, fea_out): self.feat_in = fea_in[0] self.feat_out = fea_out
class Metadata: name: str def __init__(self, name: str): self.name = name def to_dict(self) -> dict: return { 'name': self.name, } class ConfigMap: metadata: Metadata data: dict apiVersion: str = 'v1' kind: str = 'ConfigMap' def __init__( self, metadata: Metadata, data: dict, apiVersion: str = 'v1', kind: str = 'ConfigMap', ): self.metadata = metadata self.data = data self.apiVersion = apiVersion self.kind = kind def to_dict(self) -> dict: return { 'metadata': self.metadata.to_dict(), 'data': self.data, 'apiVersion': self.apiVersion, 'kind': self.kind, } configMap = ConfigMap( metadata=Metadata(name='the-map'), data={'altGreeting': 'Good Morning!', 'enableRisky': 'false'}, )
# Creating a class # Method 1 # class teddy: # quantity = 200 # print(teddy.quantity) # Method 2 class teddy: quantity = 200 quality = 90 obteddy = teddy() print(obteddy.quality) print(obteddy.quantity)
# -*- coding: utf-8 -*- """ Created on Tue Oct 9 20:09:13 2018 @author: JinJheng """ a=input() b=input() c=input() d=input() print('|%10s %10s|' %(a,b)) print('|%10s %10s|' %(c,d)) print('|%-10s %-10s|' %(a,b)) print('|%-10s %-10s|' %(c,d))
num = 10 num = 20 num = 30 num = 40 num = 50 num = 66 num = 60 num = 70
def create_HMM(switch_prob=0.1, noise_level=1e-1, startprob=[1.0, 0.0]): """Create an HMM with binary state variable and 1D Gaussian measurements The probability to switch to the other state is `switch_prob`. Two measurement models have mean 1.0 and -1.0 respectively. `noise_level` specifies the standard deviation of the measurement models. Args: switch_prob (float): probability to jump to the other state noise_level (float): standard deviation of measurement models. Same for two components Returns: model (GaussianHMM instance): the described HMM """ n_components = 2 startprob_vec = np.asarray(startprob) # STEP 1: Transition probabilities transmat_mat = np.array([[1. - switch_prob, switch_prob], [switch_prob, 1. - switch_prob]]) # # np.array([[...], [...]]) # STEP 2: Measurement probabilities # Mean measurements for each state means_vec = np.array([-1.0, 1.0]) # Noise for each state vars_vec = np.ones(2) * noise_level * noise_level # Initialize model model = GaussianHMM1D( startprob = startprob_vec, transmat = transmat_mat, means = means_vec, vars = vars_vec, n_components = n_components ) return model def sample(model, T): """Generate samples from the given HMM Args: model (GaussianHMM1D): the HMM with Gaussian measurement T (int): number of time steps to sample Returns: M (numpy vector): the series of measurements S (numpy vector): the series of latent states """ # Initialize S and M S = np.zeros((T,),dtype=int) M = np.zeros((T,)) # Calculate initial state S[0] = np.random.choice([0,1],p=model.startprob) # Latent state at time `t` depends on `t-1` and the corresponding transition probabilities to other states for t in range(1,T): # STEP 3: Get vector of probabilities for all possible `S[t]` given a particular `S[t-1]` transition_vector = model.transmat[S[t-1],:] # Calculate latent state at time `t` S[t] = np.random.choice([0,1],p=transition_vector) # Calculate measurements conditioned on the latent states # Since measurements are independent of each other given the latent states, we could calculate them as a batch means = model.means[S] scales = np.sqrt(model.vars[S]) M = np.random.normal(loc=means, scale=scales, size=(T,)) return M, S # Set random seed np.random.seed(101) # Set parameters of HMM T = 100 switch_prob = 0.1 noise_level = 2.0 # Create HMM model = create_HMM(switch_prob=switch_prob, noise_level=noise_level) # Sample from HMM M, S = sample(model,T) assert M.shape==(T,) assert S.shape==(T,) # Print values print(M[:5]) print(S[:5])
#!/usr/bin/env python3 def find_distance(matrix, key): """Find the distance of the nearest key for each cell """ if not matrix or not matrix[0]: return matrix rows, cols = len(matrix), len(matrix[0]) delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] def shortest(matrix, row, col, key): q = [(row, col, 0)] while q: r, c, d = q.pop(0) if matrix[r][c] == key: return d else: for i, j in delta: nr, nc = r+i, c+j if 0 <= nr < rows and 0 <= nc < cols: q.append((nr, nc, d+1)) result = [[0] * cols for _ in range(rows)] for r in range(rows): for c in range(cols): result[r][c] = shortest(matrix, r, c, key) return result if __name__ == '__main__': matrix = [input().split() for _ in range(int(input()))] print(find_distance(matrix, '0'))
""" Utilities for the :class:`~django_mri.analysis.interfaces.fmriprep.fmriprep.FmriPrep` interface. """ #: Command line template to format for execution. COMMAND = "singularity run -e {security_options} -B {bids_parent}:/work,{destination_parent}:/output,{freesurfer_license}:/fs_license {singularity_image_root}/fmriprep-{version}.simg /work/{bids_name} /output/{destination_name} {analysis_level} --fs-license-file /fs_license" # noqa: E501 #: Default FreeSurfer home directory. FREESURFER_HOME: str = "/usr/local/freesurfer" #: "Flags" indicate parameters that are specified without any arguments, i.e. #: they are a switch for some binary configuration. FLAGS = ( "skip_bids_validation", "low-mem", "anat-only", "boilerplate_only", "md-only-boilerplate", "error-on-aroma-warnings", "longitudinal", "force-bbr", "force-no-bbr", "medial-surface-nan", "use-aroma", "return-all-components", "skull-strip-fixed-seed", "fmap-bspline", "fmap-no-demean", "use-syn-sdc", "force-syn", "no-submm-recon", "fs-no-reconall", "clean-workdir", "resource-monitor", "reports-only", "write-graph", "stop-on-first-crash", "notrack", "sloppy", ) #: Dictionary of expeected outputs by key. OUTPUTS = { # Anatomicals "native_T1w": ["fmriprep", "anat", "desc-preproc_T1w.nii.gz"], "native_brain_mask": ["fmriprep", "anat", "desc-brain_mask.nii.gz"], "native_parcellation": ["fmriprep", "anat", "*dseg.nii.gz"], "native_csf": ["fmriprep", "anat", "label-CSF_probseg.nii.gz"], "native_gm": ["fmriprep", "anat", "label-GM_probseg.nii.gz"], "native_wm": ["fmriprep", "anat", "label-WM_probseg.nii.gz"], "standard_T1w": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz", ], "standard_brain_mask": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz", ], "standard_parcellation": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_dseg.nii.gz", ], "standard_csf": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_label-CSF_probseg.nii.gz", ], "standard_gm": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_label-GM_probseg.nii.gz", ], "standard_wm": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_label-WM_probseg.nii.gz", ], "native_to_mni_transform": [ "fmriprep", "anat", "from-T1w_to-MNI152NLin2009cAsym_mode-image_xfm.h5", ], "mni_to_native_transform": [ "fmriprep", "anat", "from-MNI152NLin2009cAsym_to-T1w_mode-image_xfm.h5", ], "native_to_fsnative_transform": [ "fmriprep", "anat", "from-T1w_to-fsnative_mode-image_xfm.txt", ], "fsnative_to_native_transform": [ "fmriprep", "anat", "from-fsnative_to-T1w_mode-image_xfm.txt", ], "smoothwm": ["fmriprep", "anat", "hemi-*_smoothwm.surf.gii"], "pial": ["fmriprep", "anat", "hemi-*_pial.surf.gii"], "midthickness": ["fmriprep", "anat", "hemi-*_midthickness.surf.gii"], "inflated": ["fmriprep", "anat", "hemi-*_inflated.surf.gii"], # Functionals "native_boldref": ["fmriprep", "func", "*space-T1w_desc-boldref.nii.gz"], "native_func_brain_mask": [ "fmriprep", "func", "*space-T1w_desc-brain_mask.nii.gz", ], "native_preproc_bold": [ "fmriprep", "func", "*space-T1w_desc-preproc_bold.nii.gz", ], "native_aparc_bold": [ "fmriprep", "func", "*space-T1w_desc-aparcaseg_dseg.nii.gz", ], "native_aseg_bold": [ "fmriprep", "func", "*space-T1w_desc-aseg_dseg.nii.gz", ], "standard_boldref": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-boldref.nii.gz", ], "standard_func_brain_mask": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz", ], "standard_preproc_bold": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz", ], "standard_aparc_bold": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-aparcaseg_dseg.nii.gz", ], "standard_aseg_bold": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-aseg_dseg.nii.gz", ], "confounds_tsv": ["fmriprep", "func", "*desc-confound_timeseries.tsv"], "confounds_json": ["fmriprep", "func", "*desc-confound_timeseries.json"], "freesurfer_T1": ["freesurfer", "mri", "T1.mgz"], "freesurfer_rawavg": ["freesurfer", "mri", "rawavg.mgz"], "freesurfer_orig": ["freesurfer", "mri", "orig.mgz"], "freesurfer_nu": ["freesurfer", "mri", "nu.mgz"], "freesurfer_norm": ["freesurfer", "mri", "norm.mgz"], "freesurfer_aseg": ["freesurfer", "mri", "aseg.mgz"], "freesurfer_aseg_stats": ["freesurfer", "stats", "aseg.stats"], "freesurfer_brain": ["freesurfer", "mri", "brain.mgz"], "freesurfer_brainmask": ["freesurfer", "mri", "brainmask.mgz"], "freesurfer_filled": ["freesurfer", "mri", "filled.mgz"], "freesurfer_wm": ["freesurfer", "mri", "wm.mgz"], "freesurfer_wmparc": ["freesurfer", "mri", "wmparc.mgz"], "freesurfer_wmparc_stats": ["freesurfer", "stats", "wmparc.stats"], "freesurfer_BA_stats": ["freesurfer", "stats", ".BA_exvivo*.stats"], # TODO: Finish outputs dictionary. }
val = open('val.txt', encoding='UTF-8') out = open('out.txt', encoding='UTF-8') t = val.readline() a = out.readline() sum = 0 right = 0 while t and a: error = [] t = t.strip() a = a.strip() for i in range(len(t)): sum += 1 if t[i] == a[i]: right += 1 else: error.append(a[i]) print(t) print(a) print("wrong with {}", format(error)) t = val.readline() a = out.readline() print("right={}".format(right)) print("sum={}".format(sum)) print(right / sum)
#!/usr/bin/env python3 @app.route('/api/v1/weight', methods=['GET']) def weight_v1(): conn = None try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor) cur.execute("""SELECT * FROM weights WHERE child_id={};""".format(request.args['child_id'])) ans = cur.fetchall() if (len(ans) == 0): return jsonify({'code':204, 'name':'No content', 'key':''}) ans1 = [] for row in ans: ans1.append(dict(row)) return jsonify(ans1) except (Exception, psycopg2.DatabaseError) as error: return str(error) finally: if conn is not None: conn.close()
URL_FANTOIR = ( "https://www.collectivites-locales.gouv.fr/competences/la-mise-disposition-gratuite-du-fichier-des-" "voies-et-des-lieux-dits-fantoir" ) URL_DOCUMENTATION = "https://docs.3liz.org/QgisCadastrePlugin/"
class JavascriptDebugRenderer: def __init__(self, debugger): self.debugger = debugger def render(self, meta=None): data = {} if meta is None: meta = [] for name, collector in self.debugger.collectors.items(): data.update({collector.name: collector.collect()}) return """ <div class="fixed inset-x bottom-0 h-72 bg-white border border-top border-gray-300 w-full overflow-auto" x-data="bar"> <nav class="relative z-0 flex divide-x divide-gray-300 bg-gray-100" aria-label="Tabs"> <template x-for="tab in tabs"> <!-- Current: "text-gray-900", Default: "text-gray-500 hover:text-gray-700" --> <!-- class="text-gray-500 hover:text-gray-700 group relative min-w-0 flex-1 overflow-hidden bg-white py-4 px-4 text-sm font-medium text-center hover:bg-gray-50 focus:z-10"> --> <a x-on:click="setTab(tab)" class="text-gray-700 cursor-pointer max-w-min group relative min-w-0 flex-1 overflow-hidden py-1 px-3 text-sm font-base text-center hover:bg-gray-50 focus:z-10" > <span x-text="tab"></span> <!-- <span aria-hidden="true" class="bg-red-500 absolute inset-x-0 bottom-0 h-0.5"></span> --> <span aria-hidden="true" class="absolute inset-x-0 bottom-0 h-0.5" :class="currentTab == tab ? 'bg-red-500' : 'bg-transparent'" ></span> </a> </template> </nav> <!-- content --> <div> <!-- TODO later: it will be html --> <template x-for="(object, index) in currentContent"> <div> <span x-html="object.html"></span> </div> </template> </div> </div> <script> document.addEventListener('alpine:init', () => { Alpine.data('bar', function () { return { rawData: {}, tabs: [], content: [], currentTab: this.$persist("python"), currentContent: "", init() { // TODO: Load JSON debugbar payload of last request this.getRequestData() }, async getRequestData(id = null) { //this.rawData = await (await fetch(`/_debugbar/${id}/`)).json(); this.rawData = await (await fetch("/_debugbar/")).json() this.tabs = this.rawData.collectors this.content = this.rawData.data this.currentContent = this.getTabContent(this.currentTab) }, setTab(tab) { this.currentTab = tab this.currentContent = this.getTabContent(tab) }, getTabContent(tab) { return this.content[tab].data } } }) }) </script> """
n = int(input('digite um numero: ')) if n%2 == 0: print('PAR') else: print('IMPAR')
#Factorial Number Calc num = int(input("Digite um número inteiro positivo para fazer o fatorial: ")) resultado = 1 nTemp = 1 if num < 0: #Colocar outro while print("! Por Favor, digite um número positivo maior que 0 !") elif num == 1 and num == 0: print("O Fatorial de ", num, " é -> 1") else: while( nTemp <= num): resultado *= nTemp nTemp += 1 print("O Fatorial de ", num, " é -> ", resultado)
# -*- coding: utf-8 -*- """ File Name: reversePairs Author : jing Date: 2020/4/24 https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/ 逆序对 """ class Solution: def reversePairs(self, nums) -> int: """ 小到大排序,每次取最小的,那么它在原list中的位置就代表的它前面有多少个比他大的 然后删除掉当前最小,取下一个最小 超时了 :param nums: :return: """ if nums is None or len(nums) < 2: return 0 sorted_nums = sorted(nums) count = 0 for num in sorted_nums: index = nums.index(num) count += index nums.remove(num) return count def reversePairs2(self, nums) -> int: """ 归并 排序 :param nums: :return: """ global cnt cnt = 0 self.guibing(nums) return cnt % 1000000007 def guibing(self, data): global cnt if len(data) == 1: return data mid = len(data) // 2 left = self.guibing(data[:mid]) right = self.guibing(data[mid:]) i = 0 j = 0 res = [] while i < len(left) and j < len(right): if left[i] <= right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) cnt += len(left) - i # 计算逆序对的数量 j += 1 res += left[i:] res += right[j:] return res print(Solution().reversePairs2([1, 3, 2, 3, 1]))
''' You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3. ''' def arrangeCoins2(n): count = 1 while n > 0: print("*"*count) n -= count if n >= 0: count +=1 return count - 1 def arrangeCoins3(n): i = 1 while n>=i: n, i = n-i, i+1 return i-1 def arrangeCoins(n): print("*"*8) start = 0 end = n while start+1<end: mid = start + (end-start)//2 total = (mid+1)*mid//2 print("mid and total ", mid, total) if total == n: return mid elif total < n: start = mid else: end = mid print("start nad end ", start, end) if (end+1)*end//2 <= n: return end else: return start
ir_licenses = { 'names': { 'P': 'Pro', 'A': 'Class A', 'B': 'Class B', 'C': 'Class C', 'D': 'Class D', 'R': 'Rookie' }, 'bg_colors': { 'P': '#000000', 'A': '#0153DB', 'B': '#00C702', 'C': '#FEEC04', 'D': '#FC8A27', 'R': '#FC0706' }, 'colors': { 'P': '#FFFFFF', 'A': '#FFFFFF', 'B': '#FFFFFF', 'C': '#000000', 'D': '#000000', 'R': '#FFFFFF' } } content = { 'bg_colors': { 'owned': '#1E9E1E', 'missing': '#40474C', 'twitter': '#1DA1F2', 'github': '#333000', 'paypal': '#003087' }, 'colors': { 'normal': 'black', 'alt': '#DDDDDD', 'owned': 'black', 'missing': '#DDDDDD', 'twitter': '#FFFFFF', 'github': '#FAFAFA', 'paypal': '#009CDE' } }
pkg_dnf = { 'nfs-utils': {}, 'libnfsidmap': {}, } svc_systemd = { 'nfs-server': { 'needs': ['pkg_dnf:nfs-utils'], }, 'rpcbind': { 'needs': ['pkg_dnf:nfs-utils'], }, 'rpc-statd': { 'needs': ['pkg_dnf:nfs-utils'], }, 'nfs-idmapd': { 'needs': ['pkg_dnf:nfs-utils'], }, } files = {} actions = { 'nfs_export': { 'command': 'exportfs -a', 'triggered': True, 'needs': ['pkg_dnf:nfs-utils'], }, } for export in node.metadata['nfs-server']['exports']: files['/etc/exports.d/{}'.format(export['alias'])] = { 'source': 'template', 'mode': '0644', 'content_type': 'mako', 'context': { 'export': export, }, 'needs': ['pkg_dnf:nfs-utils'], 'triggers': ['action:nfs_export', 'svc_systemd:nfs-server:restart', 'svc_systemd:rpcbind:restart'], } if node.has_bundle('firewalld'): if node.metadata.get('nfs-server', {}).get('firewalld_permitted_zones'): for zone in node.metadata.get('nfs-server', {}).get('firewalld_permitted_zones'): actions['firewalld_add_nfs_zone_{}'.format(zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd_zone_{}'.format(zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind_zone_{}'.format(zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } elif node.metadata.get('firewalld', {}).get('default_zone'): default_zone = node.metadata.get('firewalld', {}).get('default_zone') actions['firewalld_add_nfs_zone_{}'.format(default_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd_zone_{}'.format(default_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind_zone_{}'.format(default_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } elif node.metadata.get('firewalld', {}).get('custom_zones', False): for interface in node.metadata['interfaces']: custom_zone = node.metadata.get('interfaces', {}).get(interface).get('firewalld_zone') actions['firewalld_add_nfs_zone_{}'.format(custom_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd_zone_{}'.format(custom_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind_zone_{}'.format(custom_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } else: actions['firewalld_add_nfs'] = { 'command': 'firewall-cmd --permanent --add-service=nfs', 'unless': 'firewall-cmd --list-services | grep nfs', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd'] = { 'command': 'firewall-cmd --permanent --add-service=mountd', 'unless': 'firewall-cmd --list-services | grep mountd', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind'] = { 'command': 'firewall-cmd --permanent --add-service=rpc-bind', 'unless': 'firewall-cmd --list-services | grep rpc-bind', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], }
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ m, q, n = len(A), len(B), len(B[0]) # C = [[0] * n] * m C = [[0] * n for _ in range(m)] for i in range(m): for k in range(q): if A[i][k]: for j in range(n): if B[k][j]: C[i][j] += A[i][k] * B[k][j] return C
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here n, q = map(int, input().strip().split()) a = list(map(int, input().strip().split())) for _ in range(q): x, y = map(int, input().strip().split()) if x == y: print(0) else: ans = n - 1 matched_idx = init_idx = None for i in range(n): if a[i] == x or a[i] == y: if matched_idx is None: matched_idx = init_idx = i else: if a[i] != a[matched_idx]: ans = min(ans, (i - matched_idx) // 2) matched_idx = i if a[init_idx] != a[matched_idx]: ans = min(ans, (init_idx - (matched_idx - n)) // 2) print(ans)
# FIXME need to figure generation of bytecode class Scenario: STAGES = [ {"name": "install", "path": "build/{version}/cast_to_short-{version}.cap",}, { "name": "send", "comment": "READMEM APDU", "payload": "0xA0 0xB0 0x01 0x00 0x00", "optional": False, }, ]
class SalesforceRouter(object): """ A router to control all database operations on models in the salesforce application. """ def db_for_read(self, model, **hints): """ Attempts to read salesforce models go to salesforce. """ if model._meta.app_label == 'salesforce': return 'salesforce' return None def db_for_write(self, model, **hints): """ Attempts to write salesforce models go to salesforce. """ if model._meta.app_label == 'salesforce': return 'salesforce' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the salesforce app is involved. """ if obj1._meta.app_label == 'salesforce' or \ obj2._meta.app_label == 'salesforce': return True return None def allow_migrate(self, db, model): """ Make sure the salesforce app only appears in the 'salesforce' database. """ if db == 'salesforce': return False elif model._meta.app_label == 'salesforce': return False return None
class Solution: def calPoints(self, ops: List[str]) -> int: arr = [] for op in ops: #print(arr) if op.isdigit() or op[0] == '-': arr.append(int(op)) elif op == 'C' and arr: arr.pop() elif op == 'D' and arr: arr.append(arr[-1] * 2) elif len(arr) >= 2: arr.append(arr[-1] + arr[-2]) #print(arr) return sum(arr)
# 153. Find Minimum in Rotated Sorted Array class Solution(object): global find_min_helper def find_min_helper(nums,left,right): # base case: if left >= right, return the first element if left >= right: return nums[0] # get middle element mid = (left+right)/2 # check if mid < right and mid element > mid+1 if mid < right and nums[mid] > nums[mid+1]: # return mid+1 element return nums[mid+1] # check if mid > left and mid element < mid-1 element if mid > left and nums[mid] < nums[mid-1]: return nums[mid] # check if mid < right and mid element < mid+1 if nums[mid] < nums[right]: # return function(nums,mid+1,right) return find_min_helper(nums,left,mid-1) # return function(nums,left, mid) return find_min_helper(nums,mid+1,right) def findMin(self, nums): # if nums length is 1, return first element if len(nums) == 1: return nums[0] if len(nums) == 2: return min(nums) # return the helper function (log n) binary search return find_min_helper(nums,0,len(nums)-1)
#Exercício070 total = 0 maisdemil = 0 contador = 0 barato = 0 nomebarato = '' print('\033[31m--------------------------') print('\033[32m>>>>>ATACADÃO DO M0Z1<<<<<') print('\033[31m--------------------------') while True: #Realiza a repetição para continuar cadastrando produtos produto = str(input('\033[32mNome do produto: \033[m')).capitalize() preco = float(input('\033[32mPreço: \033[m')) while True: #Realiza a repetição apenas para o caso do usuário errar na digitação continua = str(input('\033[31mQuer continuar? [S/N]: \033[m')).strip().upper()[0] if continua == 'S' or continua == 'N': #Se usuário digitar corretamente, interrompe a repetição break print('\033[31m--------------------------') contador += 1 #Realiza a contagem de produtos total += preco #Realiza a soma dos produtos if preco > 1000: #Realiza a contagem dos produtos com preço maior que 1000 maisdemil += 1 if contador == 1: #O primeiro preço torna-se o mais barato no cadastro do primeiro produto barato = preco nomebarato = produto #Nomeia o protudo mais barato como o primeiro if barato > preco: #Indica se o proximo preço for mais barato barato = preco nomebarato = produto #Nomeia o mais barato como o proximo caso essa seja a situação if continua == 'N': #Interrompe a repetição caso usuário indique que não quer continuar break print('\033[31m>>>>>>>FIM DA COMPRA<<<<<<') print(f'\033[32mTOTAL DA COMPRA: \033[mR$: {total:.2f}') print(f'\033[m{maisdemil} \033[32mprodutos custam mais de R$: 1000.00') print(f'\033[32mO produto mais barato foi \033[m{nomebarato} \033[32mque custa R$: \033[m{barato:.2f}') print('\033[32mxD\033[m')
# Configuration file for ipython. #------------------------------------------------------------------------------ # InteractiveShellApp(Configurable) configuration #------------------------------------------------------------------------------ ## lines of code to run at IPython startup. c.InteractiveShellApp.exec_lines = ['%load_ext autoreload', '%autoreload 2'] ## A list of dotted module names of IPython extensions to load. c.InteractiveShellApp.extensions = ['autoreload']
#!/usr/bin/env python3 size_of_grp = 5 inp_list = "1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2".split() set_l = set(inp_list) cap_room = "" for element in set_l: inp_list.remove(element) if not element in inp_list: cap_room = element break print(int(cap_room))
class InferErr(Exception): def __init__(self, e): self.code = 1 self.message = "Inference Error" super().__init__(self.message, str(e)) def MiB(val): return val * 1 << 20 def GiB(val): return val * 1 << 30 class HostDeviceMem(object): def __init__(self, host_mem, device_mem): self.host = host_mem self.device = device_mem def __str__(self): return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device) def __repr__(self): return self.__str__()
GPU_ID = 0 BATCH_SIZE = 64 VAL_BATCH_SIZE = 100 NUM_OUTPUT_UNITS = 3000 # This is the answer vocabulary size MAX_WORDS_IN_QUESTION = 15 MAX_WORDS_IN_EXP = 36 MAX_ITERATIONS = 50000 PRINT_INTERVAL = 100 # what data to use for training TRAIN_DATA_SPLITS = 'train' # what data to use for the vocabulary QUESTION_VOCAB_SPACE = 'train' ANSWER_VOCAB_SPACE = 'train' EXP_VOCAB_SPACE = 'train' # VQA pretrained model VQA_PRETRAINED = 'PATH_TO_PRETRAINED_VQA_MODEL.caffemodel' # location of the data VQA_PREFIX = './VQA-X' DATA_PATHS = { 'train': { 'ques_file': VQA_PREFIX + '/Questions/v2_OpenEnded_mscoco_train2014_questions.json', 'ans_file': VQA_PREFIX + '/Annotations/v2_mscoco_train2014_annotations.json', 'exp_file': VQA_PREFIX + '/Annotations/train_exp_anno.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/train2014/COCO_train2014_' }, 'val': { 'ques_file': VQA_PREFIX + '/Questions/v2_OpenEnded_mscoco_val2014_questions.json', 'ans_file': VQA_PREFIX + '/Annotations/v2_mscoco_val2014_annotations.json', 'exp_file': VQA_PREFIX + '/Annotations/val_exp_anno.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/val2014/COCO_val2014_' }, 'test-dev': { 'ques_file': VQA_PREFIX + '/Questions/OpenEnded_mscoco_test-dev2015_questions.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/test2015/COCO_test2015_' }, 'test': { 'ques_file': VQA_PREFIX + '/Questions/OpenEnded_mscoco_test2015_questions.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/test2015/COCO_test2015_' } }
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def largest_prime_factor(): i = 2 lst = [] number = 600851475143 while i != number: if number % i == 0: lst.append(i) number /= i i = 2 else: i += 1 lst.append(i) return lst[-1] if __name__ == '__main__': print(largest_prime_factor())
state_dict = {} aug_dict = {} oneof_dict = {} def clear_dict(state): skey = 'session' if skey not in list(state_dict.keys()) or state != state_dict[skey]: state_dict.clear() state_dict.update({'session': state}) aug_dict.clear()
def reduce_to_one_dividing_by_one_or_pm_one(n): """ Given n this function computes the minimum number of operations 1. Divide by 2 when even 2. Add or subtract 1 when odd to reduce n to 1. The n input is supposed to be a string containing the decimal representation of the actual number. Original problem statement: Fuel Injection Perfection ========================= Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly. Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time. The fuel control mechanisms have three operations: 1) Add one fuel pellet 2) Remove one fuel pellet 3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets) Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. For example: solution(4) returns 2: 4 -> 2 -> 1 solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit Solution.java Test cases ========== Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Python cases -- Input: solution.solution('15') Output: 5 Input: solution.solution('4') Output: 2 -- Java cases -- Input: Solution.solution('4') Output: 2 Input: Solution.solution('15') Output: 5 """ count = 0 while not n == 1: if not n & 1: # Divisible by 2, then divide. n //= 2 else: if (n == 3) or (n_minus_1 % 4 == 1): # Subtracting 1 will give two # divisions by 2 afterwards. # The case n = 3 gives only one zero but # that one division by 2 finishes it. n -= 1 else: # Adding 1 will create at least # two divisions by 2. n += 1 count += 1 return count
# Given an array, cyclically rotate the array clockwise by one. def rotateCyclic(a): start = 0 end = 1 while(end != len(a)): temp = a[start] a[start] = a[end] a[end] = temp end += 1 a = [1,2,3,4,5,6] rotateCyclic(a) print(a)
""" You are given two arrays a1,a2,…,an and b1,b2,…,bn. In each step, you can set ai=ai−bi if ai≥bi. Determine the minimum number of steps that are required to make all a's equal. Input format First line: n Second line: a1,a2,…,an Third line: b1,b2,…,bn Output format Print the minimum number of steps that are required to make all a's equal. If it is not possible, then print -1. """ def sub(a, b): count = j = 0 while j < len(a): mini = min(a) while a[j] > mini: a[j] -= b[j] count += 1 if a[j] < mini: mini = a[j] j = 0 else: j = j + 1 for j in range(n): assert a[j] > 0, 'No Solution' return count n = int(input('Enter number of numbers:')) a1 = [] b1 = [] for i in range(n): a1.append(int(input('Enter A\'s' + str(i + 1) + ' Number:'))) for i in range(n): b1.append(int(input('Enter B\'s' + str(i + 1) + ' Number:'))) for i in range(n): assert a1[i] > b1[i], 'Invalid Input' print(sub(a1, b1))
# -*- coding: utf-8 -*- # Aprimore a classe do exercício anterior para adicionar o método aumentarSalario (porcentualDeAumento) # que aumente o salário do funcionário em uma certa porcentagem. class Funcionario(object): def __init__(self, nome, salario): self.nome = nome.title() self.salario = salario def aumentar_salario(self, porcentagem): self.salario += self.salario * (porcentagem / 100) def __str__(self): return """ ╔════════╤═════════════╗ ║ Nome │ Salario(R$) ║ ╟────────┼─────────────╢ ║ {:<6.6} │ {:<11.2f} ║ ╚════════╧═════════════╝ """.format(self.nome, self.salario) if __name__ == '__main__': nome = input('Nome: ') salario = float(input('Salário: ')) funcionario = Funcionario(nome, salario) porcentagem = int(input('Aumentar o salário em: ')) funcionario.aumentar_salario(porcentagem) print(funcionario)
'''Leia o nome completo de uma pessoa e mostre: O nome com todas as letras maiúsculas O nome com todas as letras minusculas Quantas letras ao todo, sem considerar os espaços Quantas letras tem o primeiro nome''' nome = str(input('Escreva seu nome: ')).strip() print(nome.upper()) print(nome.lower()) print(len(nome) - nome.count(' ')) #print(len(nome.replace(' ', ''))) '''dividido = nome.split()''' '''dividido2 = dividido[0]''' '''print(len(dividido[0]))''' print(nome.find(' '))
s = 'hello world' y =[] for i in s.split(' '): x=i[0].upper() + i[1:] y.append(x) z= ' '.join(y) print(z)
def removeTheLoop(head): ##Your code here if detectloop(head)==0: return one=head two=head while(one and two and two.next): one=one.next two=two.next.next #print(one.data,two.data) if one==two: f=one break #print(f.data) temp=head while(temp!=f): if temp.next==f.next: #print(temp.next.data,f.next.data) f.next=None break else: temp=temp.next f=f.next return True
#!usr/bin/env python3 def main(): print('Reading text files') f = open('lines.txt') # open returns a file object, that's an iterator. by default it opens in read & text mode for line in f: print(line.rstrip()) # Return a copy of the string with trailing whitespace removed print('\nWriting text files') infile = open('lines.txt', 'rt') # open in read mode and text mode outfile = open('lines-copy.txt', 'wt') # open in write mode and text mode for line in infile: print(line.rstrip(), file=outfile) print('.', end='', flush=True) # flushes the output buffer so we ensure we print the "." properly outfile.close() # to prevent any data loss when exiting the main function print('\ndone.') print('\nWriting binary files') infile = open('berlin.jpg', 'rb') # open in read mode and binary mode outfile = open('berlin-copy.jpg', 'wb') # open in write mode and binary mode while True: buffer = infile.read(10240) # 10k bytes if buffer: # is going to be false when is empty outfile.write(buffer) print('.', end='', flush=True) # each "." represents 10k bytes read and written else: break outfile.close() print('\ndone.') if __name__ == '__main__': main() # CONSOLE OUTPUT: # Reading text files # 01 The first line. # 02 The second line. # 03 The third line. # 04 The fourth line. # 05 The fifth line. # 06 The sixth line. # 07 The seventh line. # 08 The eight line. # 09 The ninth line. # 10 The tenth line. # # Writing text files # .......... # done. # # Writing binary files # ..................................................... # done.
def mcd(a, b): if a > b: small = b else: small = a for i in range(1, small+1): if((a % i == 0) and (b % i == 0)): mcd1 = i return mcd1 a = int(input("intrduzca un numero:")) b = int(input("intrduzca un segundo numero:")) print ("The mcd is : ",end="") print (mcd(a,b)) #lo que hacemos es asignar cual de los dos es el menor de los valores y por cada numero contenido entre el # 1 y el menor de los valores, dividimos ambos numeros entre todos aquellos hasta que damos un valor para # el que ambos son divisores exactos ( el mayor de estos ya que varios daran de resto 0 pero el # mayor el que nos interesa) y ese seria el mcd.
""" entradas cantidadmetros-->m-->float salidas metrosapulgadas-->pu-->float mmetrosapies-->pi-->float """ #entradas m=float(input("Ingrese la cantidad de metros: ")) #caja negra pu=round((m*39.27), 2) pi=round((pu/12), 2) #salidas print(m, " metros equivalen a ", pu, " pulgadas y ", pi, " pies")
# MenuTitle: Display all kerning group members # -*- coding: utf-8 -*- __doc__ = """ Opens a tab containing all the members of the currently selected glyphs kerning groups. """ Glyphs.clearLog() # Glyphs.showMacroWindow() lefts = dict((g.parent.leftKerningGroup, []) for g in Glyphs.font.selectedLayers if g.parent.leftKerningGroup) rights = dict((g.parent.rightKerningGroup, []) for g in Glyphs.font.selectedLayers if g.parent.rightKerningGroup) for g in Glyphs.font.glyphs: try: lefts[g.leftKerningGroup].append(g.name) except KeyError: pass try: rights[g.rightKerningGroup].append(g.name) except KeyError: pass # thisGlyph = Glyphs.font.selectedLayers[0].parent # leftGroup = ['/' + g.name for g in Glyphs.font.glyphs if g.leftKerningGroup == thisGlyph.leftKerningGroup] # rightGroup = ['/' + g.name for g in Glyphs.font.glyphs if g.rightKerningGroup == thisGlyph.rightKerningGroup] # print rightGroup strings = [] strings.append('Leftside Kerning Group(s):\n' + '\n'.join([' '.join(map(lambda x: '/' + x, gn)) for gn in sorted(lefts.values())])) strings.append('Rightside Kerning Group(s):\n' + '\n'.join([' '.join(map(lambda x: '/' + x, gn)) for gn in sorted(rights.values())])) string = '\n\n'.join(strings) if string: Glyphs.font.newTab(string)