text
stringlengths
38
1.54M
# This file contains functions of some transformations and mathematical calculations import model import highPrecision import numpy as np import re import scipy.interpolate # Numerically solute the Kepler Equation, using Newton iteration def KeplerEquation(M, e): # precision of the calculation ep...
import os import json import logging import requests import pandas as pd logging.basicConfig(level='INFO') # read data into python object path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] data = json.load(open(os.path.join(path, 'example.json'))) # re-serialize as json data_as_json = json.dumps(d...
"""mci_rest_djongo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cla...
#!/usr/bin/python #----------------------------------------------------- # This program find average per key using # the reduceByKey() transformation. #------------------------------------------------------ # Input Parameters: # none #------------------------------------------------------- # @author Mahmoud Parsian...
from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from rest_framework.views import APIView from rest_framework.authtoken.models import Token from django.contrib import auth...
from django.db import models # Create your models here. class category(models.Model): category_name = models.CharField(max_length=100) class restaurant(models.Model): # category 삭제시 같이 삭제 category = models.ForeignKey(category, on_delete=models.CASCADE) rst_name = models.CharField(max_length=100) r...
from ZeroScenarioHelper import * def main(): CreateScenaFile( "c0220.bin", # FileName "c0220", # MapName "c0220", # Location 0x000D, # MapIndex "ed7100", 0x00002000, # Flags ...
import FWCore.ParameterSet.Config as cms HistosFromPAT = cms.EDAnalyzer('Zprime2muHistosFromPAT', lepton_src = cms.InputTag('leptons', 'muons'), dilepton_src = cms.InputTag('dimuons'), leptonsFromDileptons = cms.bool(False), ...
from wild_relation_network.relation_network import RelationNetwork from wild_relation_network.wild_relation_network import WReN
class ProductOrder(object): """This class creates instances of Orders Orders follow the following structure: 'Header': '1', 'Lines': [ {'A': '1'}, {'B': '2'}, {'C': '3'}, {'D': '4'}, {'E': '5'} ...
from sqlalchemy import create_engine#Don't mix the "import" below in one line. from sqlalchemy import Table, MetaData#This import should be one line # Set up an enigne interface for the database engine = create_engine( "postgresql+psycopg2://YXiong:X4Rw-#0AB1925(8@DOTQASIMSPGSQL1.dot.nycnet:5432/sims") # eng...
# Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). # # For example, given a 3-ary tree: # #   # # # #   # # We should return its level order traversal: # # # [ # [1], # [3,2,4], # [5,6] # ] # # #   # # Note: # # # The depth...
#! /usr/bin/env python3 # Filename: using_os.py import os print (os.name) print (os.getcwd()) folds = os.listdir() for filename in folds: print (filename)
import sys import os f = open("C:/Users/user/Documents/python/ant/import.txt","r") sys.stdin = f # -*- coding: utf-8 -*- n = int(input()) a = list(map(int,input().split())) ans = 0 for i in range(n): for j in range(i+1,n): for k in range(j+1,n): len = a[i] + a[j] + a[k] ...
class BoardViewTerminal: def draw(self, board): size = board.get_size() temp = [] # Board is size*2 to draw planks in between for i in range(size[1]*2): temp_row = [] for j in range(size[0]*2): temp_row.append(' ') temp.append(temp_row) #Draw the stumps first for st...
#!/usr/bin/env python MAX_INPUT_NUMBER = 5000000 # chain_len[i] is the length of a chain starting at i; e.g., the chain starting # at 6 has length 9 (6, 3, 10, 5, 16, 8, 4, 2, 1), so chain_len[6] = 9 chain_len = [None for x in range(MAX_INPUT_NUMBER + 1)] chain_len[1] = 1 # longest_chain[i] is the number n that star...
import matplotlib.pyplot as plt #from ai import MCUCT from ai_dnn import MCUCT_DNN from gomoku_board import GomokuBoard plt.ion() #ai = MCUCT(GomokuBoard, C=0.3, min_num_sim=3e4) ai = MCUCT_DNN(GomokuBoard, min_num_sim=2**10, load_path=r'./dnn_data/v1', training_mode=True) game_board = GomokuBoard() ax = None whil...
import numpy as np import torch from models.MLP import MLP class Ensemble(): """ Creates an ensemble of neural network functions with randomized prior functions (Osband et. al. 2018). """ def __init__(self, params): self.params = params self.kappa = self.params['kappa'] s...
#---- # K近邻算法 #---- from numpy import * import operator import matplotlib import matplotlib.pyplot as plt #---------------------create data set----------------------------------------- def createDataBase(): group = array([ [1.0, 1.1], [1.0, 1.0], [0., 0.], [0., 0.1]]) labels =...
# coding=gbk # from register_or_login import * from classInformation2 import * from YanjiuInfomation2 import * from selfinformation_user import * def user_hanshu(ID): print("你现在是用户了。\n") print("用户只能1.添加个人信息,2.更改个人信息,3.查询个人信息,4.查看个人教学信息,5.查看个人科研信息,6.添加个人研究信息\n") choose = input("请输入你要进行的操作,输入0退出程序,输入...
# A function is a block of code which only runs when it is called. In python, we do not use curly braces we use indentation tabs or spaces # Create a function def sayHello( name ): print( "Hello "+ name ) name = "Thembekile Mkhombo" sayHello( name ) # Return value x = 9 y = 8 def getPum( nu...
from common import get_primes PRIMES = set(get_primes(10000000)) def quadratic_prime(a, b): i = 0 while True: s = i ** 2 + a * i + b if s not in PRIMES: return i i += 1 if __name__ == "__main__": n = 1000 a = 0 b = 0 maximum = 0 for i in range(-n + 1, n)...
from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, *args, timestamp): return six.text_type(args.id)+six.text_type(timestamp)+six.text_type(args.Verified)
from flask import session, render_templates, redirect, url_for, flash from application import app from application.models.data_manager import * @app.route('/login', methods=['GET','POST']) def login(): if request.method == 'POST': accounts = data_manager.load_account() print request.form for acc...
import numpy as np FACE_POINT = ( 107, 55, 105, 52, 70, 46, 336, 285, 334, 282, 300, 276, 159, 144, 33, 133, 386, 373, 362, 263, 17, 61, 291, 0, 78, 308, 14, 13, 10, 297, 389, 356, 288, 378, 152, 149, 58, 127, 162, 67, 50, 280) # 10부터 시계방향 50,280(왼쪽 광대, 오른쪽 광대) POSE_POINT = { 'NOSE': 0, 'LEFT_SHOULDER': 1...
import datetime import requests from urllib.parse import urlencode import base64 client_id = '913e8eccae4e44dd90c3ce3ff8933be2' client_secret = 'eec2117dcbf84d5498608a1259059d27' class SpotifyAPI(object): access_token = None access_token_expires = datetime.datetime.now() client_id = None clie...
numero = str(input("Digite o número:")) b = numero.split() normal = " ".join(b) aocontrario = "" for letra in range(len(normal)-1, -1, -1): aocontrario += normal[letra] print(normal, aocontrario) if normal == aocontrario: print("O seu número é um palindromo") else: print("O seu número não é um palidromo")
import os import os.path from unittest.mock import patch from programy.mappings.properties import PropertiesCollection from programy.storage.stores.file.config import FileStorageConfiguration from programy.storage.stores.file.engine import FileStorageEngine from programy.storage.stores.file.store.properties import File...
from aiohttp import web from gql import gql, Client from gql.transport.aiohttp import AIOHTTPTransport import yaml from datetime import datetime import aiohttp import asyncio import os from rich import print # /echo GET _echo_ # handler #async def _tick_(request): #try: # 0 : extract payload dict ...
from app import cfg from app import db from app import util from flask import Blueprint from flask import jsonify from flask import render_template from flask import request import math bp_bans = Blueprint('bans', __name__) @bp_bans.route("/bans") def page_bans(): page = request.args.get('page', type=int, default=...
from behave import given, then, when # import testovane funkce from src.count_words import count_words @given(u"a sample text") def a_sample_text(context): assert context.text context.input = context.text @when(u"I count all words in text") def step_impl(context): """Zavolani testovane funkce.""" c...
# # Reconciliation library for dup/loss/deep coalescence # Based on three-tree model of DLCoal # # python libraries import sys import copy # rasmus libraries from rasmus import util from rasmus import treelib # compbio libraries from compbio import phylo, coal #======================================================...
import os import shutil import urllib.request MUSIC_FOLDER = 'C:\\Users\\avathar\\Music\\KHinsider\\' def save_file_from_url(url, file_name): # Download the file from `url` and save it locally under `file_name`: directory = MUSIC_FOLDER + file_name.split('/')[0] if not os.path.exists(directory): ...
# -*- coding: utf-8 -*- # <nbformat>2</nbformat> # <codecell> def TwoSum(lst, target): ''' 2-SUM algorithm via hash table. O(n) time. ''' global hashTable for x in lst: y = target-x if y in hashTable and x != y: return True return False # <codecell> lin...
from db import db class AnswerModel(db.Model): __tablename__ = 'answers' id = db.Column(db.Integer, primary_key=True) choice = db.Column(db.String) is_selected = db.Column(db.Integer) is_correct = db.Column(db.Integer) question_id = db.Column(db.Integer, db.ForeignKey('questions.id')) que...
hour = int(input()) minutes = int(input()) final_minutes = 0 if minutes < 45: final_minutes = minutes + 15 elif minutes >= 45: final_minutes = minutes + 15 - 60 hour = hour + 1 if hour == 24: hour = 0 if final_minutes < 10: print(f'{hour}:0{final_minutes}') else: print(f'{hour}:{final_minutes...
import pandas as pd import numpy as np from sklearn import linear_model from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error train = pd.read_csv('winequality-red.csv') # Handling missing value data = train.select_dtypes(include=[np.number]).interpolate().dropna() # Top...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # align-docs.py # # Copyright (C) 2018 Frederic Blain (feedoo) <f.blain@sheffield.ac.uk> # # Licensed under the "THE BEER-WARE LICENSE" (Revision 42): # Fred (feedoo) Blain wrote this file. As long as you retain this notice you # can do whatever you want with this stuff....
"str -> String" print(type("Cadena de Texto")) "int -> Integer (Entero)" print(type(10)) "float -> Numero de Punto Flotante" print(type(10.5)) "bool -> Boleanos" print(type(True)) print(type(False)) "list -> Listado de Elementos" frutas = ["Manzana", 1, True] print(type(frutas)) "tuple -> Tupla" frutas2 = ("Manzan...
import logging from utility.services import Services class CasinoPage: def __init__(self, driver): self.driver = driver self.services = Services(self.driver) self.title = "Exclusive Casino Games - Best online casino | Optibet" self.casino = "//a[@data-role='Casino']" def verif...
# -*- coding: utf-8 from django.contrib.auth import login from django.conf import settings from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseRedirect from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import...
import discord import os from discord.ext import commands from discord.utils import get import asyncio import json THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) my_file = os.path.join(THIS_FOLDER, '../db/skids.json') class Skids(commands.Cog): @commands.command() @commands.guild_only() async def addsk...
# -*- coding: utf-8 -*- __author__ = 'MoroJoJo' import os import datetime import time import tushare from stl_utils import stl_logger as slog from stl_utils import stl_thread_pool as stp from stl_data_manager.tushare import stl_dm_fundamental as sfund ''' 获取证券股票的指定交易日的分笔(TICK)行情信息 ''' # Global Consts USING_CSV ...
# Sample Python script for reading a file and calling an external REST API from dg.CardClient import CardClient from dg.LineParser import LineParser from dg.CardResponse import CardResponse from dg.RecordDAO import RecordDAO from config import config from cryptography.fernet import Fernet from dg.FileService i...
import calendar from django.utils.deconstruct import deconstructible @deconstructible class YearlessDate(object): "An object representing a date in a year (but not a year itself). Suitable especially for birthdays, anniversaries etc." def __init__(self, day, month): self.day = int(day) self.m...
# MIT License # # Copyright (c) 2016 David Sandberg # # 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, me...
from collections import UserDict class FloatStrDict(UserDict): def __missing__(self, key): if isinstance(key, str) and '.' in key: raise KeyError(key) return self[str(float(key))] def __contains__(self, key): return str(float(key)) in self.data def __setitem__(...
import SubClass import pickle import json with open("config.json")as js: store=json.load(js) ObjL=[] ObjTemp=[None]*len(store["SubNames"]) FileName="ObjectPickle.pick" def initia(): PickleW=open(FileName,"wb") SubNames=store["SubNames"] SubPrio=store["Sub...
import numpy as np import pandas as pd import os import pickle from sklearn.model_selection import KFold from sklearn.metrics import precision_recall_curve import sklearn.metrics as metrics from model import lightgbm_train from glob import glob from utils import * import shap def load_data(all_fpath, n, f): """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from argparse import ArgumentParser, RawDescriptionHelpFormatter, ArgumentDefaultsHelpFormatter import boto3 import numpy as np DESCRIPTION = """ Approve workers for an individual HIT. Usage ----- >>> export AWS_ACCESS_KEY_ID=<MTurk access key id...
import datetime from faker import Faker from sqlalchemy import Column, Integer, String, Date, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() fake = Faker('en_US') class Customer(Base): __tablename__ = 'customers' __table_args__ = {'mysql_charset': 'utf8',...
#!/usr/bin/python # -*- coding: utf-8 import os, sys, time, mechanize, itertools, datetime, random, hashlib, re, threading, json, getpass, urllib, cookielib from multiprocessing.pool import ThreadPool P = '\x1b[1;97m' M = '\x1b[1;91m' H = '\x1b[1;92m' K = '\x1b[1;93m' B = '\x1b[1;94m' U = '\x1b[1;95m' O = '\x1b[1;96m'...
import os import shutil import numpy as np import tensorflow as tf os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3' from model import * from plot import * class CTR(Model): def _session(self): config = tf.ConfigProto(device_count={"gpu": 0}) config.gpu_options.allow_growth = True return tf.Sessi...
import datetime last_id = 0 class Note: def __init__(self, memo, tags =''): ''' A Note is contained in a Notebook :param memo: :param tags: ''' self.memo = memo self.tags = tags self.date = datetime.date.today() global last_id last...
n=int(input("enter the number of disks")) def hanoi(n,source,destination,temp): if n==1: print("move disk 1 from rod",source,"to rod",destination) return elif(n>1): hanoi(n-1,source,temp,destination) print("move disk",n,"from rod",source,"to rod",destination) hanoi(n-1,te...
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False] * len(s) + [True] word_set = set(wordDict) for i in range(len(s) - 1, -1, -1): for j in range(i, len(s) + 1): if s[i:j] in word_set and dp[j]: dp[i] = True ...
import scrapy import json class WearSpider(scrapy.Spider): name = "wear" dem = 0 start_urls = ['https://www.wear.com.vn/'] def parse(self, response): #kiểm tra điều kiện trang có trả về không, trang có phải là trang mô tả sản phẩm hay không if response.status == 200 and response.css('me...
from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from .api_views import get_or_create_token from rest_framework.test import APIClient from rest_framework import status class UserTest(APITestCase): def setUp(self): self....
""" This controller should create a child policy, update it and extend it """ from models.ChildPolicy import ChildPolicy from models.Driver import Driver from models.VehicleDetails import VehicleDetails from models.VehicleModifications import VehicleModifications from models.ICBenefits import ICBenefits from models.ICE...
#!/usr/bin/env python import numpy as np from spotmicro.Kinematics.LegKinematics import LegIK from spotmicro.Kinematics.LieAlgebra import RpToTrans, TransToRp, TransInv, RPY, TransformVector from collections import OrderedDict class SpotModel: def __init__(self, shoulder_length=0.055, ...
#!python3 #coding: utf-8 import random print ('********* 猜数字游戏规则 *********\n' '系统生成4次1-30的随机整数,每个用户猜4次,' '猜对的次数越多,排名越靠前。\n' '猜完后输入1到下一位用户,' '输入0结束游戏并打印出排行榜。\n' '·作者:谢育政 · 版本:Python3.6·\n' '**********************************') names_num = {} # 猜中多少次,key为名字,value为变量count(猜中的次...
from typing import List, Optional from tea_client.models import TeaClientModel from paperswithcode.models.page import Page class Dataset(TeaClientModel): """Dataset object. Attributes: id (str): Dataset ID. name (str): Dataset name. full_name (str, optional): Dataset full name. ...
''' This module includes SQL queries to answer the questions from the assignment for week 12, day 1. ''' import sqlite3 import numpy as np conn = sqlite3.connect('rpg_db.sqlite3') curs = conn.cursor() # How many total Characters are there? query = """SELECT COUNT(character_id) FROM charactercreator_character AS cc...
# Under MIT License, see LICENSE.txt from RULEngine.Util.geometry import Position, get_angle, get_distance import timeit as t import math as m from StrategyIA.UltimateStrat.InfoManager import InfoManager __author__ = 'RoboCupULaval' class RVOPathfinder: """Pathfinder qui esquive les obstacles mobiles. Calcu...
#!/usr/bin/env python # PyVision License # # Copyright (c) 2006-2008 David S. Bolme # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above c...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __author__ = 'AJay' __mtime__ = '2019/4/15 0015' """ from pymongo import MongoClient, ASCENDING from settings import MONGO_PORT, MONGO_IP class Mongo(): def __init__(self, ip=MONGO_IP, port=MONGO_PORT): conn = MongoClient(ip, port) self.db = con...
import os #imput pi=float(os.sys.argv[1]) radio=float(os.sys.argv[2]) #processing area_circunferencia=(pi*radio) #output if(area_circunferencia<=24): print("esta pequeño")
# 12) Crear un programa que muestre los números del 15 al 5, descendiendo (pista: en cada pasada habrá # que descontar 1, por ejemplo haciendo i=i-1, que se puede abreviar i--). count = 16 while count > 5: count -= 1 print(count)
#this file is for crawling game info from the store_page with game id #what we try to have: #game mode #game genre #user define game genre(probably not) #release date #<td class="span3">Genres</td> #<td>Action,Adventure,Massively Multiplayer,Simulation,Early Access</td> import urllib2 from bs4 import BeautifulSoup i...
import FWCore.ParameterSet.Config as cms import sys process = cms.Process("RawToDigi") process.load("FWCore.MessageService.MessageLogger_cfi") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) # Input source process.source = cms.Source("NewEventStreamFileReader", fileNames = cms.untrack...
from django.db import models from constants import CHARACTER_CHOICES, WEAPON_CHOICES, ROOM_CHOICES from clue.models import Game, Player, PlayerCard class GameSuggestion(models.Model): game_player = models.ForeignKey(GamePlayer) character = models.CharField(max_length=2, choices=CHARACTER_CHOICES) weapon = ...
''' Find the probability of a die roll being an odd or prime number. ''' from sympy import FiniteSet s = FiniteSet(1, 2, 3, 4, 5, 6) a = FiniteSet(2, 3, 5) b = FiniteSet(1, 3, 5) e = a.intersect(b) print(len(e)/len(s))
import unittest import dim_color class TestDim(unittest.TestCase): def test_dim_color(self): self.assertEqual(dim_color.dim_color("000"), "000") self.assertEqual(dim_color.dim_color("#000"), "#000") self.assertEqual(dim_color.dim_color("000000"), "000000") self.assertEqual(dim_colo...
#!/usr/bin/python -tt def FirstReverse(strng): return ''.join(strng[::-1]) def main(): result = FirstReverse("I Love Code!") print result if __name__ == "__main__": main()
#Parth Dodiya:171CO215 class LinkedList: """Defines a Singly Linked List. attributes: head - a pointer to the first node object """ def __init__(self): self.head = ListNode() """ This is the constructor. It tells you what are the attributes of all objects belonging to this class. You ...
from base import analyze_file # [("1", "2"), ("3", "4")] # [{'username': 'xiaoming', 'password': 'xiaoming123'}, {'username': 'xiaohong', 'password': 'xiaohong'}] def analyze_file_with_key(key): script_data = analyze_file("search_data")[key] script_list = list() for i in script_data.values(): scri...
soubor=open("zadani.txt","r") zadani=soubor.read().split("\n") soubor.close() while len(zadani) > 0: a=int(zadani.pop(0)) print("1/"+str(a)+"="+str(1/a)+"\npředperioda: "+"\nperioda: ") cislo=list(str(1/a))
#!/usr/bin/env python # # colourmaps.py - Manage colour maps and lookup tables for overlay rendering. # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # """This module manages the colour maps and lookup tables available for overlay rendering in *FSLeyes*. The :func:`init` function must be called before any colour ...
# -*- coding: utf-8 -*- # # Copyright 2015 Grigoriy Kramarenko <root@rosix.ru> # # This file is part of RosixDocs. # class AbstractClass(object): """ Использование класса:: a = AbstractClass() print a.test() """ attr = 'атрибут класса' def test(self, s='test class'): ...
# Generated by Django 3.0.1 on 2019-12-28 13:15 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('records', '0013_auto_20191228_1225'), ] operations = [ migrations.RenameField( model_name='record'...
import requests from lxml import etree from db.MongoDB.pm import MongodbClient db = MongodbClient(db="SpiderData", table="nikki_guide") key_word = ["属性", "技能推荐", "TAG", "要求属性", "对方技能", "注", "下一关", "NPC技能", "背景", "tag", "推荐技能", "tag:海军风"] def barrier(url=None): result = [] try: if not url: ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import argparse import facenet import os import sys import math import pickle from sklearn.svm import SVC """ Regenerates or creates the embedding classifier""" cla...
from selenium.webdriver.common.by import By class LambdaPageLocators(object): TXT_ALL_INTEGRATIONS = (By.XPATH, "//a[text()='See All Integrations']") TXT_CODELESS_AUTOMATION = (By.XPATH, "//a[text()='Codeless Automation']") LINK_TESTING_WHIZ = (By.XPATH, "//a[contains(@href,'testingwhiz-integration/') an...
def parse(programs, move): instruction = move[0] if move[0] == "s": programs = spin(programs, int(move[1:])) elif move[0] == "x": programs = exchange(programs, int(move[1:].split("/")[0]), int(move[1:].split("/")[1])) elif move[0] == "p": programs = partner(program...
# Generated by Django 2.2 on 2019-05-19 17:54 from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Cpu', fields=[ ...
from flask import Flask from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_mail import Mail from flaskblog.config import Config from flask_script import Manager from flask_migrate import Migrate, MigrateCommand ...
import pandas as pd import os import requests import zipfile from zipfile import ZipFile import numpy as np import scipy from scipy.optimize import leastsq, least_squares, minimize import matplotlib.pyplot as plt from statistics import mean import io from functools import reduce class ResidentialFloorspace: """C...
def solution(user_id, banned_id): answer = 1 for banid in banned_id: available = {} n = len(banid) for userid in user_id: if n == len(userid): available[userid] = True for i in range(n): if banid[i] == '*': continue ...
def count_trees(forest, step): pos = (0, 0) nr_trees = 0 while pos[1] < len(forest): if forest[pos[1]][pos[0] % len(forest[0])] == '#': nr_trees += 1 pos = (pos[0] + step[0], pos[1] + step[1]) return nr_trees with open("./input.txt") as f: forest = [] for row in ...
import time import os import matplotlib matplotlib.use("AGG") import matplotlib.pyplot as plt import numpy from datetime import datetime from datetime import date from datetime import timedelta import random import shelve historyFile = "./record" plotFile = "./history.png" def measureNewDatapoint(): return random.ra...
# -*- coding: utf-8 -*- import tkinter from tkinter import ttk import paho.mqtt.client as mqtt broker_ip = # input ip address of mosquito server broker_user = # input user of mosquito server broker_password = # input pasword of mosquito server broker_port = # input port of mosquito server StatusConnect...
from ibllib.io.video import VideoStreamer FRAME_ID = 4000 # example 1: with URL directly url = "http://ibl.flatironinstitute.org/mainenlab/Subjects/ZM_1743/2019" \ "-06-17/001/raw_video_data/_iblrig_leftCamera.raw.00002677-a6d1-49fb-888b-66679184ee0e.mp4" vs = VideoStreamer(url) f, im = vs.get_frame(FRAME_ID) ...
import tkinter from tkinter import messagebox e1=0 e2=0 proent=ens=en1=en2=en3=en4=en5=en6=en7=en8=en9=c1=0 gsum=0 w=0 def clear(): en1.delete(0) en2.delete(0) en3.delete(0) en4.delete(0) en5.delete(0) en6.delete(0) en7.delete(0) en8.delete(0) en9.delete(0) proent.delete(0) e...
#!/usr/bin/env python from optparse import OptionParser """ UnderstandingOptparse.py: a try to understand optparse library """ if __name__ == "__main__": parser = OptionParser() parser.add_option("-l", # short option string "--loglevel", # long option string ...
from Bio import SeqIO import argparse import sys parser = argparse.ArgumentParser(description="Change amino acids to predetermined codons") parser.add_argument("protein_fasta", type=str, help="fasta protein file") parser.add_argument("output", type=str, help="output file name") parser.add_argument("--afterburner", hel...
# Written by Ragavendran Lakshminarasimhan(z5179974) for COMP9021 import sys import re filename = input('Which data file do you want to use? ') try: redundancy = open(filename, 'r').readlines() except FileNotFoundError: print("File doesn't exist. Quitting") sys.exit() coordinates = dict(...
"""Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are so...
import random def hangman(): #cool spanish words! (there are so many more :D) words = ["quijotesco", "sabotaje", "amazona", "aquelarre", "escalofrios", "aparato", "consciente", "asertividad", "juego", "ahorcado"] random_number = random.randint(0, 4) word = words[random_number] ...
numTest = int(2e6 + 1) numLists = [] for i in range(numTest): numLists.append(True) sum = 0 for i in range(2, numTest): if numLists[i]: sum += i j = i * i while (j < numTest): numLists[j] = False j += i print sum
import time import logging from uuid import uuid4 from itertools import count import fire import requests from config import douban from utils import config_log, load_cookies, request, config_driver class DouBan: def __init__(self, username): self.driver = config_driver() self.usern...