text
stringlengths
8
6.05M
# -*- coding: utf-8 -*- """ Created on Wed May 27 09:08:16 2020 @author: peter_goodridge """ from selenium import webdriver import time from selenium.common.exceptions import TimeoutException, ElementClickInterceptedException, NoSuchElementException, StaleElementReferenceException import json from datetime import ...
import os,sys, time from main.page.base import * from main.function.general import * from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium import w...
class BreadCrumb: def __init__(self, name, href): self.name = name if href == '/': self.href = href else: self.href = '/' + str(href) + '/'
import GameLogic.Unit from GameLogic.Barrack import BaseBarrack from GameLogic.Character import * from Vector2 import Vector2 class Tile: def __init__(self, _position: Vector2, _basicMoney: int, _enemyMoney: int): self._position = _position self._basicMoney = _basicMoney self._enemyMoney =...
""" 분해합 https://www.acmicpc.net/problem/2231 """ n = int(input()) data = [] for i in range(n): sum = 0 for j in str(i): sum += int(j) sum += i if sum == n: data.append(i) if len(data) == 0: print("0") else: print(min(data))
import matplotlib.pyplot as plt import numpy as np divisions = ["Div-a","Div-b","Div-c","Div-d","Div-e"] divisions_averge_marks = [70,82,73,65,68] boys_average_marks = [68,67,77,61,70] index = np.arange(5) width = 0.30 plt.bar(index,divisions_averge_marks,width,color='green', label = 'Division marks') plt.bar(index+...
# Copyright 2007-2011 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import sys from portage.dep import Atom, ExtendedAtomDict, best_match_to_list, match_from_list from portage.exception import InvalidAtom from portage.versions import cpv_getkey if sys.hexversion >= 0x3000000: b...
from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Dprofile @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): user = instance if created: dprofile = Dprofile(user=user) dprofil...
''' % captured as fn of Col_Gap ''' import numpy as np import scipy.stats as sts import matplotlib.pyplot as plt import scipy.constants as sc import scipy.special as scp import timeit start = timeit.default_timer() ymot = 0.008 # Diameter of Col Atoms G = 38.11e6 # See ln 96 Xi_D = 6.6 Xi_d = 0.15 E...
import unittest from katas.kyu_7.find_the_capitals import capitals class CapitalsTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(capitals('CoDeWaRs'), [0, 2, 4, 6])
import cv2 import numpy as np from src.image.utils import rgb2gray from src.video.video_reader import AviReader from src.image.utils import uv_2_motion_vector from src.image.utils import draw_motion_vectors from src.image.horn_schunk import HornSchunkFrame class HS_Estimate: def __init__(self,alpha,num_iter,vide...
# -*- coding: utf-8 -*- import io import json import yaml import os import glob import datetime import petname from django import forms import python_terraform from pydot import graph_from_dot_data from architect.manager.client import BaseClient from celery.utils.log import get_logger logger = get_logger(__name__) r...
from django.contrib import admin from .models import * admin.site.register(User) admin.site.register(Plan) admin.site.register(Previous_Plans)
# coding: utf-8 # In[96]: # 获得 id # http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=%s' % term_name # http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=cancer&retstart=3182080&retmax=100 # http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pmc&id=212403,45841...
#-*- coding=utf-8 -*- import os from datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) import pymysql SECRET_KEY = 'SSDFDSFDFD' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://user:password@localhost/db' # user,password,db换成你的 SQLALCHEMY_TRACK_MODIFICATIONS = True debug = True MAIL_...
from __future__ import unicode_literals import locale import unittest from datetime import datetime from decimal import Decimal from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from django.utils import timezone from six import text_type from six.moves.u...
import unittest from katas.kyu_6.autocomplete_yay import autocomplete class AutocompleteTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(autocomplete( 'ai', ['airplane', 'airport', 'apple', 'ball']), ['airplane', 'airport']) def test_equals_2(self): ...
from __future__ import annotations import os import sys from typing import Any, BinaryIO, Optional, Tuple, Type, TypeVar, Union import PIL.Image import torch from torchvision.prototype.utils._internal import fromfile, ReadOnlyTensorBuffer from torchvision.tv_tensors._tv_tensor import TVTensor D = TypeVar("D", bound...
#!/usr/bin/env python3 """A simple script used to download files to the target system. Uses Python 3""" import argparse import requests def get_arguments(): """Get user supplied arguments from terminal.""" parser = argparse.ArgumentParser() # arguments parser.add_argument('-t', '--target', dest='t...
import pyautogui, time import random time.sleep(5) f=open("instagram_comments.txt",'r') for word in f: ccc = random.randrange(1,5,2) cc = random.randrange(1,8, 3) c = random.randrange(20,30, cc) print('2.SLeeping time: ') print(c) pyautogui.typewrite(word) time.sleep(ccc) print('1.Sle...
# Generated by Django 3.1.7 on 2021-04-01 21:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Gestion', '0001_initial'), ] operations = [ migrations.AlterField( model_name='hijo', name='id', field=m...
#!/usr/bin/python import simplejson import urlib import urllib2 url = "https://www.virustotal.com/vtapi/v2/url/scan" parameters = {"url": "https://www.virustotal.com/vtapi/v2/url/scan", "apikey": "af492b1351def36003ae0d7e8210bf000c8c52d5c1a7e37a057af865f90c5937"}
# coding=utf-8 """ 题目: 输入数字n,按顺序打印从1到最大的n位十进制数.比如输入3,则打印出1、2、3一直到到最大的3位数999 """ import sys def increment(number_char_array): # 进位 carry = 0 is_overflow = False for index in reversed(range(len(number_char_array))): number = int(number_char_array[index]) + carry if index == len(number_ch...
import matplotlib.pyplot as plt import numpy as np from astropy.io import fits import h5py import healpy as hp from pytest import approx from glob import glob import multiprocessing as mp from multiprocessing import Pool from joblib import Parallel, delayed import huffman from scipy.interpolate import interp1d fro...
class Data: def __init__(self, p): self.p = p def variance(self): self.variance = 0 for i in self.p: self.variance +=(i-(sum(self.p)/len(self.p)))**2 print(self.variance/(len(self.p)-1)) def mean(self): print(sum(self.p)/len(self.p)) def sd(self): self.variance = 0 for i in self.p...
import numpy as np from cloudmetrics.utils import make_periodic_mask def _parse_example_mask(s): return np.array([[float(c) for c in line] for line in s.strip().splitlines()]) EXAMPLE_MASK = _parse_example_mask( """ 00011000 11000011 11011011 00011000 00000000 00000000 00011000 00011000 """ ) EXAMPLE_MASK...
""" Brenna Carver & Cece Tsui CS349 Final Project Spring 2017 """ from sklearn.feature_extraction.text import TfidfVectorizer import json import numpy as np def getAverageRatings(filename, type): ''' Returns a dictionary consisting of user or business ids as keys and average rating as values ''' ratingDict = {} ...
MOD = int(1e9 + 7) class Solution(object): def findPaths(self, m, n, N, i, j): dp = [{} for _ in range(N + 1)] dp[0][(i, j)] = 1 dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)] ans = 0 for step in range(1, N + 1): for r, c in dp[step - 1]: # 前一个能抵达的状态 ...
from gdstorage.storage import GoogleDriveStorage, GoogleDrivePermissionType, \ GoogleDrivePermissionRole, GoogleDriveFilePermission from django.conf import settings if settings.GDRIVE_USER_EMAIL: permission = GoogleDriveFilePermission( GoogleDrivePermissionRole.READER, GoogleDrivePermissionTyp...
from __future__ import division import hercubit # import saved_data import pickle import sklearn from sklearn import datasets, svm import pandas as pd import numpy as np import matplotlib.pyplot as plt import pylab as pl try: import mpld3 from mpld3 import enable_notebook from mpld3 import plugins en...
# -*- coding: utf-8 -*- # To change this template, choose Tools | Templates # and open the template in the editor. import memcache def getCache(): return memcache.Client(['127.0.0.1:11211'],debug=0)
from arago.actors import Router class ShortestQueueRouter(Router): """Routes received messages to the child with the lowest number of enqueued tasks""" def _route(self, msg): # Try to simply find a free worker, first for item in self._children: if hasattr(item, "_busy") and not item._busy: return item #...
#!/usr/bin/env python2.7 # -*- coding: UTF-8 -*- import SimpleHTTPServer import SocketServer IP = "0.0.0.0" PORT = 8000 def main(): Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer((IP, PORT), Handler) print "serving at port", PORT httpd.serve_forever() if __name__ ...
from flask import Flask from be.view import auth, order, goods from flask import Blueprint from flask import request import logging bp_shutdown = Blueprint("shutdown", __name__) def shutdown_server(): func = request.environ.get("werkzeug.server.shutdown") if func is None: raise RuntimeError("Not runn...
from django.apps import AppConfig class PdfwebsiteConfig(AppConfig): name = 'pdfwebsite'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import pyqtSignal class progressWidget(QtWidgets.QDialog): progressClosed = pyqtSignal(int, name='progressClosed') def __init__(self): QtWidgets.QDialog.__init__(self) #self.s...
class Player(object): def __init__(self, name, cup=None): self.name = name self.cup = cup
import math class Point: def reset(self): self.x = 0 self.y = 0 def move(self,x=0,y=0): self.x = x self.y = y def calc_distance(self,anotherpoint): return math.sqrt((self.x -anotherpoint.x)**2 + (self.y - anotherpoint.y)**2) p1 = Point() p2 = Point() p1.reset()...
# A program that indexes the supplied corpus of documents and then iteratively asks for # search queries and provides results (as a list of file paths). If the search query contains # more than one word, consider this to be a Boolean AND query. from CONST import * from Directory_Listing import ListFiles from File_Rea...
from flask import Flask, render_template from flaskext.mysql import MySQL from werkzeug import generate_password_hash,check_password_hash app = Flask(__name__) mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'seproject' app.config['MYSQL_DATABASE_DB'] = 'IMS_DB1' app.c...
# usage: # results = analyze_free_exploration(filename='bag_free_17.txt') # # returns a dictionary, results: # results = { # 'pre': { # in the pre-app # 't0': 0, # time from start of app to first child action # 'total_duration': 0, # total duration of audio pla...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from dataclasses import dataclass from pants.backend.shell.lint.shfmt.skip_field import SkipShfmtField from pants.backend.shell.lint.shfmt.subsystem import Shfmt from pants.backend.shell....
from django.db import models class Article(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) email = models.EmailField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Employee(mod...
import pandas as pd import math RESULT_CSV_RAW_PATH = "D:/kostya_work/runtime-New_configuration/TestProject/experiments/Bengali_0_01/predictions/validation0.[0]-pr.csv" DST_PATH = "D:/kostya_work/runtime-New_configuration/TestProject/experiments/Bengali_0_01/predictions/validation0.[0]-pr-submission.csv" srcDF ...
from art import logo import time MENU = { "espresso": { "ingredients": { "water": 50, "milk": 0, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, ...
import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn.datasets.samples_generator import make_blobs ######################### fig = plt.figure() ax = p3.Axes3D(fig) ''' ax.set_xlabel('X') ax.set_ylabel('Y') ax.se...
print("[*] Position the windows so the text fits niceley inside the window!") from mss import mss import cv2 from PIL import Image import numpy as np import time from modules.config import * x, y = int(screen_resolution.split("x")[0]), int(screen_resolution.split("x")[1]) settings = {"top": int(0.08 * y) + adjust_y...
# Generated by Django 2.0.3 on 2018-03-13 04:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('static_pages', '0002_work'), ] operations = [ migrations.AlterModelOptions( name='page', options={'ordering': ['name'], 'ver...
from email import message from flask import Flask, render_template, request, redirect from cs50 import SQL # from flask_mail import Mail, Message SPORTS = [ "MMA", "Cricket", "Volleyball", "Skating", "Dodgeball", "Karate Kata", "Dance", "Chess" ] db = SQL("sqlite:///data.db") app = Fl...
# -*- coding: utf-8 -*- """ Created on Sun Sep 9 22:19:14 2018 Multiple Linear Regression Machine Learning A-Z Python @author: alyam """ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:,...
from riordan_utils import * from sage.rings.integer import Integer class AbstractPartitioning: def colours_table(self): return NumberedColoursTable() class IsPrimePartitioning(AbstractPartitioning): def partition(self, negatives_handling_choice, element): return negatives_handling_choice.d...
import gym from itertools import count from collections import deque from utils import SimpleMemory, preprocess, StatRecorder env = gym.make('Breakout-v0') obs = env.reset() total_steps = 1e3 n_frames = 3 memory = SimpleMemory() stats = StatRecorder def get_start_frames(n): frames = deque(maxlen=n) for i ...
from django.conf.urls import url,include from .views import * from django.views.static import serve from django.conf import settings from django.conf.urls.static import static # 张宸豪 urlpatterns = [ # url(r'^book/$', book_views), url(r'^book/(\d+)$', book_views), url(r'findpage/$',findpage_views), ] #廖万林...
import pygame import sys from random import randrange, choice def terminate(n=None): if n is None: pygame.quit() sys.exit() else: pygame.quit() sys.exit(n) class Board(pygame.sprite.Sprite): # Класс для спрайтов брёвен, плывущих по реке def __init__(se...
import cv2 import numpy as np import os import imutils import pytesseract suduku_arr = [[0 for _ in range(9)] for _ in range(9)] def detect_entire_block(filename): img=cv2.imread(filename,0) edges=cv2.Canny(img,100,200) cnts = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cnts = imutils.grab...
import unittest from _feature_objects.feature_screen import DevicesScreen from _feature_objects.feature_left_menu import * from _pages.pageLogin import LoginPage from _pages.pageMain import MainPage from selenium import webdriver class SmokeTest(unittest.TestCase): driver = None #global variable @classmeth...
import os.path as p import glob from pathlib import Path from typing import List, Tuple import numpy as np import faiss from SimSent.indexer.faiss_cache import faiss_cache __all__ = ['BaseIndexHandler'] class BaseIndexHandler(object): DiffScores = List[np.float32] VectorIDs = List[np.int64] FaissSearch...
from flask import Flask, request, jsonify import json app = Flask("__name__") @app.route("/index", methods=["POST", "GET"]) def req(): return jsonify({"code": 0, "msg": "hello word"}) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
import tweepy consumer_key = "P5wTozEUuNOAJCXMajGnRcDs2" consumer_secret = "RB7p2JVEZxbodmRT3eaA32caonxpo5fS5DOKXcoTxEKJelTZys" access_token = "997065391644917761-mSZZ6gkTdLEOdDSOAFfu7clvJO4vQPq" access_token_secret = "MoAMNPZeAmYMwtjaopDrAs1njCwmx9pdCmC7JBP0A1uxF" auth = tweepy.OAuthHandler(consumer_key, consumer_se...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import PurePath import pytest from pants.backend.terraform.hcl2_parser import resolve_pure_path def test_resolve_pure_path() -> None: assert resolve_pure_path(PurePath...
from django.contrib import admin from patients.models import Patient, RegisteredPatient, NotRegisteredPatient # Register your models here. admin.site.register(Patient) admin.site.register(RegisteredPatient) admin.site.register(NotRegisteredPatient)
import numpy as np import torch def target_distribution(name): w1 = lambda z: torch.sin(2 * np.pi * z[:, 0] / 4) w2 = lambda z: 3 * torch.exp(-0.5 * ((z[:, 0] - 1) / 0.6) ** 2) w3 = lambda z: 3 * torch.sigmoid((z[:, 0] - 1) / 0.3) if name == "1": u = lambda z: 0.5 * ((torch.norm(z, p...
import socket import os import subprocess import psutil import time import threading from queue import Queue import wmi from datetime import datetime, timedelta NUMBER_OF_THREADS = 2 JOB_NUMBER = [1, 2] queue = Queue() system_data = {"HostName": "", "UpTime": "", "CPU": ""} def host_name(): ho...
#-*- coding: utf-8 -*- print('''n = 123, f = 456.789, s1 = 'hello,world', s2 = 'hello, \\\'Adam\\\'\' s3 = r'Hello,"Bart"' s4 = r\'\'\'Hello, Lisa!\'\'\' ''') s1 = 'n = 123' s2 = 'f = 456.789' s3 = 's2 = \'hello, \\\'Adam\\\'\'' print(s3) print('''line1 line2 line3''')
import pygame import time pygame.init() # initialize the joystick pygame.joystick.init() joystick = pygame.joystick.Joystick(0) joystick.init() axes = joystick.get_numaxes() while True: for i in range(axes): # print out the axis values axis = joystick.get_axis(i) #s = 'Axis i: ' + axis print 'Axis %d:\t%6.4...
#! /usr/bin/python # coding=utf-8 import time import select import sys import os import RPi.GPIO as GPIO import numpy as np import picamera import picamera.array from picamera import PiCamera import matplotlib.pyplot as plt import matplotlib.image as mpimg import time import cv2 import math import threading from car ...
#! python3 import GetFromAPI import MyYouTubeDB import threading import datetime def MainRoutine(): # Run the process every N seconds Timer = 60.0 threading.Timer(Timer, MainRoutine).start() # called every minute Key = 'YOUTUBE-API-KEY' SelectedMethodNumList = [1, 6] SelectedUserNameList = [...
from apps.items.models import * from apps.inventory.models import * def add_ship_values(): ShipValues.objects.create( travel_time_multiplier = 5.0, travel_cost = 20, ) def add_rookie(): ShipTemplate.objects.create( ship_type = ShipTemplate.ROOKIE, size = ShipTemplat...
""" This prototype application is available under the terms of GPLv3 Permission for other licences can and probably will be granted if emailed at antimatter15@gmail.com. """ import httplib import pickle import urllib import json from optparse import OptionParser waveid = "googlewave.com!w+Mu9eK7j2H" parser = OptionPa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np def cloud_fraction(mask): """ Compute metric(s) for a single field Parameters ---------- field : numpy array of shape (npx,npx) - npx is number of pixels (cloud) mask field. Returns ------- cf : float ...
# The point of writing super() is to ensure that the next method in line # in the method resolution order (MRO) is called, which becomes important # in multiple inheritance # Note: super() can only be called if an ancestor inherits object eventually class Base(object): def __init__(self): print("Base init'...
import torch import torch.nn import os import numpy as np import matplotlib.pyplot as plt import glob import math from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_select...
"""Operate on pages in manual; extract data from zones and print to examination file.""" from operator import itemgetter import xmlStaticOperators import xmlChildSearch import xmlTableZoneExpander import os class xmlTableIdentifier(object): """ Identify two-column pages, search them for table zones and textz...
import re from getpass import getpass from users import check_password, encrypt_password, Users, Logs class InvalidAction(Exception): pass class MaxTries(Exception): pass class Interface: EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+") NUM_TRIES = 3 def __init__(self, users...
import csv import random import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Lambda from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.preprocessing.image import img_to_array, load_img from sklearn.model_selection import train_test_split fr...
class Player(object): def __init__(self, player): self.values = player def __eq__(self,other): return self.values == other.values '''We don't need this method anymore''' def getValidMoves(self, board): return board.getValidMoves() def makeMove(self, board, co...
import requests import datetime # for unix UTC conversion # COMPLEX WEATHER def fullData(): # GET URL AND ENTER KEYS key = input('Enter your API key: ') location = input('Enter the location to search: ') url = 'http://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=' + key # LOA...
#!/usr/bin/env python3 import asi import numpy as np import cv2 def main(): print('Warning: No checking for error return codes!') asi.ASIGetNumOfConnectedCameras() rtn, info = asi.ASIGetCameraProperty(0) frame_size = info.MaxWidth * info.MaxHeight asi.ASIOpenCamera(info.CameraID) asi.ASIInit...
def max_gap(numbers): nums = sorted(numbers) gap = 0 for i,n in enumerate(nums[:-1]): subt = abs(nums[i+1] - n) if gap < subt: gap = subt return gap ''' Task Given an array/list [] of integers , Find The maximum difference between the successive elements in its sorted form. Notes ...
#!/usr/bin/python """ ********************************************************************************************************************************************************** *Authors : Amar Bhagwandas Lalwani (MT2012073) and Raghav Bali (MT2012108) * *Date : May 18 2013 * *Project ...
import sys #import sys to get arguments mode=sys.argv[1] #command parsing if mode=="-help": #help screen print("USAGE:") print("python hertz.py hertz [pin] [length] [hertz] [debug]") print("eg. \"python hertz.py hertz 18 10 30\"") print("python hertz.py delay [pin] [length] [delay] [debug]") print("eg. \"python ...
# -*- coding: utf-8 -*- import scrapy import json import time from OwhatLab.conf.configure import * from OwhatLab.utils.myredis import RedisClient from OwhatLab.items import OwhatLabArticleItem, OwhatLabUserIterm class SpiderArticlesInfoSpider(scrapy.Spider): name = 'spider_articles_info' allowed_domains =...
import WorldElement class Toy(WorldElement): def __init__(self, color, shape): super(Toy, self).__init__(color, shape) def display(self): "Toy of color {0} and shape {1}".format(color, shape)
''' This program is used to fetch all the versions of library which user wants. Program used in the following way: python3 cdnjsFetch.py ${library name} After exec it, the program will create a new folder with the name of that library and include all the files in the subfolder named with version number. ''' import os i...
#from datetime import datetime,timedelta #creattime = datetime.now() #a = creattime.strftime('%d/%m/%Y %H:%M:%S') #print(a) #a={} #b = {} #b['c'] = 0 #a['b']= b #print(a) #a = {} #b = {} #b ['v'] = 1 #a ['b'] = b #a ['c'] = 1 #for i in a: # print(i) for i in range(10,100): for j in range(0,9): print(...
# Copyright 2017 Google Inc. # # 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 writin...
"""Finish all TODO items in this file to complete the isolation project, then test your agent's strength against a set of known agents using tournament.py and include the results in your report. """ import random directions = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)] class...
u = int(input()) while u > 0: n,x,t = map(int,input().split()) start = [] for i in range(n): start.append(i*x) #print(start) end = [] for i in range(n): end.append(start[i]+t) #print(end) stor = [] for k in range(n-1): a = end[k] cnt = ...
import sqlite3 as lite import sys def setupTables(name='P50Events.sqlite'): con=lite.connect(name) with con: cur = con.cursor() cur.execute("CREATE TABLE P50Muon(event INT,pulseTop REAL,pulseBot REAL,renormTop REAL,renormBot REAL,length REAL,time REAL)") def insertEvent(event,p...
class Solution(object): def findTilt(self, root): self.total = 0 def addtraverse(root): if not root: return 0 l = r = 0 if root.left: l = addtraverse(root.left) if root.right: r = addtraverse(root.right)...
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import os from model_utils import RnnEncoder from model_utils import TwoLayerMLP from vision import Vision from amdim.model import Model class Agent(nn.Module): def __init__(self, agent_hps=None, visio...
from colossus.apps.campaigns.tests.factories import ( CampaignFactory, EmailFactory, LinkFactory, ) from colossus.apps.subscribers.activities import render_activity from colossus.apps.subscribers.constants import ActivityTypes from colossus.apps.subscribers.tests.factories import ActivityFactory from colossus.test....
#!/usr/bin/env python3 import subprocess import os p1 = subprocess.Popen(["/usr/local/bin/processing-java", "--sketch=/home/pi/pi_cube/main", "--run"]) os.chdir("/home/pi/pi_cube/sol") p2 = subprocess.Popen(["python3", "sol.py"]) try: p1.wait() p2.wait() except KeyboardInterrupt: try: p1.termin...
# coding: utf-8 # ### Preprocessing Pipeline # 1. Create a BIDSDataGrabber Node to read data files # 2. Create a IdentityInterface - infosource Node to iterate over multiple Subjects # 3. Create following Nodes for preprocessing # - [x] Exclude 4 volumes from the functional scan # - [x] slice time correction #...
import os, sys, pygame from pygame.locals import * def load_image(fileName, colorkey=None): image = pygame.image.load(fileName).convert() if colorkey is not None: if colorkey == -1: colorkey = image.get_at((0,0)) # set colorkey to top-left pixel of image image.set_colorkey(colorkey, RLEACCEL) return image, i...
#!/usr/bin/env python import os import polib LOCALES = [ "br", "cs", "de", "el", "es", "fi", "fr", "it", "ja", "nl", "pt", "pt-br", "pl", "po", "ru", "sv", "tr", "zh-hant", ] OLD_TRANSLATION_MODULES = [ "", "admin", "dnstools", ...
from django.shortcuts import render from django.conf import settings from django.http.response import JsonResponse from django.views.decorators.csrf import csrf_exempt import stripe from users.models import Order @csrf_exempt def stripe_config(request): if request.method == 'GET': stripe_config = {'publ...
# -*- coding: utf-8 -*- class Solution: def minCostToMoveChips(self, chips): count_even, count_odd = 0, 0 for chip in chips: if chip % 2 == 0: count_even += 1 else: count_odd += 1 return min(count_even, count_odd) if __name__ == "_...
""" This is the file where I'll use everything I built to create a NN to do something (idk atm) """ from NeuralNetwork import * import numpy as np import matplotlib.pyplot as plt from Layer import * from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshap...
from ddd.painter2 import * from ddd.bresenham3 import * import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D tree = Vine() paint = Painter(tree) paint.build_tree_set() branches = paint.build_tree_set() fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') ax.set_xl...