text stringlengths 8 6.05M |
|---|
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import tabletmanagerdata_pb2 as tabletmanagerdata__pb2
class TabletManagerStub(object):
"""TabletManager is a service definition for tabletmanagerdata.TabletManager.
Various read-only methods
"""
def __init__(self, channel):... |
"""
You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the dat... |
import requests
import pygame
import os
import math
x, y = 0, 0
w, h = 0, 0
def_l = 'map'
def_spn = '0.01,0.01'
def_ll = '30.25,59.947176'
def_pt = '30.25,59.947176'
lst = ['map', 'sat', 'skl']
n = 0
address = ''
size = 0.01
mp = False
index_status = False
index = ' '
sz_lst = [0.01, 0.1, 0.9, 1.8]
size_lst = [[0.013,... |
# Dependencies
import requests as req
# Performing a GET Request and saving the API's response within a variable
url = "https://api.spacexdata.com/v2/rockets/falcon9"
response = req.get(url)
response_json = response.json()
# It is possible to grab a specific value from within the JSON object
print(response_json["cost... |
__author__ = 'ou3'
from foqus_lib.gui.common.InputPriorTable import InputPriorTable
class InferenceInputsTable(InputPriorTable):
def __init__(self, parent = None):
super(InferenceInputsTable, self).__init__(parent)
self.typeItems = ['Variable', 'Fixed', 'Design', 'Uncertain']
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 1 15:55:42 2018
@author: andr
"""
import os
import numpy as np
add_period_list = list(range(1000))
pdot_list = [i/100 for i in range(-400, 400)]
for add in add_period_list:
for pdot in pdot_list:
with open('0943_fk_start.par', 'r') as... |
import pytest
from asn1PERser.codec.per.encoder import encode as per_encoder
from asn1PERser.codec.per.encoder import SizeConstrainViolated, InvalidComponentIndexIntoStructuredType
from asn1PERser.classes.data.builtin.SequenceOfType import SequenceOfType
from asn1PERser.classes.data.builtin.IntegerType import IntegerTy... |
#system lib
from time import time
import fileinput
import os
#hash lib
import hashlib as hasher
## encrpty lib
from Crypto.Hash import SHA256, SHA, SHA512
from Crypto.PublicKey import RSA
import Crypto.Cipher.PKCS1_v1_5
import Crypto.Random
import Crypto.Signature.PKCS1_v1_5
import rsa
## project lib
import get_key
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 22 00:12:32 2018
@author: nakul
"""
#Kmeans Clustering
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3,4]].values
#Use elbow method to find optimal number of cluster... |
#slicing a list
players = ['delgado', 'abrams', 'beto', 'gillam']
print("slice 1 = ")
print(players[0:3]) #don't forget to use [], not ()
print("slice 2 = ")
print(players[2:4])
print("slice without a beginning = ") #starts at beginning of list
print(players[:4])
print("slice without an end = ")
print(players[2:])
... |
for i in range(3):
inArr = list(map(int, input().split()))
gcd = 1
for j in range(min(inArr), 0, -1):
works = True
for n in inArr:
if n % j != 0:
works = False
if works == True:
gcd = j
break
else:
j += 1
pri... |
a = True
temp = [int(x) for x in input().split()]
dmax = pow(temp[1],2)
x = 0 #valor horizontal
y = 0 #valor vertical
for i in range(temp[0]):
m = input().split() #movimento desta linha
d = int(m[1]) #distância percorrida
if m[0] == "N":
y += d
elif m[0] == "S":
y -= d
el... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, RequestContext
from models import *
# Create your views here.
def buckets(request):
return render(request, 'buckets/index.html', {'title':'Buck... |
import datetime
import factory
from django.db.models import signals
from elections.models import (
ElectedRole,
Election,
ElectionType,
ModerationHistory,
ModerationStatus,
ModerationStatuses,
)
from organisations.tests.factories import (
DivisionGeographyFactory,
OrganisationDivisionFa... |
from .base_sequence import Sequence
from .minibatch_sequence import MiniBatchSequence, SAGEMiniBatchSequence, FastGCNBatchSequence
from .fullbatch_sequence import FullBatchSequence
from .sample_sequence import SBVATSampleSequence
from .null_sequence import NullSequence
|
def minMinMax(arr):
arr = sorted(arr)
minMiss = arr[0]
for x in range(1,len(arr)):
if minMiss+x not in arr:
minMiss = minMiss+x
break
return [arr[0], minMiss, arr[-1]]
'''
Given an unsorted array of integers, find the smallest number in the array,
the largest number i... |
# Basic functions
def createSkeleton(name, id, health=20, damage=10):
id = id + 1
return {
'name' : name,
'health' : health,
'damage': damage,
'id': id
}
def add(skeleton, army):
army.append(skeleton)
def find(id, army):
for unit in army:
if (unit['id'] == id): return unit
return 0
d... |
from discord.ext import commands
import discord
import random
import time
import datetime
from pytz import timezone
import pytz
from random import randrange
class CommandsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.remove_command('help')
@commands.command(name="next")... |
from typing import List
from entities.employee import Employee
from entities.manager import Manager
from abc import ABC, abstractmethod
from utils.connection_util import connection
from daos.employee_dao import EmployeeDAO
from exceptions.resource_not_found import ResourceNotFound
from exceptions.user_credential_failed... |
"""
Galois Field by user6655984 on StackOverflow
https://stackoverflow.com/questions/48065360/interpolate-polynomial-over-a-finite-field
"""
import itertools
from sympy.polys.domains import ZZ
from sympy.polys.galoistools import (gf_irreducible_p, gf_add, gf_sub, gf_mul, gf_rem, gf_gcdex)
from sympy.ntheory.pr... |
'''pca_svd.py
Subclass of PCA_COV that performs PCA using the singular value decomposition (SVD)
YOUR NAME HERE
CS 251 Data Analysis Visualization, Spring 2020
'''
import numpy as np
import pca_cov
class PCA_SVD(pca_cov.PCA_COV):
def pca(self, vars, normalize=False):
'''Performs PCA on the data variables... |
#!/usr/bin/python3
"""
PYTHON OBJECT RELATIONAL MAPPING MODULE
model_state_update_id_2 module provides function to change the name of a
State object from the DB.
"""
import sys
from model_state import Base, State
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def model_state_update_id_... |
from datetime import datetime
class Bomba:
_tipo = None
__valor = 0
__quantidade = 0
def __init__(self, tipo, valor, quantidade):
self._tipo = tipo
self.__valor = valor
self.__quantidade = quantidade
def desconto(self, desconto):
self.__valor -= self.__valor *... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 1 00:22:09 2019
@author: HP
"""
import cv2
num=cv2.imread(r'F:\CS Projects\Coding\Python\Input\Num_3.jpg')
a=5
b=6
dict={a:'hi',b:'hello'}
print(dict)
gray=cv2.cvtColor(num,cv2.COLOR_BGR2GRAY)
gray=cv2.GaussianBlur(gray,(7,7),0)
edge=cv2.Canny(gray,50,100)
#edge=cv2... |
# -*- coding: utf-8 -*-
"""Tests for MacOS fseventsd files."""
import unittest
import pygzipf
from dtformats import fseventsd
from tests import test_lib
class FseventsFileTest(test_lib.BaseTestCase):
"""MacOS fseventsd file tests."""
# pylint: disable=protected-access
def testReadDLSPageHeaderV1(self):
... |
from flask import render_template
from app import app
from app.forms import LoginForm, RegistrationForm
@app.route('/')
@app.route('/index')
def index():
return render_template('base.html', title='Display this shit')
@app.route('/register')
def register():
form = RegistrationForm()
return render_template('regis... |
"""
"""
__all__ = [
"ERR_CHAN",
"DATA_CHAN",
"netPeer",
"sendCmd",
"sendData",
"disconnectPeer",
]
from edh import *
# conventional Nedh channel for error reporting
ERR_CHAN = "err"
# conventional Nedh channel for data exchange
DATA_CHAN = "data"
# effectful identifier of the peer object
ne... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 07:39:40 2020
@author: adonay
"""
import os.path as op
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import utils_io as uio
import utils_signal_processing as sig_proc
import utils_feature_extraction as fea... |
import asyncio
async def count(limit=3):
for step in range(1, limit+1):
print("Веду отсчет.",step)
await asyncio.sleep(0)
coroutine = count(5)
while True:
coroutine.send(None) |
/Users/samnayrouz/anaconda3/lib/python3.6/bisect.py |
import os
os.sys.path.insert(0, os.path.abspath('../settings_folder'))
import settings
import ddpg_airsim
import dqn_airsim
import dqn_baselines
import ppo_airsim
#import sac_airsim
from game_handler_class import *
import msgs
import file_handling
from utils import *
def runTask(task):
# decide on the algorithm... |
from rest_framework import serializers
from apps.jogo.models import Jogo
class JogoSerializer(serializers.ModelSerializer):
class Meta:
model = Jogo
fields = '__all__'
def create(self):
jogo = Jogo()
jogo.iniciar_jogo()
for n in range(1, 301):
jogo.inic... |
class Product(object):
def __init__(self, price, item_name, weight, brand, cost=0.0, status='for sale'):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.cost = cost
self.status = status
def sell(self):
self.st... |
# Generated by Django 2.2.2 on 2019-09-04 09:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0006_auto_20190829_0910'),
]
operations = [
migrations.CreateModel(
name='City',
fields=[
('... |
import cv2
import numpy as np
import imutils
from calibration import Contour, ReferenceLine, SquaresIdentifier, PeaksIdentifier, CalibrationRig
USE_VIDEO = False
def process_image(image):
triangles, squares = Contour.find_triangles_and_squares(image)
ref_line = ReferenceLine(triangles)
ref_line.draw(image... |
from fastapi import APIRouter
from fastapi.exceptions import HTTPException
from app.schemas import questions
from app.api.operation.question import get_question, create_question
from app.models.questions import QuestionChoices
router = APIRouter()
@router.post("/create_question/", response_model=questions.Question)... |
from app.DAOs.MasterDAO import MasterDAO
from psycopg2 import sql, errors,errorcodes
from app.DAOs.AuditDAO import AuditDAO
from app.handlers.WebsiteHandler import WebsiteHandler
from app.DAOs.WebsiteDAO import WebsiteDAO
from app.DAOs.PhoneDAO import PhoneDAO
from flask import jsonify
class ServiceDAO(MasterDAO):
... |
class LivingThing():
def breathe(self):
return "I'm breathing as a living thing."
class Mammal(LivingThing):
def breathe(self):
return "I'm breathing as a mammal."
class Animal(LivingThing):
def sound(self):
return "I am speaking out as an animal"
class Bird(LivingThing):
p... |
number_to_guess = 5
times = 5
while times !=0:
user_number=int(input("Adivina el numero del 0 al 10: "))
if number_to_guess == user_number:
print("Has gando campeón\n")
times=0
else:
times -=1
if times ==0:
print("Has perdido imbecil\n")
|
import datastore
import encryptordatastore
def initialize():
datastore.initialize()
encryptordatastore.initialize() |
from . import (parsers,
common,
io,
multiprocessing_tools,
analysis,
diagnostics,
stochastic_processes,
stats_utils,
plotting) |
import math
import pylo
class StaticMagneticFieldForTilt(pylo.Device):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.init_event_id = "static_magnetic_field_init"
self.modify_step_event_id = "static_magnetic_field_modify_step"
self.clearEvents()... |
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, ListModelMixin
from rest_framework.permissions import IsAuthenticated
from ..models import Order
from ..permissions import IsRegularUser
from .serializers import OrderSerializer
class OrderViewSet(CreateModelMixin, ... |
# -*- coding: UTF-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_con... |
import random
from collections import Counter
import matplotlib.pyplot as plt
import math
# multiplica um vetor por um escalar
def scalar_multiply(escalar, vetor):
return [escalar * i for i in vetor]
def vector_sum(vetores):
resultado = vetores[0]
for vetor in vetores[1:]:
resultado = [resultado[... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, reverse, HttpResponse, redirect
from models import *
from django.contrib import messages
import bcrypt
import re
from django.core.urlresolvers import reverse
from django.core import serializers
import json
from django... |
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
start = dt.datetime(2000,1,1)
end = dt.datetime(2016,12,31)
# Here in DataReader, parameters are stock_tick, website/source, start, end.
df = web.DataReade... |
import sys,pygame
from pygame.locals import *
class State():
def __init__(self,screen,rm):
self.screen = screen
self.rm = rm
self.last_keystate = {}
def _draw(self):
pass
def _step(self):
pass
def _input(self,im):
# key input handling
if im.... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
python tasks/mongo_multimedia.py --local-scheduler --date 20150115
"""
import luigi
from ke2mongo.tasks.mongo import MongoTask
class MongoMultimediaTask(MongoTask):
"""
Import Mult... |
"""
The url shortener backend.
"""
from fastapi import FastAPI
from backend.routes import router
def build_app(app: FastAPI) -> FastAPI:
app.include_router(router)
return app
app = build_app(FastAPI()) |
def wordBreak(s, dict):
if s == "":
return True
newdict = set([])
for word in dict:
i=0
while i < len(word):
if i > (len(s)-1) or s[i] != word[i]:
break
else:
i+= 1
... |
from django.shortcuts import render, Http404, HttpResponse, HttpResponseRedirect
#import matplotlib.pyplot as plt
import pygal
import pygal.style
import io
from .utils import *
from .forms import NewDeviceForm, RemoveDeviceForm, EditDeviceForm
from .models import Device, LastUpdated, MACtoPort, IgnoredPort
from django.... |
"""Module for the root endpoint of the debug routes.
Contains the blueprint to avoid circular dependencies."""
from flask import Blueprint, render_template
DEBUG_BLP = Blueprint(
"debug-routes", __name__, template_folder="templates", url_prefix="/debug"
)
@DEBUG_BLP.route("/")
@DEBUG_BLP.route("/index")
def in... |
import os
import sys
import numpy as np
from setuptools import setup, Extension, find_packages
# HIDE WARNING:
# cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
from distutils.sysconfig import get_config_vars
cfg_vars = get_config_vars()
for k, v in cfg_vars.items():
... |
# Calculadora em Python
operacao = ''
while operacao != "sair":
print()
operacao = input(" Qual operacao desejada - soma, sub, mult, div ou sair: ")
if operacao == "sair":
break
numero_1 = float(input(" Digite primeiro número: "))
numero_2 = float(input(" Digite segundo número: "... |
namne=" moona"
print("hi", msg)
|
def create_list():
a = [1, 2, 3, 5, 6, 7, 7, 8, 8, 5, 9, 1]
return a
def set_list(a):
a = set(a)
return a
print (create_list())
print (set_list(create_list())) |
from django.contrib.auth.forms import forms, UserCreationForm, UserChangeForm
from phonenumber_field.formfields import PhoneNumberField
from phonenumber_field.widgets import PhoneNumberPrefixWidget
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
phone = PhoneNumberField(widget=PhoneN... |
from datetime import datetime
import string
import pandas
def get_house_bill_df(file):
df = pandas.read_excel(file, header=None)
index_to_leave = [1, 2, 4, 6, 7, 12, 18, 29, 30, 32, 40, 42, 43, 54]
for index, row in df.iteritems():
if index not in index_to_leave:
del df[index]
d... |
# -*- coding: utf-8 -*-
# -*- author: hechao -*-
import os
from core.config import config
from core.db_info import get_db_table_info_data
from jinja2 import PackageLoader, Environment
def render_html(db_name, db_real_name, tables):
env = Environment(loader=PackageLoader("html", "templates"))
template = env.g... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'Matches', fields ['source', 'value']
db.cr... |
import random
from game import constants
from game.actor import Actor
from game.point import Point
class Food(Actor):
'''This keeps track of the food item and how much each piece is worth.
attributes:
'''
def __init__(self):
'''constructor
'''
super().__init__()
... |
import requests
BASE = 'http://127.0.0.1:5000/'
responses = requests.get(BASE + 'product')
for response in responses:
print(response.json) |
# Author: Jack (z5129432) for COMP9021 Assignment 1
# Date: 23/08/2017
# Description:
import sys
# funtion: calculate_next_step
# version: v01
# dependency: transformation()
# input: this_step[]
# output: next_step[]
# description: just add new elements to next_step[], I mean this_step is included into next_ste... |
from musket_text import text_datasets
from musket_core import datasets
@datasets.dataset_provider(origin="train.csv",kind="TextClassificationDataSet")
def get_sample():
return text_datasets.BinaryTextClassificationDataSet("train.csv","question_text","target")
@datasets.dataset_provider(origin="test.csv",ki... |
import requests
from requests.exceptions import HTTPError
url = "https://covid19-us-api.herokuapp.com/twitter"
payload = {}
headers= {}
response = requests.get(url)
#print(response.text.encode('utf8'))
response.raise_for_status()
Jsonresponse = response.json()
a = Jsonresponse["message"]
i = 0
b ... |
import os
from flask import json, jsonify
from app import app
AUTH_TOKEN = ""
def test_signup():
print('testing /auth/signup')
# Create new user from sign in form
#'''
with app.test_client() as c:
rv = c.post('/auth/signup', json={
'email': "ralf_stone@host.com", #'bill_xavier@host... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, TwistStamped
from styx_msgs.msg import Lane, Waypoint, TrafficLight, TrafficLightArray
import math
import copy
'''
This node will publish waypoints from the car's current position to some `x` distance ahead.
... |
"""
Import and parse football data.
Author: Alton Wiggers, Kadan Lottick
Date: 12/17/19
"""
import csv
source_file = "spreadspoke_scores.csv"
#dest_file
def main():
read_csv(source_file,1979)
def get_bookie_score(source_file):
"""
check predicted winners against actual results
for all games in 2015-2... |
#include ./splitterDict
def merge(patch, name):
# Flag lines for removal
to_remove = []
for n in range(len(patch)):
if 'solid' in patch[n]:
to_remove.append(n)
# Remove lines using list of flags
i = 0
for n in to_remove:
del patch[n-i]
i += 1
# Add begi... |
# @see https://adventofcode.com/2015/day/14
# Note:
# -----------------------------------------------------------
# I apologise in advance to you (or to my future self) if this
# isn't readable enough :/
import re
def parse_line(s: str):
r = re.match(r'([A-Z][a-z]+) can fly ([\d]+) km/s for ([\d]+) seconds, but... |
#coding:utf-8
#!/usr/bin/env python
import gclib.curl
import gclib.cacheobj
class MMPersistent:
@staticmethod
def install(obj, roleid):
"""
安装
"""
i = 0
for column in obj.extend_columns:
setattr(obj, column['name'], column['value'])
i = i + 1
@staticmethod
def get(tp, roleid):
"""
... |
"""
Week 5, Day 1: Course Schedule
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first
take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequis... |
import pytest
# See: https://docs.pytest.org/en/latest/how-to/writing_plugins.html#assertion-rewriting
pytest.register_assert_rewrite("pants.testutil.pytest_util", "pants.testutil.process_util")
|
#
# @lc app=leetcode.cn id=77 lang=python3
#
# [77] 组合
#
# @lc code=start
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res, track = [], []
def backtrack(n, depth):
# track 表示当前路径
if len(track) == k:
# print(track)
res... |
# -*- coding: utf-8 -*-
'''
Created on 05-08-2013
@author: klangner
'''
from bluenotepad.storage.log import read_folder_sessions, read_sessions
from collections import defaultdict
import os
DATA_ROOT = os.path.join(os.path.dirname(__file__), '../../data/')
def event_before(sesions, event_name):
events = defaul... |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Defines the interface of the Display module of the racecar_core library.
"""
import abc
import numpy as np
import math
from typing import List, Tuple, Any
from nptyping import NDArray
import racecar_utils as rc_utils
class Display(abc.ABC):
"""
... |
#!/usr/bin/env python
# A simple script to suck up HTML, convert any images to inline Base64
# encoded format and write out the converted file.
#
# Usage: python standalone_html.py <input_file.html> <output_file.html>
#
# TODO: Consider MHTML format: https://en.wikipedia.org/wiki/MHTML
import os
# from bs4 import Beau... |
from Batch import batch2TrainData
from LoadFile import loadPrepareData, trimRareWords
from Algorithm import EncoderRNN, LuongAttnDecoderRNN
from torch import optim
from Train import trainIters
import torch.nn as nn
import random
import os
import torch
import argparse
parser = argparse.ArgumentParser(description='Train... |
import argparse
import gym
import algs.q_learning
import test_envs
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Run Q-Learning algorithm in Gridworld environment."
)
parser.add_argument("--height", type=int, help="height of the grid", default=10)
parser.add_argu... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserPersonalInfo(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
#Additional Story:
Profile_Link=models.URLField(blank=True)
Image_Profile=models.ImageField(upload_to='profile_... |
import logging
from pyfiles.db import player
from pyfiles.model import session
# Current connected but unauthenticated sessions
_connected_sessions = []
# Dict mapping of session IDs to usernames once authenticated/logged_in
_active_sessions = {}
def add_connected_session(session_id: str) -> None:
logging.info(... |
from django.contrib import admin
from Materia.models import Materia
from Materia.Turma.models import Turma
class MateriaAdmin(admin.ModelAdmin):
fieldsets = [
('Materia', {'fields': ['nome','sigla']}),
]
list_display = ('nome','sigla',)
class TurmaAdmin(admin.ModelAdmi... |
from django.core.management.base import BaseCommand, CommandError
from bay.models import Torrent, File
from unidecode import unidecode
import traceback
import csv
from pprint import pformat
import codecs
import os
import progressbar
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yiel... |
# Graph Theory Project - Quentin Lautischer and Joshua White
"""
Assignment 3 - Directions
DRIVING ROUTE FINDER
Part 1: Server
Part 2: Client
""" |
import time
import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptio... |
from django.db import models
from django.utils import timezone
from projects.models.project import Project
class TechnicalSheet(models.Model):
class Meta:
verbose_name = 'technicalsheet'
verbose_name_plural = 'technicalsheets'
created = models.DateTimeField(editable=False, auto_now_... |
import serial
import time
# define version one object which does basic communication with arduino
class serialCommObj:
def __init__(self, port, baud):
self.Connection = serial.Serial(port,baud)
time.sleep(2)
def setFreqAndDuty(self,freq, duty):
# maximum frequency is 500 Hz
# duty is a fraction e [0:1]
... |
from datetime import datetime
from django.views.generic import ListView
from .models import Battle
# Create your views here.
class UpcomingBattlesView(ListView):
queryset = Battle.objects.filter(start_time__gte=datetime.now(), is_active=True)
template_name = 'battles.html'
context_object_name = 'battle... |
#!/usr/bin/env python3
import os
import signal
import sys
from time import strftime, sleep
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
def signal_handler(signal, frame):
if WEBDRIVER is not None:
WEBDRIVER.quit()
sys.exit(0)
def set_webdriver(driver):
o... |
#!/usr/bin/env python
# encoding: utf-8
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.options import options
import logging
from settings import settings
from gelyung.urls import url_patterns
from gelyung.sched import MonitTask
class MainApplication(tornado.web.Application):
d... |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print("Copying from {0} to {1}".format(from_file, to_file))
# we could do these two in one line, how?
# in_file = open(from_file)
# indata = in_file.read()
indata = open(from_file).read()
print("input file is {0} bytes long".format(len... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 2 12:33:02 2018
@author: Estagio
"""
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
cancer = load_breast_cancer()
x = cancer['data']
y = cancer['target']
X_train, X_test, y_train, y_test = train_test_split(x, y) |
import pandas as pd
loop = True
chunkSize = 10000
chunks = []
index=0
reader=pd.read_csv('H:\\SMPData\\Weibo.Corpus\\Weibo.data\\merge\\weibodata.csv',iterator = True)
while loop:
try:
chunk = reader.get_chunk(chunkSize)
chunks.append(chunk)
index=index+1
print "Iteration %d"%(index)
if index>2499... |
import pygame
from math import sqrt
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Tic-tac-toe')
current_player = 'X'
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
game_going_on = True
winner = None
font = pygame.font.Font('freesansbold.... |
# Echo client program
import socket
import time
HOST = "10.0.0.2" # The remote host
PORT = 30002 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(("speedj([0, 0, 0, 0, 0, 10], a=5.0, t=10)" + "\n").encode())
s.close()
|
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
abHeaders = ['sex', 'length', 'diameter', 'height', 'wholeWeight', 'shuckedWeight', 'visceraWeight', 'shellWeight', 'rings']
dfAb = pd.read_csv('abalone.data', sep=",... |
import tensorflow as tf
import numpy as np
from dps import cfg
from dps.env import TensorFlowEnv
from dps.register import RegisterBank
from dps.utils import Param, Config
from dps.rl.policy import ProductDist, Normal, Gamma, Policy
def build_env():
if cfg.room_angular:
return RoomAngular()
else:
... |
def start_master_application(essid, ap, password):
'''Start the master application on the network that you specify.
ARGS:
@essid -- the name of the network to put it on.
@ap -- the mac address of the ap.
RETURNS:
None
'''
from batman_sockets.TCPServerSocket import TCPServerSocket
... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Documents"),
"icon": "icon-star",
"items": [
{
"type": "doctype",
"name": "Checklist Requisition",
"description": _("Run Checklist")
},
{
"type": "doctype",
"name": "C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.