content
stringlengths
7
1.05M
JWT_SECRET_KEY = "e75a9e10168350b2a8869a8eb8a0f946a15eec8452048c0b51923f98ea9ea43b" JWT_ALGORITHM = "HS256" JWT_EXPIRATION_TIME_MINUTES = 60 * 24 * 5 TOKEN_DESCRIPTION = "It checks username and password if they are true, it returns JWT token to you." TOKEN_SUMMARY = "It returns JWT Token." ISBN_DESCRIPTION = "It is unique identifier for books."
load(":rollup_js_result.bzl", "RollupJsResult") def _impl(ctx): node_executable = ctx.attr.node_executable.files.to_list()[0] rollup_script = ctx.attr.rollup_script.files.to_list()[0] module_name = ctx.attr.module_name node_modules_path = rollup_script.path.split("/node_modules/")[0] + "/node_modules" exports = ctx.attr.exports dep_files = [] for d in ctx.attr.deps: dep_files.extend(d.files.to_list()) entrypoint_js_file = ctx.actions.declare_file("%s-entrypoint.js" % module_name) vendor_import_entries = [] for export_name in exports: vendor_import_entries.append("import * as %s from '%s'" % (exports[export_name], export_name)) vendor_entrypoint_content = \ "\n".join(vendor_import_entries) + \ "\n\n" + \ "export default {\n" + \ ",\n".join(exports.values()) + \ "}\n" ctx.actions.write( output=entrypoint_js_file, content=vendor_entrypoint_content) dest_file = ctx.actions.declare_file(module_name + ".js") sourcemap_file = ctx.actions.declare_file(module_name + ".js.map") # transitive deps are not properly imported without the includePaths fix, detailed here: # https://github.com/rollup/rollup-plugin-node-resolve/issues/105#issuecomment-332640015 rollup_config_content = """ const path = require('path'); import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve'; import includePaths from 'rollup-plugin-includepaths'; import sourcemaps from 'rollup-plugin-sourcemaps'; import replace from 'rollup-plugin-replace' export default { input: '%s', output: { file: '%s', format: 'iife', sourcemap: true, sourcemapFile: '%s', name: '%s', intro: 'const global = window' }, plugins: [ sourcemaps(), resolve({ preferBuiltins: false, }), commonjs(), replace({ "process.env.NODE_ENV": JSON.stringify( "production" ) }) ], onwarn(warning) { if (['UNRESOLVED_IMPORT', 'MISSING_GLOBAL_NAME'].indexOf(warning.code)>=0) { console.error(warning.message) process.exit(1) } else { console.warn(warning.message) } } }; """ % ( entrypoint_js_file.path, dest_file.path, sourcemap_file.path, module_name, ) rollup_config_file = ctx.actions.declare_file("%s-rollup-config.js" % module_name) ctx.actions.write( output=rollup_config_file, content=rollup_config_content) ctx.actions.run_shell( command="ln -s %s node_modules;env NODE_PATH=node_modules %s %s -c %s" % ( node_modules_path, node_executable.path, rollup_script.path, rollup_config_file.path, ), inputs=dep_files, outputs = [dest_file, sourcemap_file], progress_message = "running rollup js '%s'..." % module_name, tools = [ node_executable, rollup_script, rollup_config_file, entrypoint_js_file, ] + ctx.attr.rollup_plugins.files.to_list() + dep_files ) return [ DefaultInfo(files=depset([dest_file, sourcemap_file])), RollupJsResult(js_file=dest_file, sourcemap_file=sourcemap_file), ] rollup_js_vendor_bundle = rule( implementation = _impl, attrs = { "module_name": attr.string(mandatory=True), "exports": attr.string_dict(), "deps": attr.label_list(), "node_executable": attr.label(allow_files=True, mandatory=True), "rollup_script": attr.label(allow_files=True, mandatory=True), "rollup_plugins": attr.label(mandatory=True), } )
''' A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17") Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. Example: solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" ''' def solution(args): out = [] beg = end = args[0] for n in args[1:] + [""]: if n != end + 1: if end == beg: out.append(str(beg)) elif end == beg + 1: out.extend([str(beg), str(end)]) else: out.append(str(beg) + "-" + str(end)) beg = n end = n return ",".join(out) # '-6,-3-1,3-5,7-11,14,15,17-20' if __name__ == '__main__': print(solution(([-60, -58, -56])))
class Pattern_Seven: '''Pattern seven * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' def __init__(self, strings='*', steps=10): self.steps = steps if isinstance(strings, str): self.strings = strings else: # If provided 'strings' is integer then converting it to string self.strings = str(strings) def method_one(self): print('Method One') for i in range(1, self.steps): joining_word = ' '.join(self.strings * i) print(joining_word.center(len(joining_word) * 2).rstrip(' ')) def method_two(self): print('\nMethod Two') steps = 1 while steps != self.steps: joining_word = ' '.join(self.strings * steps) print(joining_word.center(len(joining_word) * 2).rstrip(' ')) steps += 1 if __name__ == '__main__': pattern_seven = Pattern_Seven() pattern_seven.method_one() pattern_seven.method_two()
# Example 1: # Input: haystack = "hello", needle = "ll" # Output: 2 # Example 2: # Input: haystack = "aaaaa", needle = "bba" # Output: -1 # Example 3: # Input: haystack = "", needle = "" # Output: 0 class Solution: def strStr(self, haystack: str, needle: str) -> int: return haystack.find(needle)
#!/usr/bin/env python3 for file_name in ['file_ignored_by_git_included_explicitly', 'file_managed_by_git']: with open(file_name) as f: print(f.read(), end='') for file_name in ['file_managed_by_git_excluded', 'file_ignored_by_git']: try: with open(file_name) as f: raise Exception(f'File {file_name} shouldn\'t be here') except FileNotFoundError: pass
# https://leetcode.com/problems/ugly-number/ # # Write a program to check whether a given number is an ugly number. # # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # # Note that 1 is typically treated as an ugly number. # # Credits: # Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False def defactor(num, n): while num % n == 0: num = num / n return num num = defactor(num, 2) num = defactor(num, 3) num = defactor(num, 5) if num == 1: return True else: return False
#! usr/bin/python3 """ This is the python script used to download few codechef questions from the website. Put them in the correct place as the structure demands like beginner questions in beginner and so on. Add the question statement as a Readme.md for each question and the link to the question. <Add the features of @SuperCodeBot on telegram.> """
captcha="428122498997587283996116951397957933569136949848379417125362532269869461185743113733992331379856446362482129646556286611543756564275715359874924898113424472782974789464348626278532936228881786273586278886575828239366794429223317476722337424399239986153675275924113322561873814364451339186918813451685263192891627186769818128715595715444565444581514677521874935942913547121751851631373316122491471564697731298951989511917272684335463436218283261962158671266625299188764589814518793576375629163896349665312991285776595142146261792244475721782941364787968924537841698538288459355159783985638187254653851864874544584878999193242641611859756728634623853475638478923744471563845635468173824196684361934269459459124269196811512927442662761563824323621758785866391424778683599179447845595931928589255935953295111937431266815352781399967295389339626178664148415561175386725992469782888757942558362117938629369129439717427474416851628121191639355646394276451847131182652486561415942815818785884559193483878139351841633366398788657844396925423217662517356486193821341454889283266691224778723833397914224396722559593959125317175899594685524852419495793389481831354787287452367145661829287518771631939314683137722493531318181315216342994141683484111969476952946378314883421677952397588613562958741328987734565492378977396431481215983656814486518865642645612413945129485464979535991675776338786758997128124651311153182816188924935186361813797251997643992686294724699281969473142721116432968216434977684138184481963845141486793996476793954226225885432422654394439882842163295458549755137247614338991879966665925466545111899714943716571113326479432925939227996799951279485722836754457737668191845914566732285928453781818792236447816127492445993945894435692799839217467253986218213131249786833333936332257795191937942688668182629489191693154184177398186462481316834678733713614889439352976144726162214648922159719979143735815478633912633185334529484779322818611438194522292278787653763328944421516569181178517915745625295158611636365253948455727653672922299582352766484" # captcha="123123" def check(val, next): if val == next: return int(val) else: return 0 def two(): sum = 0 dist = int(len(captcha) / 2) for i, d in enumerate(captcha): # print("i={}; d={}; i+dist={}; i + dist - len(captcha)={}".format(i,d,(i + dist),(i + dist - len(captcha)))) if i + dist > len(captcha) - 1: next = captcha[(i + dist - len(captcha))] else: next = captcha[(i + dist)] sum += check(d, next) print("sum is {}".format(sum)) def one(): sum = 0 for i, d in enumerate(captcha): # print("i={}; d={}".format(i,d)) if i == len(captcha) - 1: next = captcha[0] else: next = captcha[i] sum += check(d, next) print("sum is {}".format(sum)) def main(): # one() two() if __name__ == "__main__": main()
class Metric: def __init__(self): pass def update(self, outputs, target): raise NotImplementedError def value(self): raise NotImplementedError def name(self): raise NotImplementedError def reset(self): pass
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com). { 'name': 'Peru - Accounting', 'description': """ Peruvian accounting chart and tax localization. According the PCGE 2010. ======================================================================== Plan contable peruano e impuestos de acuerdo a disposiciones vigentes de la SUNAT 2011 (PCGE 2010). """, 'author': ['Cubic ERP'], 'category': 'Localization', 'depends': ['account'], 'data': [ 'data/l10n_pe_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_pe_chart_post_data.xml', 'data/account_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.xml', ], }
"""Proper parenthetics.""" def lisp_parens_with_count(parens): """Output with count to see whether parens are open(1), broken(-1), or balanced(0).""" open_count = 0 for par in parens: if par == '(': open_count elif par == ')': open_count -= 1 if open_count < 0: return -1 if open_count == 0: return 0 else: return 1 def lisp_parens_with_stack(parens): """Output with stack to see whether parens are open(1), broken(-1), or balanced(0).""" open_stack = [] for par in parens: if par == '(': open_stack.append(par) if par == ')': try: open_stack.pop() except IndexError: return -1 if open_stack: return 1 else: return 0
## Local ems economic dispatch computing format # Diesel generator set PG = 0 RG = 1 # Utility grid set PUG = 2 RUG = 3 # Bi-directional convertor set PBIC_AC2DC = 4 PBIC_DC2AC = 5 # Energy storage system set PESS_C = 6 PESS_DC = 7 RESS = 8 EESS = 9 # Neighboring MG set PMG = 10 # Emergency curtailment or shedding set PPV = 11 PWP = 12 PL_AC = 13 PL_UAC = 14 PL_DC = 15 PL_UDC = 16 # Total number of decision variables NX = 17
def find(n): l = [''] * (n + 1) size = 1 m = 1 while (size <= n): i = 0 while(i < m and (size + i) <= n): l[size + i] = "1" + l[size - m + i] i += 1 i = 0 while(i < m and (size + m + i) <= n): l[size + m + i] = "2" + l[size - m + i] i += 1 m = m << 1 size = size + m print(l[n]) for _ in range(int(input())): find(int(input()))
# -*- coding: utf-8 -*- class warehouse: def __init__(self, location, product): self.location = location self.deliveryPoints = list() self.allProducts = product self.wishlist = list() self.excessInventory = [] self.allProducts = self.convertInv(self.allProducts) def take(self,item): for i in xrange(0, len(self.excessInventory)): if item == self.excessInventory[i]: self.excessInventory.pop(i) self.allProducts.pop(i) return true return false def inventoryCheck(self): self.excessInventory = self.allProducts for i in self.deliveryPoints: for j in i.productIDsRequired: found = False for k in xrange(0, len(self.excessInventory)): if k == j: del excessInventory[k] found = True break if found != True: self.wishlist.append(j) def convertInv(self,before): before = map(int, before) after = [] for i in xrange(0, len(before)): for j in xrange(0, before[i]): after.append(i) return after
# dummy variables for flake8 # see: https://github.com/patrick-kidger/torchtyping/blob/master/FURTHER-DOCUMENTATION.md batch = None channels = None time = None behavior = None annotator = None classes = None
T = input() soma = 0 matriz = [] for i in range(0,12,+1): linha = [] for j in range(0,12,+1): numeros = float(input()) linha.append(numeros) matriz.append(linha) contagem = 0 pegaNum = 0 for i in range(1, 12,+1): #linha for j in range(0, i, +1): pegaNum = float(matriz[i][j]) contagem+=1 soma = soma + pegaNum if T == "S": print("{:.1f}".format(soma)) else: media = soma/contagem print("{:.1f}".format(media))
"""A library to help interacting with omegaUp. This is composed of two modules: - [**`omegaup.api`**](./omegaup/api/) helps interacting with [omegaUp's API](https://github.com/omegaup/omegaup/blob/master/frontend/server/src/Controllers/README.md) and is auto-generated with correct types and the docstrings straight from the code. - [**`omegaup.validator`**](./omegaup/validator/) has runtime helper functions to aid in problem validation. """
# -*- coding: utf-8 -*- """ cli structs module. """ class CLIGroups: """ cli groups class. each cli handler group will be registered with its relevant group name. usage example: `python cli.py alembic upgrade --arg value` `python cli.py babel extract --arg value` `python cli.py template package` `python cli.py celery worker --arg value` `python cli.py security token --arg value` """ pass
#!/usr/bin/env python3 def word_frequencies(filename="src/alice.txt"): with open(filename, "r") as f: lines = f.readlines() d = {} for line in lines: words = line.split() for word in words: word = word.strip("""!"#$%&'()*,-./:;?@[]_""") if d.get(word) != None: d[word] += 1 else: d[word] = 1 return d def main(): d = word_frequencies() for line in d: print(line, d[line]) if __name__ == "__main__": main()
class REQUEST_MSG(object): TYPE_FIELD = "type" GET_ID = "get-id" CONNECT_NODE = "connect-node" AUTHENTICATE = "authentication" HOST_MODEL = "host-model" RUN_INFERENCE = "run-inference" LIST_MODELS = "list-models" DELETE_MODEL = "delete-model" DOWNLOAD_MODEL = "download-model" SYFT_COMMAND = "syft-command" PING = "socket-ping" class RESPONSE_MSG(object): NODE_ID = "id" INFERENCE_RESULT = "prediction" MODELS = "models" ERROR = "error" SUCCESS = "success"
valid_passwords = 0 with open('input.txt', 'r') as f: for line in f: min_max, letter_colon, password = line.split() pmin, pmax = [int(c) for c in min_max.split('-')] letter = letter_colon[0:1] # remove colon password = ' ' + password # account for 1-indexing matching_chars = 0 if password[pmin] == letter: matching_chars += 1 if password[pmax] == letter: matching_chars += 1 if matching_chars == 1: # exactly one match valid_passwords += 1 # print(f"{pmin} | {pmax} | {letter} | {password} | {num_letters}") print(valid_passwords)
class Globee404NotFound(Exception): def __init__(self): super().__init__() self.message = 'Payment Request returned 404: Not Found' def __str__(self): return self.message class Globee422UnprocessableEntity(Exception): def __init__(self, errors): super().__init__() self.message = 'Payment Request returned 422:' self.errors = errors or [] def __str__(self): ret = '%s\n' % self.message for error in self.errors: ret += '\ttype: %s\n' % error['type'] ret += '\textra: %s\n' % error['extra'] ret += '\tfield: %s\n' % error['field'] ret += '\tmessage: %s\n' % error['message'] return ret class GlobeeMissingCredentials(Exception): def __init__(self, missing_key_name): super().__init__() self.message = "The '%s' is missing!" % missing_key_name def __str__(self): return self.message
class BaseExchangeContactService(object): def __init__(self, service, folder_id): self.service = service self.folder_id = folder_id def get_contact(self, id): raise NotImplementedError def new_contact(self, **properties): raise NotImplementedError class BaseExchangeContactItem(object): _id = None _change_key = None _service = None folder_id = None _track_dirty_attributes = False _dirty_attributes = set() # any attributes that have changed, and we need to update in Exchange first_name = None last_name = None full_name = None display_name = None sort_name = None email_address1 = None email_address2 = None email_address3 = None birthday = None job_title = None department = None company_name = None office_location = None primary_phone = None business_phone = None home_phone = None mobile_phone = None def __init__(self, service, id=None, xml=None, folder_id=None, **kwargs): self.service = service self.folder_id = folder_id if xml is not None: self._init_from_xml(xml) elif id is None: self._update_properties(kwargs) else: self._init_from_service(id) def _init_from_xml(self, xml): raise NotImplementedError def _init_from_service(self, id): raise NotImplementedError def create(self): raise NotImplementedError def update(self): raise NotImplementedError def delete(self): raise NotImplementedError @property def id(self): """ **Read-only.** The internal id Exchange uses to refer to this folder. """ return self._id @property def change_key(self): """ **Read-only.** When you change a contact, Exchange makes you pass a change key to prevent overwriting a previous version. """ return self._change_key def _update_properties(self, properties): self._track_dirty_attributes = False for key in properties: setattr(self, key, properties[key]) self._track_dirty_attributes = True def __setattr__(self, key, value): """ Magically track public attributes, so we can track what we need to flush to the Exchange store """ if self._track_dirty_attributes and not key.startswith(u"_"): self._dirty_attributes.add(key) object.__setattr__(self, key, value) def _reset_dirty_attributes(self): self._dirty_attributes = set() def validate(self): """ Validates that all required fields are present """ if not self.display_name: raise ValueError("Folder has no display_name") if not self.parent_id: raise ValueError("Folder has no parent_id")
# coding: utf-8 n, t = [int(i) for i in input().split()] queue = list(input()) for i in range(t): queue_new = list(queue) for j in range(n-1): if queue[j]=='B' and queue[j+1]=='G': queue_new[j], queue_new[j+1] = queue_new[j+1], queue_new[j] queue = list(queue_new) print(''.join(queue))
### global constants ### hbar = None ### dictionary for hbar ### hbars = {'ev': 0.658229, 'cm': 5308.8, 'au': 1.0 } ### energy units ### conv = {'ev': 0.0367493, 'cm': 4.556e-6, 'au': 1.0, 'fs': 41.3413745758, 'ps': 41.3413745758*1000.} ### mass units ### me2au = 0.00054858 # amu/m_e ### distance units ### ang2bohr = 1.88973 # bohr/ang def convert_to(unit): """ """ return conv[unit] def convert_from(unit): """ """ return 1./conv[unit]
# Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This # provides a helpful message to anyone still trying to use port 8000. # Based upon # https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#the-first-wsgi-application html_response = b''' <html> <head><title>System configuration error</title></head> <body> <h1>System configuration error</h1> <p>Please contact the administrator of this server.</p> <p style="border: 0.1em solid black; padding: 0.5em">If you are the administrator of this server: KoBoCAT received this request on port 8000, when 8001 should have been used. Please see <a href="https://github.com/kobotoolbox/kobo-docker/issues/301"> https://github.com/kobotoolbox/kobo-docker/issues/301</a> for more information.</p> <p>Thanks for using KoBoToolbox.</p></body></html> ''' def application(env, start_response): start_response('503 Service Unavailable', [('Content-Type','text/html')]) return [html_response]
class Action: def __init__(self, num1: float, num2: float): self.num1 = num1 self.num2 = num2 class History: def __init__(self, goldenNums: list, userActs: dict): self.goldenNums = goldenNums self.userActs = userActs class Game: def __init__(self): self.goldenNums = [] self.userActs = {} self.round = 0 self.scores = {} self.userNum = 0 def initUsers(self, users: list): """Initialize players""" self.userNum = len(users) for name in users: self.userActs[name] = [] self.scores[name] = 0 def beginRound(self): """Start a new round""" self.round += 1 def endRound(self): """End current round and judge for scores""" sm = 0 cnt = 0 for acts in self.userActs.values(): if len(acts) == self.round: sm += acts[-1].num1 + acts[-1].num2 cnt += 2 avg = 0.618 * (sm / cnt) self.goldenNums.append(avg) if self.userNum >= 2: mn, mnName = 200, set() mx, mxName = -200, set() for name, acts in self.userActs.items(): if len(acts) == self.round: x, y = abs(acts[-1].num1-avg), abs(acts[-1].num2-avg) if x < mn: mn = x mnName.clear() mnName.add(name) elif x == mn: mnName.add(name) if x > mx: mx = x mxName.clear() mxName.add(name) elif x == mx: mxName.add(name) if y < mn: mn = y mnName.clear() mnName.add(name) elif y == mn: mnName.add(name) if y > mx: mx = y mxName.clear() mxName.add(name) elif y == mx: mxName.add(name) for name in mnName: self.scores[name] += self.userNum - 2 for name in mxName: self.scores[name] += -2 for acts in self.userActs.values(): if len(acts) != self.round: acts.append(Action(0, 0)) def getHistory(self) -> History: """Gets history""" return History(self.goldenNums, self.userActs) def userAct(self, name: str, action: Action) -> bool: """Do a user action""" if (not (0 < action.num1 < 100)) or (not (0 < action.num2 < 100)): return False if name not in self.userActs: return False if len(self.userActs[name]) == self.round: return False self.userActs[name].append(action) return True
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/14 14:58 # @Author : Baimohan/PH # @Site : https://github.com/BaiMoHan # @File : varargs3.py # @Software: PyCharm def test(x, y, z=3, *books, **scores): # **代表收集关键字参数 print(x, y, z) print(books) # 收集参数保存的是元组 print(scores) # 对于关键字参数保存的是字典形式 if __name__ == '__main__': test(1, 2, 3, 'fluent phthon', 'first python', Chinese=89, Math=36) test(1, 2, Chinese=88, Englishi=88)
PORT = 8050 DEBUG = True DASH_TABLE_PAGE_SIZE = 5 DEFAULT_WAVELENGTH_UNIT = "angstrom" DEFAULT_FLUX_UNIT = "F_lambda" LOGS = { "do_log":True, "base_logs_directory":"/base/logs/directory/" } MAX_NUM_TRACES = 30 CATALOGS = { "sdss": { "base_data_path":"/base/data/path/", "api_url":"http://skyserver.sdss.org/public/SkyServerWS/SearchTools/SqlSearch", "example_specid":"2947691243863304192" } }
def show_urls( urllist, depth=0 ): for entry in urllist: if ( hasattr( entry, 'namespace' ) ): print( "\t" * depth, entry.pattern.regex.pattern, "[%s]" % entry.namespace ) else: print( "\t" * depth, entry.pattern.regex.pattern, "[%s]" % entry.name ) if hasattr( entry, 'url_patterns' ): show_urls( entry.url_patterns, depth + 1 )
def area(l, c): return f'A área do terreno {l}x{c} é de {l * c:.2f} m²' print(area(float(input('Qual a largura do terreno? ')), float(input('Qual o comprimento do terreno? '))))
class DictToObject(object): def __init__(self, dictionary): def _traverse(key, element): if isinstance(element, dict): return key, DictToObject(element) else: return key, element objd = dict(_traverse(k, v) for k, v in dictionary.items()) self.__dict__.update(objd)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- MAX_SEQUENCE_LENGTH = 800 MAX_NB_WORDS = 20000 EMBEDDING_DIM = 50 #300 VALIDATION_SPLIT = 0.2 TEST_SPLIT = 0.10 K=10 #10 EPOCHES=100 #100 OVER_SAMPLE_NUM = 800 UNDER_SAMPLE_NUM = 500 ACTIVATION_M = 'sigmoid' LOSS_M = 'binary_crossentropy' OPTIMIZER_M = 'adam' ACTIVATION_S = 'softmax' LOSS_S = 'categorical_crossentropy' OPTIMIZER_S = 'rmsprop' head_short=['Func.','Conc.', 'Dire.', 'Purp.', 'Qual.', 'Cont.', 'Stru.', 'Patt.', 'Exam.', 'Envi.', 'Refe.', 'Non-Inf.'] head_medica = ['Class-0-593_70,Class-1-079_99,Class-2-786_09,Class-3-759_89,Class-4-753_0,Class-5-786_2,Class-6-V72_5,Class-7-511_9,Class-8-596_8,Class-9-599_0,Class-10-518_0,Class-11-593_5,Class-12-V13_09,Class-13-791_0,Class-14-789_00,Class-15-593_1,Class-16-462,Class-17-592_0,Class-18-786_59,Class-19-785_6,Class-20-V67_09,Class-21-795_5,Class-22-789_09,Class-23-786_50,Class-24-596_54,Class-25-787_03,Class-26-V42_0,Class-27-786_05,Class-28-753_21,Class-29-783_0,Class-30-277_00,Class-31-780_6,Class-32-486,Class-33-788_41,Class-34-V13_02,Class-35-493_90,Class-36-788_30,Class-37-753_3,Class-38-593_89,Class-39-758_6,Class-40-741_90,Class-41-591,Class-42-599_7,Class-43-279_12,Class-44-786_07']
{"tablejoin_id": 204, "matched_record_count": 156, "layer_join_attribute": "TRACT", "join_layer_id": "641", "worldmap_username": "rp", "unmatched_records_list": "", "layer_typename": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "join_layer_url": "/data/geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "join_layer_typename": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "table_name": "boston_income_01tab_1_1", "tablejoin_view_name": "join_boston_census_blocks_0zm_boston_income_01tab_1_1", "unmatched_record_count": 0, "layer_link": "http://localhost:8000/data/geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "table_id": 330, "table_join_attribute": "tract", "llbbox": "[-71.1908629979881,42.2278900020655,-70.9862559993925,42.3987970008647]", "map_image_link": "http://localhost:8000/download/wms/641/png?layers=geonode%3Ajoin_boston_census_blocks_0zm_boston_income_01tab_1_1&width=658&bbox=-71.190862998%2C42.2278900021%2C-70.9862559994%2C42.3987970009&service=WMS&format=image%2Fpng&srs=EPSG%3A4326&request=GetMap&height=550", "layer_name": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "embed_map_link": "http://localhost:8000/maps/embed/?layer=geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1"}
""" network-structure of vgg16 excludes fully-connection layer date: 9/17 author: arabian9ts """ # structure of convolution and pooling layer up to fully-connection layer """ size-format: [ [ convolution_kernel ], [ bias ] ] [ [ f_h, f_w, in_size, out_size ], [ out_size ] ] """ structure = { # convolution layer 1 'conv1_1': [[3, 3, 3, 64], [64]], 'conv1_2': [[3, 3, 64, 64], [64]], # convolution layer 2 'conv2_1': [[3, 3, 64, 128], [128]], 'conv2_2': [[3, 3, 128, 128], [128]], # convolution layer 3 'conv3_1': [[3, 3, 128, 256], [256]], 'conv3_2': [[3, 3, 256, 256], [256]], 'conv3_3': [[3, 3, 256, 256], [256]], # convolution layer 4 'conv4_1': [[3, 3, 256, 512], [512]], 'conv4_2': [[3, 3, 512, 512], [512]], 'conv4_3': [[3, 3, 512, 512], [512]], # convolution layer 5 'conv5_1': [[3, 3, 512, 512], [512]], 'conv5_2': [[3, 3, 512, 512], [512]], 'conv5_3': [[3, 3, 512, 512], [512]], # fully-connection 6 'fc6': [[4096, 0, 0, 0], [4096]], # fully-connection 7 'fc7': [[4096, 0, 0, 0], [4096]], # fully-connection 8 'fc8': [[1000, 0, 0, 0], [1000]], # for cifar 'cifar': [[512, 0, 0, 0], [512]], } # kernel_size is constant, so defined here ksize = [1, 2, 2, 1,] # convolution-layer-strides is already below conv_strides = [1, 1, 1, 1,] # pooling-layer-strides is already below pool_strides = [1, 2, 2, 1,]
""" Set of tools to work with different observations. """ __all__ = ["hinode", "iris"]
def wiki_json(name): name = name.strip().title() url = 'https://en.wikipedia.org/w/api.php?action=query&titles={0}&continue=&prop=categories&format=json'.format(name) return url def categories(response): return response.json()["query"]["pages"].values()[0]["categories"] def is_ambiguous(dic): for item in dic: if 'disambiguation' in item["title"]: return True return False def is_dead(dic): for item in dic: if 'deaths' in item["title"]: return True return False def was_born(dic): for item in dic: if 'births' in item["title"]: return True return False
""" IPv4 was the first publicly used Internet Protocol. It used 4-byte addresses and permitted 232 distinct values. The typical format for an IPv4 address is A.B.C.D where A, B, C, and D are integers in the inclusive range between 0 and 255. IPv6, with 128 bits, was developed to permit the expansion of the address space. These addresses are represented by eight colon-separated sixteen-bit groups, where each sixteen-bit group is written using 1 to 4 hexadecimal digits. Leading zeroes in a section are often omitted from an address, meaning that the groups 0 is identical to 0000 and group 5 is identical to 0005. Some examples of valid IPv6 addresses are 2001:0db8:0000:0000:0000:ff00:0042:8329 and 3:0db8:0:01:F:ff0:0042:8329. Given n strings of text that may or may not be valid Internet Protocol (IP) addresses, we want to determine whether each string of text is: An IPv4 address. An IPv6 address. Neither an IPv6 address nor an IPv4 address. Complete the checkIP function in the editor below. It has one parameter: an array of strings, ip, where each element i denotes a string of text to be checked. It must return an array of strings where each element i contains the answer for ipi; each answer must be whichever of the following case-sensitive terms is appropriate: IPv4 if the string is a valid IPv4 address. IPv6 if the string is a valid IPv6 address. Neither if the string is not a valid IPv4 or IPv6 address. Input Format Locked stub code in the editor reads the following input from stdin and passes it to the function: The first line contains an integer, n, denoting the number of elements in ip. Each line i of the n subsequent lines (where 0 ≤ i < n) contains a string describing ipi. Constraints 1 ≤ n ≤ 50 1 ≤ ipi ≤ 500 It is guaranteed that any string containing a valid IPv4 or IPv6 address has no leading or trailing whitespace. Output Format The function must return an array of strings where each element i contains the string IPv4, IPv6, or Neither, denoting that ipi was an IPv4 address, an IPv6 address, or Neither (i.e., not an address at all). This is printed to stdout by locked stub code in the editor. Sample Input 0 2 This line has junk text. 121.18.19.20 Sample Output 0 Neither IPv4 Explanation 0 We must check the following n = 2 strings: ip0 = "This line has junk text." is not a valid IPv4 or IPv6 address, so we return Neither in index 0 of our return array. ip1 = "121.18.19.20" is a valid IPv4 address, so we return IPv4 in index 1 of our return array. Sample Input 1 1 2001:0db8:0000:0000:0000:ff00:0042:8329 Sample Output 1 IPv6 Explanation 1 We only have n = 1 value to check. Because ip0 = "2001:0db8:0000:0000:0000:ff00:0042:8329" is a valid IPv6 address, we return IPv6 in index 0 of our return array. """ #IP VERIFIER, DETERMINES IF IT IS REAL IPV4 or IPV6 def checkIP(ip): lst = list() #list containing verification results correct_parts = False all_are_numbers=False for index in ip: IPv4_parts = index.split(".") #splits the "IP" into a list of parts based on the IPv4 prototcol. IPv6_parts = index.split(":") #splits the "IP" into a list of parts based on the IPv6 protocol. if len(index) > 1 and len(IPv4_parts) == 4 or len(IPv6_parts) == 8: #check to see if the IPs have the correct lengths if len(IPv4_parts) == 4: #further filtering into specific IPv4 verification for i in IPv4_parts: for num in i: if num in "0123456789": all_are_numbers=True else: all_are_numbers=False break if all_are_numbers and 0 <= int(i) <= 255: correct_parts=True else: correct_parts=False break if correct_parts: lst.append('IPv4') else: lst.append('Neither') elif len(IPv6_parts) == 8: #further filtering into specific IPv6 verification for i in IPv6_parts: if 1 <= len(i) <= 4: for char in i: if char in "0123456789abcdefABCDEF": #assuming inputs are not case-sensitive correct_parts=True else: correct_parts=False break if correct_parts: lst.append('IPv6') else: lst.append('Neither') else: lst.append('Neither') return lst
# Escreva um programa para ler um vetor de 10 elementos inteiros. Em seguida exclua o 3° elemento do vetor deslocando os elementos subsequentes uma posição para o inicio do vetor. Depois escreva o vetor resultante na tela. list = [1,2,3,4,5,6,7,8,9,10] for i in range(len(list)): print(f"Posição {i}: {list[i]}") del(list[2]) print("Com a exclusão do 3º elemento da lista ela ficou com a seguinte composição: ") for i in range(len(list)): print(f"Posição {i}: {list[i]}")
class ValidationError(Exception): pass class MaxSizeValidator: def __init__(self, max_size): self.so_far = 0 self.max_size = max_size def __call__(self, chunk): self.so_far += len(chunk) if self.so_far > self.max_size: raise ValidationError( 'Size must not be greater than {}'.format(self.max_size))
# # JSON Output # def GenerateJSONArray(list, startIndex=0, endIndex=None, date=False): # Generate a json array string from a list # ASSUMPTION: All items are of the same type / if one is list all are list if(len(list) > 0 and type(list[0]) == type([])): # If the list has entries and the type of the list items is list as well acc = "[" # Accumulate the data for i in range(0, len(list)): # Recursively add the json strings of each list to the accumulator acc += GenerateJSONArray(list[i]) if(not i == len(list) - 1): acc += "," return acc + "]" # Return the accumulator else: # If the list contains non list items acc = "[" if(endIndex == None): endIndex = len(list) # Set a default endIndex if None is provided for i in range(startIndex, endIndex): # Iterate the list value = "" # Get value as string number = False # False if item is not a number try: # Try to parse the string to a number value = int(list[i]) number = True except ValueError: try: value = round(float(list[i]), 2) number = True except ValueError: value = list[i] if(not number or date): # If the item is not a number add " acc += "\"" + list[i].replace("\"", "\\\"") + "\"" else: # Else add it just as string acc += str(value).replace('.0', '') # Replace unnecessary 0s if(not i == len(list) - 1): acc += "," return acc + "]" def GenerateJSONArrayFromDict(dict, endIndex): # Generate json string from dictionary # ASSUMPTION: Dict only has number keys acc = "[" for i in range(0, endIndex): # Go through all possible keys starting from 0 if(not i in dict): # If the key is not in the dictionary val = 0 # Its value is 0 else: val = dict[i] # Else get value acc += str(val) # Add value to accumulator if(not i == endIndex - 1): acc += "," return acc + "]"
#!/usr/bin/python3 def target_in(box, position): xs, xe = min(box[0]), max(box[0]) ys, ye = min(box[1]), max(box[1]) if position[0] >= xs and position[0] <= xe and position[1] >= ys and position[1] <= ye: return True return False def do_step(pos, v): next_pos = (pos[0] + v[0], pos[1] + v[1]) next_v = list(v) if next_v[0] > 0: next_v[0] -= 1 elif next_v[0] < 0: next_v[0] += 1 next_v[1] -= 1 return next_pos, tuple(next_v) def loop(target, v): pos = (0,0) max_y = 0 reached = False while pos[1] >= min(target[1]): pos, v = do_step(pos, v) if pos[1] > max_y: max_y = pos[1] t_in = target_in(target,pos) if t_in: reached = True break return reached, max_y def run(file_name): line = open(file_name, "r").readline().strip() line = line.replace("target area: ", "") tx, ty = line.split(", ") target_x = [int(i) for i in tx.replace("x=", "").split("..")] target_y = [int(i) for i in ty.replace("y=", "").split("..")] target = (target_x,target_y) trajectories = [] for y in range(min(target_y)*2,abs(max(target_y))*2): for x in range(max(target_x)*2): reached, m_y = loop(target, (x,y)) if reached: trajectories.append((x,y)) return trajectories def run_tests(): assert target_in(((20,30),(-10,-5)), (28,-7)) assert target_in(((20,30),(-10,-5)), (28,-4)) == False run_tests() traj = run('inputest') assert len(traj) == 112 traj = run('input') print(f"Answer: {len(traj)}")
# login.py # # Copyright 2011 Joseph Lewis <joehms22@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. #Check password user_pass = {"admin":"21232f297a57a5a743894a0e4a801fc3"} if SESSION and 'login' in SESSION.keys() and SESSION['login']: #Redirect to the index page if already logged in. self.redirect('index.py') elif POST_DICT: try: #If the user validated correctly redirect. if POST_DICT['password'] == user_pass[POST_DICT['username']]: #Send headder SESSION['login'] = True SESSION['username'] = POST_DICT['username'] self.redirect('index.py') else: POST_DICT = [] except: POST_DICT = [] if not POST_DICT: self.send_200() page = ''' <!-- login.py Copyright 2010 Joseph Lewis <joehms22@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --> <html lang="en"> <head> <title>AI Webserver Login</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <LINK REL=StyleSheet HREF="assets/login.css" TYPE="text/css"> </LINK> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/md5.js"></script> <script type="text/javascript"> function start() { $('#login').hide(); $('#login_text').hide(); $('#login').delay(1000).fadeIn(2000, function() {}); $('#login_text').fadeIn(2000, function() {}); } function hash() { //Hash the password before submission, not secure against //things like wireshark, but will at least hide plaintext. :) document.getElementById('pass').value = MD5(document.getElementById('pass').value); $('#bg').fadeOut(1000, function() {}); $('#login').fadeOut(2000, function() {}); $('#login_text').fadeOut(2000, function() {}); } </script> </head> <body id="login_page" onLoad="start()"> <!--Stretched background--> <img src="assets/earthrise.jpg" alt="background image" id="bg" /> <h1 id="login_text">AI Webserver Login</h1> <!--Login form--> <div id="login"> <form method="post"> <input type="text" name="username" placeholder="Username"/> <br /> <input type="password" id="pass" name="password" placeholder="Password"/> <br /> <input type="submit" value="Submit" onClick="hash()"/> </form> </div> </html> </body> ''' #Send body self.wfile.write(page)
def print_line(): print("-" * 60) def print_full_header(build_step_name): print_line() print(" Build Step /// {}".format(build_step_name)) def print_footer(): print_line() def log(level, data): print("{0}: {1}".format(level, data))
def partition(lst,strt,end): pindex = strt for i in range(strt,end-1): if lst[i] <= lst[end-1]: lst[pindex],lst[i] = lst[i],lst[pindex] pindex += 1 lst[pindex],lst[end-1] = lst[end-1],lst[pindex] return pindex def quickSort(lst,strt=0,end=0): if strt >= end: return pivot = partition(lst,strt,end) quickSort(lst,strt,pivot) quickSort(lst,pivot+1,end) lst = list(map(int,input('Enter the number list: ').split())) quickSort(lst,end=len(lst)) print(lst)
class Encapsulation: def __init__(self): self.__my_price = 10 def sell(self): print("my selling price is {}".format(self.__my_price)) def setprice(self, price): self.__my_price = price encap = Encapsulation() encap.sell() encap.__my_price = 20 encap.sell() encap.setprice(20) encap.sell()
# You will receive lines of input: # • On the first line, you will receive a title of an article # • On the second line, you will receive the content of that article # • On the following lines, until you receive "end of comments" you will get the comments about the article # # Print the whole information in html format: # • The title should be in "h1" tag (<h1></h1>) # • The content in article tag (<article></article>) # • Each comment should be in div tag (<div></div>) # For more clarification see the example below. title = input() content = input() comments = [] while True: comment = input() if comment == 'end of comments': break comments.append(comment) print (f'<h1>\n\t{title}\n</h1>\n<article>\n\t{content}\n</article>') for comment in comments: print(f'<div>\n\t{comment}\n</div>')
# -*- encoding: utf-8 -*- ''' @Time : 2020/7/27 9:36 @Author : qinhanluo @File : gunicorn.conf.py @Software: PyCharm @Description : TODO ''' workers = 5 worker_class = 'gevent' bind = "0.0.0.0:5000"
#Code that can be used to calculate the total cost of room makeover in a house def room_area(width, length): return width*length def room_name(): print("What is the name of the room?") return input() def price(name,area): if name == "bathroom": return 20*area elif name == "kitchen": return 10*area elif name == "bedroom": return 5*area else: return 7*area def run(): name = room_name() print("What is the width of the room?") w = float(input()) print("What is the length of the room?") l = float(input())
epochs=300 batch_size=16 latent=10 lr=0.0002 weight_decay=5e-4 encode_dim=[3200, 1600, 800, 400] decode_dim=[] print_interval=10
def histogram(data, n, b, h): # data is a list # n is an integer # b and h are floats # Write your code here # return the variable storing the histogram # Output should be a list pass def addressbook(name_to_phone, name_to_address): #name_to_phone and name_to_address are both dictionaries # Write your code here # return the variable storing address_to_all # Output should be a dictionary pass
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: count = {0:0, 1:0} for el in students: count[el] += 1 i = 0 while i < len(students) and count[sandwiches[i]]: count[sandwiches[i]] -= 1 i += 1 return len(students) - i
streetlights = [ { "_id": "5c33cb90633a6f0003bcb38b", "latitude": 40.109356050955824, "longitude": -88.23546712954632, }, { "_id": "5c33cb90633a6f0003bcb38c", "latitude": 40.10956288950609, "longitude": -88.23546931624688, }, { "_id": "5c33cb90633a6f0003bcb38d", "latitude": 40.11072693111868, "longitude": -88.23548184676547, }, { "_id": "5c33cb90633a6f0003bcb38e", "latitude": 40.11052593366689, "longitude": -88.23548345321224, }, { "_id": "5c33cb90633a6f0003bcb38f", "latitude": 40.1105317123791, "longitude": -88.23527189093869, }, ] def get_streetlights(): return streetlights
def contador(*num): for valor in num: print(num) contad contador(1, 2, 3,)
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def t(): for i in range(len(a)): a[i][i] = a[i][i]*2 t() print(a)
# Vipul Patel Hectoberfest def fun1(n): for i in range(1, n + 1): if i % 3 == 0 and i % 5 != 0: print("Fizz") elif i % 5 == 0 and i % 3 != 0: print("Buzz") elif i % 3 == 0 and i % 5 == 0: print("FizzBuzz") else: print(i) num = 100 # Change num to change range fun1(num)
# Find the first n ugly numbers # Ugly numbers are the numbers whose prime factors are 2,3 or 5. # Normal Approach : # Run a loop till n and check if it has 2,3 or 5 as the only prime factors # if yes, then print the number. It is in-efficient but has constant extra space. # DP approach : # As we know, every other number which is an ugly number can be easily computed by # again multiplying it with that prime factor. So stor previous ugly numbers till we get n ugly numbers # This approach is efficient than naive solution but has O(n) space requirement. def ugly_numbers(n): # keeping a list initialised to 1(as it a ugly number) to store ugly numbers ugly = [1] # keeping three index values for tracking index of current number # being divisible by 2,3 or 5 index_of_2, index_of_3, index_of_5 = 0, 0, 0 # loop till the length of ugly reaches n i.e we have n amount of ugly numbers while len(ugly) < n: # append the multiples checking for the minimum value of all multiples ugly.append(min(ugly[index_of_2] * 2, min(ugly[index_of_3] * 3, ugly[index_of_5] * 5))) # keep incrementing the indexes as well encounter multiples of 2,3 or 5 respectively if ugly[-1] == ugly[index_of_2] * 2: index_of_2 += 1 if ugly[-1] == ugly[index_of_3] * 3: index_of_3 += 1 if ugly[-1] == ugly[index_of_5] * 5: index_of_5 += 1 # return the list return ugly # Driver Code n = 20 print(ugly_numbers(n)) # Time Complexity : O(n) # Space Complexity : O(n)
teste = 3 * 5 + 4 ** 2 s = 'prova de python' n = 'José' i = 25 print('Você se chama {} e tem {} anos de idade'.format(n, i))
# Lexical Grammar: # # NUMBER → DIGIT+ ( "." DIGIT+ )? ; # STRING → "\"" <any char except "\"">* "\"" ; # IDENTIFIER → (ALPHA | "@") ( ALPHA | DIGIT )* ; # ALPHA → "a" ... "z" | "A" ... "Z" | "_" ; # DIGIT → "0" ... "9" ; class AstError(Exception): def __init__(self, msg, position=None): self.position = position super().__init__(msg) class LexerError(AstError): pass class Token: EQ = "=" EQ2 = "==" GT = ">" LT = "<" NE = "!=" GTE = ">=" LTE = "<=" PLUS = "+" MINUS = "-" MUL = "*" POWER = "**" DIV = "/" INT_DIV = "//" MODULO = "%" LPAREN = "(" RPAREN = ")" BIT_OR = "|" BIT_XOR = "^" BIT_AND = "&" BIT_NOT = "~" BIT_LSHIFT = "<<" BIT_RSHIFT = ">>" EXCLAMATION = "!" SEMI = ";" DOT = "." AT = "@" UNDER = "_" LCURCLY = "{" RCURCLY = "}" COLON = ":" ASSIGN = ":=" COMMA = "," DQUOTE = '"' DOLLAR = "$" INT_CONST = "INT_CONST" FLOAT_CONST = "FLOAT_CONST" STR_CONST = "STR_CONST" CONST = "CONST" ID = "ID" AND = "and" OR = "or" NOT = "not" IN = "in" ALL = "all" AS = "as" BOTTOM = "bottom" BY = "by" FROM = "from" HAVING = "having" PER = "per" TOP = "top" WHERE = "where" WITH = "with" EOF = "EOF" COMPARISON_SYMBOLS = set([LT, EQ, GT, EXCLAMATION]) KEYWORDS = set([AND, OR, NOT, IN, TOP, BOTTOM, BY, PER, WHERE, FROM, HAVING, AS, WITH, ALL]) SYMBOLS = set( [SEMI, DOT, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, COMMA, BIT_OR, BIT_AND, BIT_XOR, BIT_NOT, MODULO] ) CONSTANTS = { "None": None, "True": True, "False": False, } def __init__(self, value, type=None, position=None): self.value = value self.type = type or value self.position = position def __str__(self): return f"{self.type} -> {self.value}" class Lexer: def __init__(self, str): self.str = str self.pos = 0 self.advance() def build_token(self, value, type=None): return Token(value, type, position=self.token_start_pos) @staticmethod def is_name_start(c): return c and (c.isalpha() or c == Token.UNDER or c == Token.AT) @staticmethod def is_name_part(c): return Lexer.is_name_start(c) or c.isdigit() def advance(self): if self.pos < len(self.str): self.current_char = self.str[self.pos] self.pos += 1 else: self.current_char = '' return self.current_char def is_whitespace(self, c): if c: return c.isspace() def skip_whitespaces(self): while self.current_char.isspace(): self.advance() def skip_comment(self): while self.current_char != Token.RCURCLY: self.advance() self.advance() def number_token(self): token = '' while self.current_char.isdigit(): token += self.current_char self.advance() if self.current_char == Token.DOT: token += Token.DOT self.advance() while self.current_char.isdigit(): token += self.current_char self.advance() return self.build_token(float(token), Token.FLOAT_CONST) else: return self.build_token(int(token), Token.INT_CONST) def name_token(self, prefix=None): token = (prefix or '') + self.current_char self.advance() while Lexer.is_name_part(self.current_char): token += self.current_char self.advance() if token in Token.KEYWORDS: return self.build_token(token) elif token in Token.CONSTANTS: return self.build_token(Token.CONSTANTS[token], Token.CONST) else: return self.build_token(token, Token.ID) def string_literal(self): token = '' self.advance() while self.current_char != Token.DQUOTE: token += self.current_char self.advance() self.advance() return self.build_token(token, Token.STR_CONST) def dollar_literal(self): self.advance() if self.current_char.isdigit(): return self.number_token() else: return self.name_token(Token.DOLLAR) def colon_op(self): self.advance() if self.current_char == Token.EQ: self.advance() return self.build_token(Token.ASSIGN) return self.build_token(Token.COLON) def comparison_op(self): token = '' while self.current_char in Token.COMPARISON_SYMBOLS: token += self.current_char self.advance() # Temporary treat "="" as an "==" if token == Token.EQ: token = Token.EQ2 return self.build_token(token) def div_op(self): self.advance() if self.current_char == Token.DIV: self.advance() return self.build_token(Token.INT_DIV) else: return self.build_token(Token.DIV) def mul_or_power_op(self): self.advance() if self.current_char == Token.MUL: self.advance() return self.build_token(Token.POWER) else: return self.build_token(Token.MUL) def symbol(self): sym = self.current_char self.advance() return self.build_token(sym) def next_token(self): self.skip_whitespaces() while self.current_char: if self.current_char == Token.LCURCLY: self.skip_comment() self.skip_whitespaces() continue self.token_start_pos = self.pos if self.current_char.isdigit(): return self.number_token() if Lexer.is_name_start(self.current_char): return self.name_token() if self.current_char == Token.DQUOTE: return self.string_literal() if self.current_char == Token.DOLLAR: return self.dollar_literal() if self.current_char == Token.COLON: return self.colon_op() if self.current_char in Token.COMPARISON_SYMBOLS: return self.comparison_op() if self.current_char == Token.DIV: return self.div_op() if self.current_char == Token.MUL: return self.mul_or_power_op() if self.current_char in Token.SYMBOLS: return self.symbol() raise LexerError(f"unexpected char: '{self.current_char}' code={ord(self.current_char)} pos=#{self.pos}") return self.build_token(Token.EOF) def all_tokens(self): res = [] token = self.next_token() while token.type != Token.EOF: res.append(token) token = self.next_token() return res
def initialize(context): context.spy= sid(8554) schedule_function(my_rebalance, date_rules.month_start(), time_rules.market_open()) def my_rebalance(context,data): position= context.portfolio.positions[context.spy].amount if position == 0: order_target_percent(context.spy, 1.0) record(lev=context.account.leverage)
# Shared list of BuiltIn keywords that should be implemented # by specialized comparators. builtin_method_names = ( "should_be_equal", "should_not_be_equal", "should_be_empty", "should_not_be_empty", "should_match", "should_not_match", "should_match_regexp", "should_not_match_regexp", "should_contain", "should_not_contain", "should_contain_any", "should_not_contain_any", "should_start_with", "should_not_start_with", "should_end_with", "should_not_end_with", )
""" leetcode 239 Sliding Window Maximum """ """ Time Complexity: O(N*logk) Because python doesn't have an index_maxheap,so need to implement Notes: 1)当“滑动窗口”要把左边界移除的时候,但是没有从一个堆中移除非最堆顶元素的操作; 2)找到即将要滑出边界的那个索引,索引值如何更新呢?新进来的那个数的索引,索引对 k 取模的那个索引进行更新. """ class IndexMaxHeap: def __init__(self, capacity: int): self.data = [None for _ in range(capacity)] self.indexes = [-1 for _ in range(capacity)] self.reverse = [-1 for _ in range(capacity)] self.count = 0 self.capacity = capacity def size(self) -> int: return self.count def empty(self) -> bool: return not self.count def insert(self, i, item): if self.count + 1 > self.capacity: raise Exception('heap is out of capacity') self.data[i] = item self.indexes[self.count] = i self.reverse[i] = self.count self.count += 1 self.__shift_up(self.count - 1) def __shift_up(self, i): while i > 0 and self.data[self.indexes[i // 2]] < self.data[self.indexes[i]]: self.indexes[i // 2], self.indexes[i] = self.indexes[i], self.indexes[i // 2] self.reverse[self.indexes[i // 2]] = i // 2 self.reverse[self.indexes[i]] = i i //= 2 def __shift_down(self, i): while 2 * i <= self.count: idx = 2 * i # if idx + 1 <= self.count and self.data[self.indexes[idx]] > self.data[self.indexes[idx - 1]]: # idx += 1 if self.data[self.indexes[i]] >= self.data[self.indexes[idx]]: break self.indexes[i], self.indexes[idx] = self.indexes[idx], self.indexes[i] self.reverse[self.indexes[i]] = i self.reverse[self.indexes[idx]] = idx i = idx def pop(self) -> int: if self.count == 0: raise Exception('heap is null') ret = self.data[self.indexes[0]] self.indexes[0], self.indexes[self.count - 1] = self.indexes[self.count - 1], self.indexes[0] self.reverse[self.indexes[0]] = 0 self.reverse[self.indexes[self.count - 1]] = self.count - 1 self.reverse[self.indexes[self.count - 1]] = 0 self.count -= 1 self.__shift_down(1) return ret def pop_index(self) -> int: assert self.count > 0 ret = self.indexes[0] self.indexes[0], self.indexes[self.count - 1] = self.indexes[self.count - 1], self.indexes[0] self.count -= 1 self.__shift_down(0) return ret def peek(self) -> int: if self.count == 0: raise Exception('heap is null') return self.data[self.indexes[0]] def get_item(self, i) -> int: return self.data[i] def update(self, i, item): self.data[i] = item idx = self.reverse[i] self.__shift_down(idx) self.__shift_up(idx) def peek_index(self) -> int: if self.count == 0: raise Exception('heap is null') return self.indexes[0] def max_sliding_window(nums, k): if not nums: return [] index_maxheap = IndexMaxHeap(k) for i in range(k): index_maxheap.insert(i, nums[i]) res = [] for i in range(k, len(nums)): res.append(index_maxheap.peek()) index_maxheap.update(i % k, nums[i]) res.append(index_maxheap.peek()) return res """ test sample """ if __name__ == '__main__': nums = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 res = max_sliding_window(nums, k) print(res)
REPORTS = [ { "address": "0xCd0D1a6BD24fCD578d1bb211487cD24f840BC900", "payload": { "messages": [ "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000001789e100000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044c494e4b00000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000001cb935e0000000000000000000000000000000000000000000000000000000000000000670726963657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004434f4d5000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000091a0f0e600000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000619562600000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034554480000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000185f100000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a52580000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000657d40000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034241540000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e500000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001d7ec80000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034b4e430000000000000000000000000000000000000000000000000000000000", ], "prices": { "BAT": "0.415700", "BTC": "39091.900000", "COMP": "481.900000", "ETH": "1637.180000", "KNC": "1.933000", "LINK": "24.682000", "ZRX": "1.597200", }, "signatures": [ "0x3a6b0b7d403f330be0f12e49da0d108f424d50b11c604383800f98cb471906796b221ea563ec725db448eed29430758e83957fd30110fd0ef1d9de6cc306672b000000000000000000000000000000000000000000000000000000000000001c", "0x34374c83f25bec8e1a86e67ef0c6fd3075c44cb13075d38edba85973298978316787099a2c4449e14f774aa2531c4486e268dc905a22af3190e941430bbff664000000000000000000000000000000000000000000000000000000000000001b", "0xb1413117fffafad10df28a16da2b0a2e99147dc01b99c0ae91fbdb2ecb85d81a7197f9396ea6f012eabf9084ff1cd2385f76d2ae1c38f772971b9cd1fb3cd9c4000000000000000000000000000000000000000000000000000000000000001c", "0x5bedbc0d17bfaa04428b4c0b59023a234de4e89e7c85652c72620a4570d6de6e10994e106b8be085c4368d16de90d97e93e0b99c0cdf676dc732f18b1973bd1e000000000000000000000000000000000000000000000000000000000000001b", "0xfc74694cb78c70b48d5a895923d891f0939d9f68b1faa07c48bb9d01aa852deb68f95b90d81998491d9af978ced94df5ebfdde064ea1f0c366b9473ab51fe40f000000000000000000000000000000000000000000000000000000000000001c", "0x8c0a744a76bcda0fb1709e29ba447e625b521c77eb52618e42bd79acb7dd5ae33fac5adcc3b095d89b80ccbcf092d088350d539a1b932bd432a3f05829551230000000000000000000000000000000000000000000000000000000000000001b", "0xc470bb19e3b8328c6a4f59f6ba91b61585a6a644ba3e8161b1c9510e21c29fe16c7b0e095be9835e6c13785eb3413a615b6098c972fd6e1f0846367f4f25d822000000000000000000000000000000000000000000000000000000000000001c", ], "timestamp": "1612779749", }, }, { "address": "0xef207780639b911e6B064B8Bf6F03f8BE5260a58", "payload": { "messages": [ "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001862f80000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a52580000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000658380000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034241540000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001d82b00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034b4e430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000178a1f80000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044c494e4b00000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000001cab7a40000000000000000000000000000000000000000000000000000000000000000670726963657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004434f4d5000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000091a1e50a00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e600000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000006196e9000000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034554480000000000000000000000000000000000000000000000000000000000", ], "prices": { "BAT": "0.415800", "BTC": "39092.900000", "COMP": "481.000000", "ETH": "1637.280000", "KNC": "1.934000", "LINK": "24.683000", "ZRX": "1.598200", }, "signatures": [ "0x24f319f2ff0978613240ac8317bdbd380243a43aeeeee955fbdb99740471bb6e42d344d27056df235a9795d37aa4323b9ad1241551684c4cdf28245f63fdc7bd000000000000000000000000000000000000000000000000000000000000001b", "0x809c8af8b57f95e913902e8af9d4a047521b1cb91752b5c7859326de125f6bdf3010f79c8f741cbc0778ec4ccc9fc7d0f9e369b0e2850bc19e65fe56f72604d8000000000000000000000000000000000000000000000000000000000000001c", "0xebf24d5982c4f3a0527414133a6b1fc368d7b45e15ae3543f4e0a661db79fd3735f28edba94616b21211f61f93e83460a32e3d9d17ad1524785906d398edd653000000000000000000000000000000000000000000000000000000000000001b", "0xf5f0709e7f3719bde5003f33d71b3806291002133ff5062e4a7964a307a3d0a60a66f5308947b07a235c1d560733b41da5b183b438c9fb4e05991a0803584c15000000000000000000000000000000000000000000000000000000000000001b", "0x0597fd1934139b341177d00e849f32e48682310167324ba01d1c92911441179b7ae5e110fa4ad95339ff86d8f8908f54c05f98395116b9649b1eb9d22641e41f000000000000000000000000000000000000000000000000000000000000001c", "0xf392088cbb3e6d208cae3b76b5168966122cc329af7dc288d4bead0aaa08b4fe1fab124958a23a1b38cbcdda1d9ec01bfaac473baa9ea7ef5a4623d0536fd2da000000000000000000000000000000000000000000000000000000000000001c", "0xca0c50b59661bbdded30c8747eedb78f94f399269aa88a0ba0b6caf5e07b431d2b322e03d0b25df0f54b0e12bb781419d20246902d2c72b8d7cc5b1015ebebac000000000000000000000000000000000000000000000000000000000000001b", ], "timestamp": "1612779750", }, }, { "address": "0xd264c579e7b7B278395303aB64ee583917228bfd", "payload": { "messages": [ "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000061986fa00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034554480000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001866e00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a52580000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000006589c0000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034241540000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001d86980000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034b4e430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000178a5e00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044c494e4b00000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000001cad00e0000000000000000000000000000000000000000000000000000000000000000670726963657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004434f4d5000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e700000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000091a2d92e00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000", ], "prices": { "BAT": "0.415900", "BTC": "39093.900000", "COMP": "481.100000", "ETH": "1637.380000", "KNC": "1.935000", "LINK": "24.684000", "ZRX": "1.599200", }, "signatures": [ "0x8d0e96469b80f11cebe95e4cb6cb089dbd2c9fb0b767f6d70ae381bee3efbdf67d58ff8ddc62743f2a85d8a3b22d5baba12a2be89eb2d652fe552d00c8aa5dfb000000000000000000000000000000000000000000000000000000000000001c", "0xa079c89c55432039b1506a3964b7276a47013fa092b6d5d07087e953f6e1fec661eb2998e4b1396fc26557b1c5366010147e1c8f25987f75256d0e9d425b3a6d000000000000000000000000000000000000000000000000000000000000001b", "0x066eb88ad643a97d095523207e84072497f5f89e9648183e9a77aeef3f16eac31573dea48cce787085a805442fe72151301ea94debb821839b3245eb3205df8c000000000000000000000000000000000000000000000000000000000000001b", "0x8c9d61b86c68d46cd1fa578c5d252faa9cbb119c344cad61b2b67105e69813670577db1f9604a70ebadd8490fa52a968fba885964051457355c721a0bccf19ae000000000000000000000000000000000000000000000000000000000000001c", "0x5a3da98cb87f3fb14023418837f6d2cd3aa832f0ca5881fbd66be13b4e05cd25007cdb112f20d0662d7cc5262bd616efe396201c65c92caa7b528d1297362d11000000000000000000000000000000000000000000000000000000000000001b", "0x57e09b6d4f0d414a705b8e5cd21fc86e8167891df4055bd8f2e46a81b1bb09596a02f8ffed52f8fd5a5b03da450f4eee2c42fe29444ef5343aacbf48a72747fd000000000000000000000000000000000000000000000000000000000000001b", "0x3f82eaf2ac86d37d8ecfdbd0ed8e2a9e5186e0d819e3fadbea1b200447cbcaa0700bbd4be635e6e741a53768f305a78ab4888c567077987e859792eb3bda0cec000000000000000000000000000000000000000000000000000000000000001b", ], "timestamp": "1612779751", }, }, { "address": "0x4994779B1f4e1cA4582d0527cF0bf5A01248DF5C", "payload": { "messages": [ "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000001cae8780000000000000000000000000000000000000000000000000000000000000000670726963657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004434f4d5000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000091a3cd5200000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000006199f6400000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034554480000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001843b80000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a52580000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000655180000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034241540000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001d8a800000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034b4e430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e800000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000178a9c80000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044c494e4b00000000000000000000000000000000000000000000000000000000", ], "prices": { "BAT": "0.415000", "BTC": "39094.900000", "COMP": "481.200000", "ETH": "1637.480000", "KNC": "1.936000", "LINK": "24.685000", "ZRX": "1.590200", }, "signatures": [ "0x70d6d8ea44af86024c1417ffec64b1a68d9f15fc9e9f7d56404f3164057139ef46c8b470da85569fad4bcdb8dadee79338a158feb606ace2cfc3c3afd241bae8000000000000000000000000000000000000000000000000000000000000001b", "0x1757a9af7796f7929b86657cae31401f34418a90f40332a54381f5d984c75ca621bf37ffe6ea1124fd09c12ebdb369a05e6922442170466208b0d00cdff590b4000000000000000000000000000000000000000000000000000000000000001c", "0xd53d341bd6583813c2a7c9d0c62a0fb12d948cf14a80a09d1a0b4ba0554c3825796321469f0460dfbed697e13e6189a50b1149d95904a68796763dbee432fae3000000000000000000000000000000000000000000000000000000000000001c", "0x43cd23f8696b2f099af12a905207dc4d2fcc955ba2ebdefefb95016cd5db1056081aed5f99f2ec2f139070801849ccae6e1635d69e98849509c5cd4f5e3bd67a000000000000000000000000000000000000000000000000000000000000001c", "0x704b2bbd0ba687dcc753ae0e1c61f14a4b66cda13c3f91326b3e75b557e43bee3d5e162d08c40fcc38dee0672242394c7c82959e8be4da6bdbfaccbf9507c0d4000000000000000000000000000000000000000000000000000000000000001b", "0x5f993deecec1c2acdbc006a427999b6e29e0bd3b25d0c830942da50d289f05f65f6ef14547a45c3bec6f5989e61f9b305618efa0488b6a14db76eadec42ab7e3000000000000000000000000000000000000000000000000000000000000001b", "0x8c9fdfc3357762adeb613e741fe4cfb37291cda30442bd89e2831a4750e479f058c13187272134fb2e848ca06faf276cfa27d53b8c3d714f4968d9852ce6f038000000000000000000000000000000000000000000000000000000000000001b", ], "timestamp": "1612779752", }, }, { "address": "0xDb3DD6a3E8216381fFf19648067ca964A8bf2C1c", "payload": { "messages": [ "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000178adb00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044c494e4b00000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000001cb00e20000000000000000000000000000000000000000000000000000000000000000670726963657300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004434f4d5000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000091a4c17600000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000619b7ce00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034554480000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001847a00000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035a52580000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000006557c0000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034241540000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000602110e900000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000001d8e680000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034b4e430000000000000000000000000000000000000000000000000000000000", ], "prices": { "BAT": "0.415100", "BTC": "39095.900000", "COMP": "481.300000", "ETH": "1637.580000", "KNC": "1.937000", "LINK": "24.686000", "ZRX": "1.591200", }, "signatures": [ "0x1c4c0b0add2a10836fdcf0ba71ea939e472920e5ab38305f5950598f834efd3659b088cbdec1f66a8ffebb5182f6255f49e380eb6939b483d971f64a4454742b000000000000000000000000000000000000000000000000000000000000001c", "0x9e9ae712269067270787d1e9fc7bd51697143f228a41373151e5a0ef00e2ec5038dedbf1c558df7ec06ca7bd4ca10653e22762bf3d7c6001aea7078c1c0ffc1e000000000000000000000000000000000000000000000000000000000000001b", "0xa8797f59180db4f3ed51c3c11d3d59b151edbf80f54c0d8711c972655049e3331d01ee1d48f6a4faddce1ec7085fec886167f6fda8a71c44962832c81be18254000000000000000000000000000000000000000000000000000000000000001c", "0x899b2993ee394e7f8077b900faec02b96380653d1f1909d87020e5980ec30efe3c168fac123babc429933512450fbba7f6f8ed2eb8a61ef97a38925585b26990000000000000000000000000000000000000000000000000000000000000001c", "0x8ff31d3cbd608a539ea4c09da617dca509fac0f84be75840d124c490caef5e007bcefef6646404bd62669ea247fe554b1b3cf7ba0eb17612969f81cfd40481ba000000000000000000000000000000000000000000000000000000000000001c", "0xaf9e90951a5f4528a500d6eb3f5b0b2922e3da95730b71fe4df8fd38909021486bdc7d2bb7d80857042bbff43a30b5c3ffcc30b987501823988324d184b85c1f000000000000000000000000000000000000000000000000000000000000001b", "0x3cb850e04b74cf2f45df60d27c3e30f596c2df76e51bb29cac44c5818443d59b2dbc2474da481952dc3e6a00b2470cb8fb1caeb158d3234dc5a26be411e4b810000000000000000000000000000000000000000000000000000000000000001b", ], "timestamp": "1612779753", }, }, ] def test_weighted_median(a, OpenOraclePriceData, OpenOracleMedianizer): p = OpenOraclePriceData.deploy({"from": a[0]}) m = OpenOracleMedianizer.deploy(p, 100 * 86400, {"from": a[0]}) for each in REPORTS: m.postPrices(each["payload"]["messages"], each["payload"]["signatures"]) m.setReporter(REPORTS[0]["address"], 100) assert m.repoterCount() == 1 assert m.price("BTC") == 39091900000 m.setReporter(REPORTS[1]["address"], 100) m.setReporter(REPORTS[2]["address"], 100) m.setReporter(REPORTS[3]["address"], 100) m.setReporter(REPORTS[4]["address"], 100) assert m.repoterCount() == 5 assert m.price("BTC") == 39093900000 m.setReporter(REPORTS[3]["address"], 500) assert m.repoterCount() == 5 assert m.price("BTC") == 39094900000 m.setReporter(REPORTS[3]["address"], 0) assert m.repoterCount() == 4 assert m.price("BTC") == 39092900000
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/parallels/catkin_ws/install/include".split(';') if "/home/parallels/catkin_ws/install/include" != "" else [] PROJECT_CATKIN_DEPENDS = "cv_bridge;image_geometry;image_transport;camera_info_manager;pcl_ros;roscpp;tf;visualization_msgs;std_msgs;tf2;message_runtime;sensor_msgs;geometry_msgs;resource_retriever;pcl_conversions;dynamic_reconfigure".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "baxter_kinect_calibration" PROJECT_SPACE_DIR = "/home/parallels/catkin_ws/install" PROJECT_VERSION = "0.2.0"
self.description = "Fileconflict file -> dir on package replacement (FS#24904)" lp = pmpkg("dummy") lp.files = ["dir/filepath", "dir/file"] self.addpkg2db("local", lp) p1 = pmpkg("replace") p1.provides = ["dummy"] p1.replaces = ["dummy"] p1.files = ["dir/filepath/", "dir/filepath/file", "dir/file", "dir/file2"] self.addpkg2db("sync", p1) self.args = "-Su" self.addrule("PACMAN_RETCODE=0") self.addrule("!PKG_EXIST=dummy") self.addrule("PKG_EXIST=replace")
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright 2014 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # 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. # # For those usages not covered by the Apache version 2.0 License please # contact with opensource@tid.es # __author__ = 'arobres' REST_PATH = '../../../../manage.py' POLICY_MANAGER_IP = 'fiwarecloto' POLICY_MANAGER_PORT = 8000 FACTS_IP = 'fiwarecloto' FACTS_PORT = 5000 RABBIT_IP = 'rabbitmq' AUTH_TOKEN_OLD = '' KEYSTONE_URL = '' TENANT_ID = '' TENANT_NAME = '' USER = '' PASSWORD = '' CONTENT_TYPE = 'application/json' HEADERS = {'content-type': CONTENT_TYPE, 'X-Auth-Token': ''} DB_PATH = '../../../../cloto.db' MOCK_IP = u'127.0.0.1' MOCK_PORT = 8080 MOCK_PATH = u'commons/server_mock.py'
def find_lowest(lst): # Return the lowest positive # number in a list. def lowest(first, rest): # Base case if len(rest) == 0: return first if first > rest[0] or first < 0: return lowest(rest[0], rest[1:]) else: return lowest(first, rest) return lowest(lst[0], lst[1:]) a = [16, -6, 1, 6, 6] print(find_lowest(a))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_installed_dependencies": "00_checker.ipynb", "check_new_version": "00_checker.ipynb"} modules = ["checker.py"] doc_url = "https://muellerzr.github.io/dependency_checker/" git_url = "https://github.com/muellerzr/dependency_checker/tree/master/" def custom_doc_links(name): return None
path_name = "SampleWrite.txt" ### withを使ったファイル読み込み with open(path_name, mode='w') as f: f.write('hello new world!!') # close不要 # f.close()
num = 600851475143 p = int(num**0.5) + 1 factors = [] def addToFactors(x): for f in factors: if not x % f: return factors.append(x) for i in range(2, p): if not num % i: addToFactors(i) print(max(factors))
# https://codeforces.com/problemset/problem/230/B n = int(input()) numbers = [int(x) for x in input().split()] counter = 0 for number in numbers: if number == 1 or number == 2: print('NO') continue for x in range(2, number): if counter > 1: break if number % x == 0: counter += 1 if counter == 1: print('YES') else: print('NO') counter = 0
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ c = len(nums) / 3 m = {} for n in nums: m[n] = m.get(n, 0) + 1 return [k for k, v in m.items() if v > c] def test_majority_element(): s = Solution() assert [3] == s.majorityElement([3, 2, 3]) assert [1, 2] == s.majorityElement([1, 1, 1, 3, 3, 2, 2, 2])
# Default dt for the imaging DEF_DT = 0.2 # Parameters for cropping around bouts: PRE_INT_BT_S = 2 # before POST_INT_BT_S = 6 # after
first_sequence = list(map(int, input().split())) second_sequence = list(map(int, input().split())) line = input() while not line == 'nexus': first_pair, second_pair = line.split('|') first_list_index1, second_list_index1 = list(map(int, first_pair.split(':'))) first_list_index2, second_list_index2 = list(map(int, second_pair.split(':'))) if first_list_index1 < second_list_index1 \ and first_list_index2 > second_list_index2 \ and first_list_index1 < first_list_index2 \ and second_list_index1 > second_list_index2: connected_elements_sum = first_sequence[first_list_index1] + first_sequence[first_list_index2] \ + second_sequence[second_list_index1] + second_sequence[second_list_index2] first_sequence = first_sequence[:first_list_index1] + first_sequence[first_list_index2+1:] first_sequence = [el + connected_elements_sum for el in first_sequence] second_sequence = second_sequence[:second_list_index2] + second_sequence[second_list_index1+1:] second_sequence = [el + connected_elements_sum for el in second_sequence] elif first_list_index1 > second_list_index1 \ and first_list_index2 < second_list_index2 \ and first_list_index2 < first_list_index1 \ and second_list_index1 < second_list_index2: connected_elements_sum = first_sequence[first_list_index1] + first_sequence[first_list_index2] \ + second_sequence[second_list_index1] + second_sequence[second_list_index2] first_sequence = first_sequence[:first_list_index2] + first_sequence[first_list_index1 + 1:] first_sequence = [el + connected_elements_sum for el in first_sequence] second_sequence = second_sequence[:second_list_index1] + second_sequence[second_list_index2 + 1:] second_sequence = [el + connected_elements_sum for el in second_sequence] line = input() print(', '.join(map(str, first_sequence))) print(', '.join(map(str, second_sequence)))
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: node_list = [] sentinel = head = ListNode(0, None) for item in lists: while item: node_list.append(item.val) item = item.next for item in sorted(node_list): head.next = ListNode(item, None) head = head.next return sentinel.next
# https://leetcode.com/problems/fair-candy-swap/discuss/161269/C%2B%2BJavaPython-Straight-Forward class Solution: def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: diff = (sum(A) - sum(B)) // 2 B = set(B) A = set(A) for b in B: if b + diff in A: return [b+diff, b]
class BaseEncounter(object): """Base encounter class.""" def __init__(self, player, check_if_happens=True): self.p = self.player = player if (check_if_happens and self.check_if_happens()) or not check_if_happens: enc_name = self.__class__.__name__ enc_dict = self.p.game.enc_count_dict if enc_name in enc_dict: enc_dict[enc_name] += 1 else: enc_dict[enc_name] = 1 self.p.refresh_screen() self.run() def check_if_happens(self): return True def run(self): pass class Guaranteed(object): @staticmethod def check_if_happens(): return True
# create node class class Node: def __init__(self, value=None, next=None): self.value = value self.next = next # create stack class Stack: def __init__(self): self.top = None def isEmpty(self): if self.top == None: return True else: return False def peek(self): if self.isEmpty(): raise Exception('cannot peek empty stack') else: return self.top.value def push(self, val): self.top = Node(val, self.top) return True def pop(self): if self.isEmpty(): raise Exception('cannot pop empty stack') else: temp = self.top.value self.top = self.top.next return temp
""" Copyright 2020 Robert MacGregor 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. """ load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") load("//libraries:zlib.bzl", "zlib") load("//applications:bison.bzl", "bison") load("//libraries:harfbuzz.bzl", "harfbuzz") def graphviz(): # Ensure dependencies are loaded zlib() harfbuzz() maybe( new_git_repository, name = "graphviz", remote = "https://gitlab.com/graphviz/graphviz.git", shallow_since = "1593420362 +0000", # Release 2.44.1 commit = "771bc4dbff3e6f358fa75cdc7774a413ccacad51", build_file = "@rules_third_party//applications:graphviz.BUILD" ) def run_graphviz(name, input, output, type="png"): native.genrule( name = name, srcs = [ "@graphviz//:graphviz", input, ], outs = [ output ], cmd = "\n".join([ "DOT_BINARY=\"$(locations @graphviz//:graphviz)\"", # Load DOT binary location - the graphviz target is multiple objects and we're interested in the binary # TODO: Perhaps a filegroup to load the binaries? "IFS=' ' read -ra DOT_DATA <<< \"$$DOT_BINARY\"", "DOT_BINARY=$$(realpath $${DOT_DATA[1]})", "DOT_LIBS=\"$$(realpath $$(dirname $$DOT_BINARY)/../lib)\"", # Generate temporary directory for DOT data "DOT_TEMPORARY=$$(mktemp -d)", "cp $$DOT_LIBS/* $$DOT_TEMPORARY", # Set library path and GVBINDIR so that DOT runs correctly "export LD_LIBRARY_PATH=\"$$DOT_TEMPORARY\"", "export GVBINDIR=\"$$DOT_TEMPORARY\"", # Generate config file to ensure plugins are loaded by dot "$$DOT_BINARY -c", "$$DOT_BINARY -T%s $(location %s) > $@" % (type, input), # Cleanup "rm -rf $$DOT_TEMPORARY" ]) )
# -*- coding: utf-8 -*- class Hero(object): def __init__(self, forename, surname, hero): self.forename = forename self.surname = surname self.heroname = hero
class Ball: def __init__(self): self.x, self.y = 320, 240 self.speed_x = -10 self.speed_y = 10 self.size = 8 def movement(self, player1, player2): self.x += self.speed_x self.y += self.speed_y if self.y <= 0: self.speed_y *= -1 elif self.y >= 480 - self.size: self.speed_y *= -1 if self.x <= 0: self.__init__() elif self.x >= 640 - self.size: self.__init__() self.speed_x *= -1 self.speed_y *= -1 for n in range(-self.size, 64): if self.y == player1.y + n: if self.x <= player1.x + 8: self.speed_x *= -1 break n += 1 for n in range(-self.size, 64): if self.y == player2.y + n: if self.x >= player2.x - 8: self.speed_x *= -1 break n += 1 class Player: def __init__(self): pass
def fizzbuzz(n): if n%3 == 0 and n%5 != 0: resultado = "Fizz" elif n%5 == 0 and n%3 != 0: resultado = "Buzz" elif n%3 == 0 and n%5 == 0: resultado = "FizzBuzz" else: resultado = n return resultado
{ "includes": [ "ext/snowcrash/common.gypi" ], "targets" : [ # LIBSOS { 'target_name': 'libsos', 'type': 'static_library', 'direct_dependent_settings' : { 'include_dirs': [ 'ext/sos/src' ], }, 'sources': [ 'ext/sos/src/sos.cc', 'ext/sos/src/sos.h', 'ext/sos/src/sosJSON.h', 'ext/sos/src/sosYAML.h' ] }, # LIBDRAFTER { "target_name": "libdrafter", 'type': '<(libdrafter_type)', "conditions" : [ [ 'libdrafter_type=="shared_library"', { 'defines' : [ 'DRAFTER_BUILD_SHARED' ] }, { 'defines' : [ 'DRAFTER_BUILD_STATIC' ] }], ], 'direct_dependent_settings' : { 'include_dirs': [ 'src', ], }, 'export_dependent_settings': [ 'libsos', 'ext/snowcrash/snowcrash.gyp:libsnowcrash', ], "sources": [ "src/drafter.h", "src/drafter.cc", "src/drafter_private.h", "src/drafter_private.cc", "src/stream.h", "src/Version.h", "src/NodeInfo.h", "src/Serialize.h", "src/Serialize.cc", "src/SerializeAST.h", "src/SerializeAST.cc", "src/SerializeSourcemap.h", "src/SerializeSourcemap.cc", "src/SerializeResult.h", "src/SerializeResult.cc", "src/RefractAPI.h", "src/RefractAPI.cc", "src/RefractDataStructure.h", "src/RefractDataStructure.cc", "src/RefractSourceMap.h", "src/RefractSourceMap.cc", "src/Render.h", "src/Render.cc", "src/NamedTypesRegistry.cc", "src/NamedTypesRegistry.h", "src/RefractElementFactory.h", "src/RefractElementFactory.cc", "src/ConversionContext.cc", "src/ConversionContext.h", # librefract parts - will be separated into other project "src/refract/Element.h", "src/refract/Element.cc", "src/refract/ElementFwd.h", "src/refract/Visitor.h", "src/refract/VisitorUtils.h", "src/refract/VisitorUtils.cc", "src/refract/SerializeCompactVisitor.h", "src/refract/SerializeCompactVisitor.cc", "src/refract/SerializeVisitor.h", "src/refract/SerializeVisitor.cc", "src/refract/ComparableVisitor.h", "src/refract/ComparableVisitor.cc", "src/refract/TypeQueryVisitor.h", "src/refract/TypeQueryVisitor.cc", "src/refract/IsExpandableVisitor.h", "src/refract/IsExpandableVisitor.cc", "src/refract/ExpandVisitor.h", "src/refract/ExpandVisitor.cc", "src/refract/RenderJSONVisitor.h", "src/refract/RenderJSONVisitor.cc", "src/refract/PrintVisitor.h", "src/refract/PrintVisitor.cc", "src/refract/JSONSchemaVisitor.h", "src/refract/JSONSchemaVisitor.cc", "src/refract/FilterVisitor.h", "src/refract/Registry.h", "src/refract/Registry.cc", "src/refract/Build.h", "src/refract/AppendDecorator.h", "src/refract/ElementInserter.h", "src/refract/Query.h", "src/refract/Query.cc", "src/refract/Iterate.h", ], "dependencies": [ "libsos", "ext/snowcrash/snowcrash.gyp:libsnowcrash", ], }, # TESTLIBDRAFTER { 'target_name': 'test-libdrafter', 'type': 'executable', 'include_dirs': [ 'test/vendor/Catch/include', 'test/vendor/dtl/dtl', 'src/refract', ], 'sources': [ "test/test-drafter.cc", "test/test-SerializeResultTest.cc", "test/test-SerializeSourceMapTest.cc", "test/test-RefractDataStructureTest.cc", "test/test-RefractAPITest.cc", "test/test-RefractParseResultTest.cc", "test/test-RenderTest.cc", "test/test-RefractSourceMapTest.cc", "test/test-SchemaTest.cc", "test/test-CircularReferenceTest.cc", "test/test-ApplyVisitorTest.cc", "test/test-ExtendElementTest.cc", "test/test-ElementFactoryTest.cc", "test/test-OneOfTest.cc", "test/test-SyntaxIssuesTest.cc", ], 'dependencies': [ "libdrafter", ], 'conditions': [ [ 'OS=="win"', { 'defines' : [ 'WIN' ] } ] ], }, # DRAFTER { "target_name": "drafter", "type": "executable", "conditions" : [ [ 'libdrafter_type=="static_library"', { 'defines' : [ 'DRAFTER_BUILD_STATIC' ] }], ], "sources": [ "src/main.cc", "src/config.cc", "src/config.h", "src/reporting.cc", "src/reporting.h", ], "include_dirs": [ "ext/cmdline", ], "dependencies": [ "libdrafter", ], }, # DRAFTER C-API TEST { "target_name": "test-capi", "type": "executable", "conditions" : [ [ 'libdrafter_type=="static_library"', { 'defines' : [ 'DRAFTER_BUILD_STATIC' ] }], ], "sources": [ "test/test-CAPI.c" ], "dependencies": [ "libdrafter", ], }, ], }
# Config key of the MYSQL tag in config.ini MSSQL_TAG = "MSSQL" HOST_CONFIG = "host" DATABASE_CONFIG = "database" USER_CONFIG = "user" PASSWORD_CONFIG = "password" TABLE_CONFIG = "table" DRIVER_CONFIG = "driver" INSTANCE_NAME_FIELD_CONFIG = "instance_name_column" TIMESTAMP_FIELD_CONFIG = "timestamp_column" TIMESTAMP_FORMAT_CONFIG = "timestamp_format" # Config key of the INSIGHTFINDER tag in config.ini IF_TAG = "INSIGHTFINDER" LICENSE_KEY_CONFIG = "license_key" PROJECT_NAME_CONFIG = "project_name" USER_NAME_CONFIG = "user_name" SERVER_URL_CONFIG = "server_url" SAMPLING_INTERVAL = "sampling_interval" # Constant CONFIG_FILE = "config.ini" GMT = "GMT" RAW_DATA_KEY = "data" TIMESTAMP_KEY = "timestamp" INSTANCE_NAME_KEY = "tag" SUCCESS_CODE = 200 METRIC_DATA = "metricData" LICENSE_KEY = "licenseKey" PROJECT_NAME = "projectName" USER_NAME = "userName" AGENT_TYPE = "agentType" AGENT_TYPE_LOG_STREAMING = "LogStreaming" CUSTOM_PROJECT_RAW_DATA_URL = "/customprojectrawdata" NONE = "NONE" CHUNK_SIZE = 1000 # Time Constant ONE_MINUTE = 1000 * 60 FIVE_MINUTES = ONE_MINUTE * 5
print("hello, what is your name?") name = input() print("hi " + name)
#Python 3.X solution for Easy Challenge #0007 #GitHub: https://github.com/Ashkore #https://www.reddit.com/user/Ashkoree/ alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] morase = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",".--","-..-","-.--","--.."] def tomorase(string): string = list(string) newstring =[] for char in string: try: char = char.upper() newstring.append(morase[alphabet.index(char)]+" ") except: if char == " ": newstring.append("/ ") else: newstring.append("? ") return "".join(map(str,newstring)) def frommorase(string): string = string.split(" ") newstring = [] for char in string: try: newstring.append(alphabet[morase.index(char)]) except: if char == "/": newstring.append(" ") if char == "?": newstring.append("_") return "".join(map(str,newstring)) string = input("What is your string?") print("Morase: "+tomorase(string)) print("Normal: "+frommorase(tomorase(string)))
'''As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes. Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual: salários até R$ 880,00 (incluindo) : aumento de 20% salários entre R$ 880,00 e R$ 1000,00 : aumento de 15% salários entre R$ 800,00 e R$ 1500,00 : aumento de 10% salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela: o salário antes do reajuste; o percentual de aumento aplicado; o valor do aumento; o novo salário, após o aumento.''' salario = float(input('Digite o valor do salario atual R$: ')) if salario <= 880: porcento = (20 /100) * 880 resultado = salario + porcento print('O salario antes do rajuste R$ ', salario) print('O percentual de aumento é 20%') print('O valor do aumneto R$ ', porcento) print('O valor do novo salario após o aumento R$ ', resultado) if salario > 880 and salario <= 1000: porcento = (15 / 100) * 1000 resultado = salario + porcento print('O salario antes do rajuste R$ ', salario) print('O percentual de aumento é 20%') print('O valor do aumneto R$ ', porcento) print('O valor do novo salario após o aumento R$ ', resultado) if salario > 880 and salario <= 1500: porcento = (10 / 100) * 1500 resultado = salario + porcento print('O salario antes do rajuste R$ ', salario) print('O percentual de aumento é 20%') print('O valor do aumneto R$ ', porcento) print('O valor do novo salario após o aumento R$ ', resultado) if salario >= 1500: porcento = (5 / 100) * 1500 resultado = salario + porcento print('O salario antes do rajuste R$ ', salario) print('O percentual de aumento é 20%') print('O valor do aumneto R$ ', porcento) print('O valor do novo salario após o aumento R$ ', resultado)
# Write a function or lambda using the implementation of fold below that will # return the product of the elements of a list. def or_else(lhs, rhs): if lhs != None: return lhs else: return rhs def fold(function, arguments, initializer, accumulator = None): if len(arguments) == 0: return accumulator else: return fold( function, arguments[1:], initializer, function( or_else(accumulator, initializer), arguments[0]))
def solution(A): nums = {} for num in A: nums[num] = 1 for num in nums: if num + 1 in nums or num - 1 in nums: return True return False def solution(N): num = N numStr = str(N) if num < 0: length = len(numStr) - 1 while length > 0: if numStr[length] == '5': numStr = numStr[:length] + numStr[length+1:] return int(numStr) length-=1 else: for i in range(len(numStr)): if numStr[i] == '5': numStr = numStr[:i] + numStr[i+1:] return int(numStr)
test = { 'name': 'q1_1', 'points': 1, 'suites': [ { 'cases': [{'code': ">>> unemployment.select('Date', 'NEI', 'NEI-PTER').take(0).column(0).item(0) == '1994-01-01'\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
command = input() numbers_sequence = [int(x) for x in input().split()] odd_numbers = [] even_numbers = [] for number in numbers_sequence: if number % 2 == 0: even_numbers.append(number) else: odd_numbers.append(number) if command == 'Odd': print(sum(odd_numbers) * len(numbers_sequence)) elif command == 'Even': print(sum(even_numbers) * len(numbers_sequence))
def sainte_claire1(general, dev, msg) : code = 2 prio = 500 prio += adjust_prio(general, dev, msg) keys=list(); keys.append('Sainte Claire') if ( not contains(dev, keys) ) : return (0, 0, 0, '', '') if ( dev['Sainte Claire']['count'] < 3) : return (0, 0, 0, '', '') title = "RU @ Sainte Claire?" body = "\ Are you staying at Sainte Claire? I noticed your device had been detected there when I visited the Loca stand in the South Hall. You were detected by their network at the hotel reception %d times, so I guess that means you are checked in! :) I must have just missed you, I was by the hotel reception myself at %s which is when you were last seen there." % ( \ dev['Sainte Claire']['count'], approx_time_date(dev['Sainte Claire']['last_seen']) \ ) body += sig('Sly') body += location_and_time(general) body += dev_log(general, dev, msg) body += loca_sig() return ( prio, code, title, title, body )
"""Test the backend models module""" def test_foo(): """A fake test, because I just want to get nox to pass"""
# General TEMP_FILES_PATH = '/tmp/temp_files_parkun' PERSONAL_FOLDER = 'broadcaster' BOLD = 'bold' ITALIC = 'italic' MONO = 'mono' STRIKE = 'strike' POST_URL = 'post_url' # Twitter TWITTER_ENABLED = False CONSUMER_KEY = 'consumer_key' CONSUMER_SECRET = 'consumer_secret' ACCESS_TOKEN = 'access_token' ACCESS_TOKEN_SECRET = 'access_token_secret' MAX_TWI_CHARACTERS = 280 MAX_TWI_PHOTOS = 4 TWI_URL = 'twitter.com/SOME_TWITTER_ACCOUNT' # RabbitMQ RABBIT_HOST = 'localhost' RABBIT_AMQP_PORT = '5672' RABBIT_HTTP_PORT = '15672' RABBIT_LOGIN = 'broadcaster' RABBIT_PASSWORD = 'broadcaster' RABBIT_AMQP_ADDRESS = \ f'amqp://{RABBIT_LOGIN}:{RABBIT_PASSWORD}@{RABBIT_HOST}:{RABBIT_AMQP_PORT}' RABBIT_HTTP_ADDRESS = \ f'http://{RABBIT_LOGIN}:{RABBIT_PASSWORD}@{RABBIT_HOST}:{RABBIT_HTTP_PORT}' BROADCAST_QUEUE = 'broadcast' RABBIT_EXCHANGE_SHARING = 'sharing' ROUTING_KEY = 'sharing_status' # VK (see readme.md) VK_ENABLED = False VK_APP_ID = 'vk_app_id' # just to remember VK_GROUP_ID = 'vk_group_id' VK_API_TOKEN = 'vk_api_token' # Telegram TG_ENABLED = False TG_BOT_TOKEN = 'PUT_TOKEN_HERE' TG_CHANNEL = '@channel_name'
''' Author : MiKueen Level : Easy Problem Statement : Convert Binary Number in a Linked List to Integer Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. Example 1: Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10 Example 2: Input: head = [0] Output: 0 Example 3: Input: head = [1] Output: 1 Example 4: Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] Output: 18880 Example 5: Input: head = [0,0] Output: 0 Constraints: The Linked List is not empty. Number of nodes will not exceed 30. Each node's value is either 0 or 1. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: if head.next is None: return head.val # Method 1 res = '' while head: res += str(head.val) head = head.next return int(res, 2) # Method 2 - Cool trick res = 0 while head: res = 2 * res + head.val head = head.next return res
def computepay(h,r): return 42.37 hrs = input("Enter Hours : ") h = float(hrs) rate = input("Enter rate per hour : ") r = float(rate) if h > 40: gross = (40*r)+(h-40)*(r*1.5) print(gross) else: gross=h*r print(gross)
for t in range(int(input())): p, q = map(int, input().split()) q = q + 1 hori = [0 for _ in range(q)] vert = [0 for _ in range(q)] for _ in range(p): x, y, d = input().split() x = int(x) y = int(y) if d == 'N': vert[y + 1] += 1 if d == 'S': vert[y] -= 1 vert[0] += 1 if d == 'E': hori[x + 1] += 1 if d == 'W': hori[x] -= 1 hori[0] += 1 x, y = 0, 0 cum_sum_h, max_h = 0, 0 cum_sum_v, max_v = 0, 0 for i in range(q): cum_sum_h += hori[i] if cum_sum_h > max_h: max_h = cum_sum_h x = i cum_sum_v += vert[i] if cum_sum_v > max_v: max_v = cum_sum_v y = i print('Case #{n}: {x} {y}'.format(n = t + 1, x=x, y=y))
matrix = [sublist.split() for sublist in input().split("|")][::-1] print(' '.join([str(number) for sublist in matrix for number in sublist]))
LOGIN_URL = "/login" XPATH_EMAIL_INPUT = "//form//input[contains(@placeholder,'Email')]" XPATH_PASSWORD_INPUT = "//form//input[contains(@placeholder,'Password')]" XPATH_SUBMIT = "//form//button[contains(@type,'submit')]"