text
stringlengths
8
6.05M
""" This file emulates the environment behavior for different scenarios. The grid is an m x m grid, m is either 8 or 4. Certain columns of this grid world push the agent up by some offset upon entering this column. The agent needs to learn this and move accordingly. """ import numpy as np class GridWorld8x8: ...
#_*_coding:utf-8_*_ from django.contrib.auth.models import (BaseUserManager) from django.utils import timezone from django.db import models class KxUserManager(BaseUserManager): def create_user(self,email,nick,password=None,**extra_fields): """ 创建一个用户,用户名是email,和密码 """ now = timezo...
# -*- coding: utf-8 -*- # @Time : 2018/9/20 10:41 # @Author : HLin # @Email : linhua2017@ia.ac.cn # @File : AlignedXceptionWithoutDeformable.py # @Software: PyCharm import math import logging from torchsummary import summary import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo class...
import json config = { "root_path": '', "data_download": '', "data_process": '', "delete_files_after_processing": '', "db": '' } config_values = json.loads(open('./config.json').read()) try: root_path = config_values['root'] except: root_path = '' print("Please add root_path value in config.json fold...
""" Faça um programa que leia um nome de usuário e sa sua senha e nçao aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. """ ''' nome = str(input('Digite seu nome: ')) senha = str(input('Digite sua senha: ')) while nome == senha: ...
from .base import FunctionalTest class AdminTest(FunctionalTest): def test_admin_site(self): # user opens web browser, navigates to admin page self.browser.get(self.live_server_url + '/admin/') body = self.browser.find_element_by_tag_name('body') self.assertIn('Django administratio...
from django.db.models.signals import pre_save from django.utils.crypto import get_random_string def set_etag(instance, **kwargs): instance.etag = get_random_string( length=instance._meta.get_field("etag").max_length ) pre_save.connect(set_etag, "todo.Event") pre_save.connect(set_etag, "todo.Calendar...
# 未解决 # 未解决 # 未解决 # 未解决 # 未解决 # 未解决 # 未解决 # 未解决 def number_of_1between1_and_n(num): if num < 0: return 0 elif num < 9: return 1 else: num = str(num) if int(num[0]) > 1: return 10 ** (len(num) - 1) + number_of_1between1_and_n(int(num[1:])) elif int(num[0]...
from django.urls import path from . import views urlpatterns = [ path('', views.index,name="index"), path('about/', views.about,name="about"), path('create/', views.create,name="create"), path('delete/<todos_id>', views.delete, name="delete"), path('update/<todos_id>', views.update, name="update"), ...
import copy import re from .naming import Ref try: from itertools import izip_longest as zipl except ImportError: from itertools import zip_longest as zipl class Any(object): pass class Matcher(object): """ Matcher of Ref patterns. """ __slots__ = ('_components', '_resolver') class Error(Exce...
''' Created on 18/10/2020 @author: Sergio Marsilli @facebook: Sergio.Marsilli.23 @twitter: Sergio_Marsilli ''' from time import time from cheesequeens.Board import Board from cheesequeens.StackNode import StackNode def rotate_matrix(m): return [[m[j][i] for j in range(len(m))] for i in range(len(m)-1,-1,-1)] def i...
#count the lines of a user-entered file fname = raw_input('Enter File:') try: fhand = open(fname) except: print 'File cannot be opened:', fname quit() count = 0 for line in fhand: count = count + 1 print count
# TODO: 添加提交订单时验证码判断
#CSCI 1133 Homework 6 #Sid Lin #Problem 7A class Complex(): def __init__(self, a = 0.0, b = 0.0): self.a = a self.b = b def __add__(self, rhand): newA = float(self.a) + float(rhand.a) newB = float(self.b) + float(rhand.b) c = Complex(newA, newB) return c de...
3#count the number of times letter "o" in the string "hello world" test_str="hello world" res={} for keys in test_str: res[keys]=res.get(keys,0)+1 print("count of all characters in hello world is:\n"+str(res))
#!/usr/bin/python3 """ Gets the dump of data from the given start and end times """ import urllib.request from datetime import datetime, timedelta import time import os import gzip import codecs import sys from subprocess import call def logging(s): with open('output', 'a') as f: s = '%s: %s' % (datetime....
from rv.api import m def test_modulator(read_write_read_synth): mod: m.Modulator = read_write_read_synth("modulator").module assert mod.flags == 8273 assert mod.name == "Modulator" assert mod.volume == 141 assert mod.modulation_type == mod.ModulationType.phase_abs assert mod.channels == mod.Ch...
#!/usr/bin/python import sys def climbing_stairs(n, cache=None): """ i guess we need to build up a map to show us how to come up with the answer we will start will a dictionary of places we have been and how many steps it takes to get there the steps will rely on one another for totals for instance 0:1, 1...
import csv from Source import DataPreprocessing NOT_AVAILABLE = 'not available' def negative_tweet_process(stop_words, emotions, slangs): sentiment = 'Negative' with open('../Data/processed/negative_processed.csv', 'w',encoding='UTF-8') as fw: write_line = csv.writer(fw, delimiter=',') with o...
''' Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of hash(t). Note: hash() is one of the functions in the __builtins__ module, so it need not be imported. ''' if __name__ == '__main__': n = int(input()) # Unnecessary line o...
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from SLGI.Pages.Prices_and_Performance import Prices_and_performance baseurl = "https://www.sunlifeglobalinvestments.com/Slgi/Prices+and+Performance?vgnLocale=en_CA" @pytest.fixture(scope='function', autouse=True) def...
# Generated by Django 2.1.2 on 2018-11-05 10:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('page', '0007_remove_filial_lokos'), ] operations = [ migrations.AlterModelOptions( name='loko', options={'ordering':...
from flask import session, request from flask_socketio import emit, join_room, leave_room from .. import socketio import time import requests from flask import copy_current_request_context from flask_socketio import join_room, leave_room import threading socket_ids = [] def repeat_every(n, func, *args, **kwargs): ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import os from pwn import * context(arch="amd64", os="linux") if not args["REMOTE"]: binary = ELF("./slot_machine-x86_64-2.28-4") # https://github.com/integeruser/bowkin libc = ELF("libs/x86_64/2.28/4/libc-2.28.so") argv = [binary.path] envp = {"PWD": ...
import re import requests from socketserver import StreamRequestHandler def create_handler(url): class CNGAdapterTCPHandler(StreamRequestHandler): regex = re.compile(r"\[REQUEST\s+(?P<name>\w+)\s*(?P<body>.*)\]") def handle(self): print(f"Handling new connection from {self.client_addre...
# Generated by Django 3.1.4 on 2020-12-04 13:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('district', '0001_initial'), ] operations = [ migrations.CreateModel( name='...
# Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. # # File: diet.py # # Purpose: Solving Stigler's Nutrition model (DIET,SEQ=7) # # Source: GAMS Model library, # Dantzig, G B, Chapter 27.1. In Linear Programming and Extensions. # Princeton University Press, Princeton, New Jer...
class WorksheetData(object): def __init__(self): self.appData = [] # each row of data is a list within appData self.appName = '' # name of Application self.worksheetName = '' # name of worksheet in Excel file self.headers = [] # header labels for Excel column self.pointMapPa...
from apiclient_jsonmarshal.marshallers import marshal_request, unmarshal_response
from aws_cdk import aws_ec2 as ec2 from aws_cdk import core """ can we use: aws_cdk.aws_ec2.BastionHostLinux construct? """ class BastionStack(core.Stack): def __init__(self, scope: core.Construct, id: str, vpc: ec2.Vpc, sg: ec2.SecurityGroup, **kwargs) -> None: super().__init__(scope, id, **kwargs) ...
from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, redirect, render from .forms import PostForm, CommentForm from .models import Group, Post, Comment, Follow def index(reque...
from axes.utils import reset from ipware.ip import get_ip from django.contrib import messages from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from django.utils.translation import ugettext as _ from .forms import AxesCaptchaForm def locked_out(req...
# Convertendo centimetros para polegadas centimetros = float(input('Entre com um comprimento em centimetros: ')) polegadas = centimetros / 2.54 print(polegadas)
""" Quick sort implementation in python. Not inplace - uses new arrays to copy the sub arrays """ def qsorter(uslist): if len(uslist) < 2: return uslist pivot = uslist[(len(uslist)//2)] left = [] right = [] center = [] for i in uslist: if i > pivot: right.append(i) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import datetime class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=False) phone...
# # # Date : 2016-9-26 # Author : lampson # Input : an array of numbers # Output : a sorted array by the binary heap # # import numpy as np def heapSort(data): lastRoot = len(data)/2 - 1 lastInd = len(data)-1 for i in range(lastRoot,-1,-1): heapAdjust(data,i,lastInd) # print i for i in r...
def gcd(a, b): while b > 0: a, b = b, a%b return a def lcm(a,b): return (a*b)//gcd(a, b) N = int( input()) T = [ int( input()) for _ in range(N)] ans = T[0] for i in range(1,N): ans = lcm(ans,T[i]) print(ans)
from django.db import connection def get_data(self): with connection.cursor() as cursor: cursor.execute( "SELECT count(death_manner.character_id),book_id FROM death_manner INNER JOIN death_book ON death_manner.character_id=death_book.character_id WHERE death_manner.manner IN('Slain (sword)', '...
from selenium import webdriver import unittest class GetSourceByChrome(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() #隐式等待 self.driver.implicitly_wait(10) def test_getPageSource(self): url = "http://www.baidu.com" self.driver.get(url) se...
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ ''' i and j are pointers so that left side has A[0:i] and B[0:j], and right side has A[i:] and B[j:]. Set up con...
import gym import random import numpy as np from gym import spaces class rtsTrade_env(gym.Env): def __init__(self): self.nbars_obs_real = 1300 self.nbars_obs = 40 self.nbars_game = 150 self.counter = 0 self.net = 0 self.prev_action = -1 self.returns = [] ...
from __future__ import annotations import functools from typing import Callable from typing import TypedDict from typing import Union import mypy.checker import mypy.checkmember import mypy.options import mypy.types from mypy.fixup import TypeFixer from mypy.nodes import ArgKind from mypy.nodes import NameExpr from m...
class HitCounter(object): def __init__(self): from collections import deque self.cnts = 0 self.hits = deque() def hit(self, timestamp): if not self.hits or self.hits[-1][0] != timestamp: self.hits.append([timestamp, 1]) else: self.hits[-1][1] += 1...
from django.urls import path from . import views app_name = 'posts' urlpatterns = [ path('', views.list, name='list'), path('posts_create/', views.posts_create, name='posts_create'), path('<int:post_pk>/', views.posts_detail, name='posts_detail'), path('<int:post_pk>/posts_delete/', views.posts_delete...
from PIL import Image, ImageEnhance import cv2 import time # Camera 0 is the integrated web cam on my netbook camera_port = 1 #Number of frames to throw away while the camera adjusts to light levels ramp_frames = 30 #Number of images taken t_passed = 0 img_count = 0 # Now we can initialize the camera capture objec...
# -*- coding: utf-8 -*- """ Updated 16 Dec 2017 10 sheep eat away at their environments 2 wolves are introduced which eat nearby sheep A record of the dead sheep is recorded on screen @author: Amanda Forbes """ import matplotlib.pyplot import matplotlib.animation import csv import agentframework import wolfframework ...
print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, L? ") add_pep = input("Do you want to add pepperoni? Y or N? ") add_cheese = input("Do you want to add extra cheese? Y or N? ") amt=0 if size == 'S': amt+=15 if add_pep=='Y': amt+=2 elif size == 'M': amt+=...
from dataloader import * DATA_PATH = "tempdata.csv" data = load_data(DATA_PATH) def get_date(datestamp): ''' Loads data for a specific date, given a datestamp in YYYYMMDD format ''' global data date = DataPoint.create_date(datestamp) print("Searching for {}".format(date)) filtered = list(...
ids = ['alex'] def solve_problem(input): pass # put your solution here, remember the format needed
from enum import IntEnum import math import random import attr import numpy as np from simulation.cell import CellData, CellList from simulation.coordinates import Point, Voxel from simulation.grid import RectangularGrid from simulation.modules.geometry import TissueTypes from simulation.random import rg MAX_PHAGOSO...
''' Created on 2018年3月24日 @author: wangs0622 ''' def power(base, exponent): if base == 0 and exponent < 0: raise ValueError("exponent must be not negative when base equals 0") if not isinstance(exponent, int): raise ValueError("exponent must be int") abs_exponent = exponent if expone...
import threading import timer from enum import Enum # Session response means the seesion with a query and response # It could answer the question which is asked by users # And it could give feedback to the QA pairs. class SessionState(Enum): hello = 0 asksuccess = 1 askfail = 2 postask = 3 reply_array=...
from collections import deque K = int( input()) V = [0]*K d = deque([(1,1)]) while 1: w, v = d.popleft() if v == 0: ans = w break if V[v] == 1: continue V[v] = 1 if V[ (v+1)%K] == 0: # if (v+1)%K == 0: %こちらは必ずしも最小とは限らないため、%以下の方はWA # ans = w+1 # ...
from flask import Flask,render_template,redirect,url_for,request,flash,session,logging,request,abort,g from passlib.hash import sha256_crypt from flask_login import login_user , logout_user , current_user , login_required, LoginManager from datetime import datetime from flask_sqlalchemy import SQLAlchemy app = Flask(...
import cv2 import numpy as np # input options in order (right->left): 'camera/rgb', 'camera/depth', 'slam/odom' class ObjectDetection: # Look for area of depth image that correlates to closest object # Look for same location in rgb/infra # Detect most "present" object (i.e. the closest object that might ...
import time import os,sys import xbmc, xbmcgui, mc import subprocess import common from random import randint def get_window_id(special): if special == True: return xbmcgui.getCurrentWindowDialogId() else: return xbmcgui.getCurrentWindowId() def get_list(listNum, special): try: lst = mc.GetWindow(get_window...
#-*- coding:utf8 -*- import time import json import datetime from django.db import models from shopback.base.models import BaseModel from django.contrib.auth.models import User as DjangoUser from shopback.signals import user_logged_in from shopback.base.fields import BigIntegerAutoField from shopback import paramconfig...
class TicTacToeNoBoard(object): class PlayerStatus(object): def __init__(self, n): self.rows = [0] * n self.cols = [0] * n self.dia = 0 self.adia = 0 def __init__(self, n): """ Initialize your data structure here. :type n: int ...
import os, json, pickle, logging import pandas as pd import src.model_prediction.forecast_evaluation_functions as forecast_evaluation_functions import src.model_prediction.benchmark_algorithms as forecast_functions from src.data_representation.Examples import load_Examples_from_file from src.data_representation.config_...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
import os import matplotlib as mpl import matplotlib.patches as patches import numpy as np import seaborn as sns import yaml from matplotlib import pyplot from autumn.projects.covid_19.mixing_optimisation.constants import ( DURATION_PHASES_2_AND_3, OPTI_REGIONS, PHASE_2_DURATION, PHASE_2_START_TIME, )...
""" Script for loading Bangladesh, Dhaka and Cox's Bazar data into calibration targets and default.yml NOTE you will need to pip instal lxml to run this script """ from typing import List import pandas as pd from pathlib import Path from autumn.settings import PROJECTS_PATH from autumn.settings import INPUT_DATA_PATH...
def get_class(id): if id == 'inet': import recent.deps.inet return recent.deps.inet.InetDep elif id == 'x11': import recent.deps.x11 return recent.deps.x11.X11Dep return None
import gzip import numpy as np from collections import OrderedDict import pickle from tqdm import tqdm import mmap def get_num_lines(file_path): fp = open(file_path, "r+") buf = mmap.mmap(fp.fileno(), 0) lines = 0 while buf.readline(): lines += 1 return lines def del_pos(s): """...
# -*- coding: utf-8 -*- """ Created on Sat Jun 07 16:27:47 2014 @author: Yunsheng Wei """ import matplotlib.pyplot as plt from helper import weighted_location, dist from configuration import outlier_dist_thres from helper import binary_search, weighted_location class Vehicle: def __init__(self...
'''this code was desinged by nike hu''' import torch import torch.nn as nn device = torch.device('cuda:0') # 鉴定器网络 class Discrimite(nn.Module): def __init__(self): super(Discrimite, self).__init__() self.conv = nn.Sequential( nn.Conv2d(3, 64, kernel_size=4, stride=2, pad...
# Test Agent import torch import torch.nn.functional as F from a3c_envs import create_atari_env from a3c_model import ActorCritic from torch.autograd import Variable import time from collections import deque # rank is to desync the test agent def test(rank, params, shared_model): # desynchronising the agents ...
# import the pygame module, so you can use it import pickle,pygame,time from pygame.locals import * from random import random, randint import numpy as np from queue import PriorityQueue #Creating some colors BLUE = (0, 0, 255) GRAYBLUE = (50,120,120) RED = (255, 0, 0) GREEN = (0, 255, 0) BLACK = (0, 0...
from django.apps import AppConfig class GetBankCsvConfig(AppConfig): name = 'get_bank_csv'
from bitarray import bitarray class Hamming: def calc_redundant_bits(self, n): for i in range(n): if(2**i >= n+i+1): return i def calc_parity_bits(self, data, r): n = len(data) for i in range(r): value = 0 for j in range(1, n+1): if(j&(2**i) == (2**i)): value = value ^ int(data[-1*j]) ...
''' We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. F...
from objcenter import ObjCenter from pid import PID from multiprocessing import Manager from multiprocessing import Process import imutils from imutils.video import VideoStream #import pantilthat as pth from adafruit_servokit import ServoKit import argparse import signal import time import sys import cv2 kit = ServoK...
/home/ajitkumar/anaconda3/lib/python3.7/reprlib.py
from django.db import models from user.models import User from project_management.models import Project # Tasks class Tasks(models.Model): task_description = models.TextField() assigned_to = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='assigned_to') created_by = models.Fore...
""" Author: Seph Pace Email: sephpace@gmail.com """ from settings import GLOVE_PATH class Tokenizer: """ Tokenizes sentences into sequences of tokens. Attributes: filter (str): Punctuation and other tokens to filter out. id_to_word (list): Converts ids to words. word_to_id (dict...
ops = open('in').readlines() for mut_idx in range(len(ops)): execed = set() acc = 0 ptr = 0 while ptr not in execed: #print(ptr, execed) line = ops[ptr] op = line[:3] if ptr == mut_idx: if op == 'jmp': op = 'nop' elif op == 'nop': op = 'jmp' if op == 'jmp'...
## this program gets a sequence of nodes ids and find their degree in the other given dataframe import pandas as pd new_edges_file_path = input("Enter the newly joined edges file path:\n >>> ") nodes_info_file_path = input("Enter nodes info file path:\n >>> ") new_edges = pd.read_csv(new_edges_file_path) nodes_...
def next_move(string): total = 0 tens = {"J":10, "K":10, "Q":10} num = [2, 3, 4, 5, 6, 7, 8, 9] for i in string: if i == "0": total += 10 if i in tens: total += tens[i] try: if int(i) in num: total += int(i) except: ...
class Solution: def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ if len(citations) == 0: return 0 l, r = 0, len(citations)-1 length = len(citations) while r-l > 1: m = l+(r-l)//2 if lengt...
from django.contrib import admin from flashsale.mmexam.models import Question,Choice,Result class ChoiceInline(admin.TabularInline): model = Choice extra = 4 class Qestiondmin(admin.ModelAdmin): list_display = ('id','question','single_many', 'pub_date', 'real_answer') ordering=['id'] inli...
from qiskit inport QuantumCircuit, QuantumRegister from math import ceil def QValue(n, R): size = ceil(log(n)) * n v = QuantumRegister(size) r = QuantumRegister(R) c = QuantumCircuit(v) # TODO: f(x) = value of traveling in the order with precision R bits #Example asuming the fields are bidire...
import random import copy allDemands = {(1, 4): 2, (4, 1): 2, (1, 3): 4, (3, 1): 4 , (2, 3): 5, (3, 2): 5, (4, 5): 5, (5, 4): 5, (3, 7): 6, (7, 3): 6 , (2, 5): 1, (5, 2): 1, (2, 7): 3, (7, 2): 3, (5, 6): 2, (6, 5): 2 } depot = 1 capacity = 7 minCost = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 8, 4, 2, 7, 20, 10], ...
import os import subprocess as sp from util import open_xml, serialize_manifest def revision_from_project(path): return sp.check_output(["git", "rev-parse", "HEAD"], cwd=path).strip() def freeze(f, output, b2g_root, gaia_branch, gecko_branch, moz_remotes=[], moz_branch=[]): node = open_xml(f) default_re...
from autumn.infrastructure.remote.buildkite.buildkite import ( BooleanInputField, CommandStep, InputStep, Pipeline, TextInputField, ) from .calibrate import burn_in_field, sample_size_field, trigger_field, chains_field, runtime_field run_id_field = TextInputField( key="run-id", title="Exis...
#!/user/bin/python #coding:utf-8 __author__='yanshi' from com.sy.util import data from collections import namedtuple import jieba import codecs from gensim.models import Doc2Vec import multiprocessing import numpy as np class Doc2vec(): def __init__(self, stopWordsPath, fileTitle, fileIntro): self.fileIn...
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.chrome.options import Options from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import telebot from telebot.util import async from logic import * import config class Object(object): pass F...
# -*- coding: utf-8 -*- import tkinter as tk # 使用Tkinter前需要先導入 import tkinter.messagebox # 要使用messagebox先要導入模組 # 第1步,產生實體object,建立視窗window window = tk.Tk() # 第2步,給窗口的視覺化起名字 window.title('My Window') # 第3步,設定窗口的大小(長 * 寬) window.geometry('500x300') # 這裡的乘是小x # 第5步,定義觸發函數功能 def hit_me(): tkinter.messagebo...
from flask_wtf import FlaskForm from wtforms import PasswordField, StringField, validators class LoginForm(FlaskForm): username = StringField("Käyttäjätunnus:") password = PasswordField("Salasana:") class Meta: csrf = False class NewUserForm(FlaskForm): name = StringField("Nimi:", [validato...
import json from witapi import WitAPI as wa from location import Location as lc from responseformat import ResponseFormat as rf from timechatbot import TimeChatbot as tc from geoInfo import GeoInfo as gi from outofscoperesponse import OutOfScope as oos from synonym import SynonymReplacer as sr from posTag_spellCheck im...
from requirementmanager.api.requirement.create import requirement_create from requirementmanager.api.requirement.delete import requirement_delete from requirementmanager.api.requirement.edit import requirement_edit from requirementmanager.api.requirement.profile import requirement_profile from requirementmanager.api.re...
#!/usr/bin/env python # ==================================================================================== # # # Copyright (c) 2017 Raffaele Bua (buele) # # 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 ...
#!/usr/bin/env python import unicornhathd import time # Get the width and height of the display width, height = unicornhathd.get_shape() def draw(): # Clear the display unicornhathd.off() # Clear the buffer unicornhathd.clear() # Set the rotation of the display unicornhathd.rotation(270) ...
#!/usr/bin/env python2.7 # encoding: utf-8 """ first_price_procurement.py Created by Jakub Konka on 2011-03-09. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ from __future__ import division import sys import os import numpy as np import scipy.integrate as integrate import matplotlib.pyplot as ...
from .models import (Message, METHOD_SMS, METHOD_SMS_CALLBACK, METHOD_SMS_SURVEY, METHOD_IVR_SURVEY, METHOD_EMAIL, METHOD_TEST, METHOD_SMS_CALLBACK_TEST, RECIPIENT_USER, RECIPIENT_CASE, RECIPIENT_SURVEY_SAMPLE, CaseReminder) from corehq.apps.smsforms.app import submit_unfinished_form from corehq.apps.sms...
import numpy as np import math def minibatch(X, Y, mini_batch_size): global mini_batches m = X.shape[1] mini_batches = [] #Shuffle the dataset permutation = list(np.random.permutation(m)) shuffled_X = X[:, permutation] shuffled_Y = Y[permutation] num_howmany_minibatches = math...
__all__ = ["FFCrawler"] from .FFCrawler import FFCrawler
from django.shortcuts import render from django.http import JsonResponse from django.template.loader import get_template from django.core.mail import EmailMultiAlternatives, send_mail from .models import * from . forms import CustomerForm # Create your views here. def BasketAdd(request): if request.POST: sess...
FAKER_SEEDER = 6789
from matplotlib import pyplot as plt ages_x=[25,26,27,28,29,30,31,32,33,34,35] dev_y=[11250,23456,32145,43251,49085,53213,59934,67890,76543,89065,90876] plt.plot(ages_x,dev_y,linewidth=3,label="All Devs") py_dev_y=[23456,29087,34215,40987,49086,54321,66543,71234,78451,89034,90876] plt.plot(ages_x,py_dev_y,marker...
import re with open('simpsons_phone_book.txt') as fh: for line in fh: if re.search(r".*Neu", line): print(line)