text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Model zoo."""
import os
import pycls.core.builders as builders
import pycls.core.checkpoint as cp
from pycls.core... |
#!/usr/bin/env python3
"""
Models related to voting history of North Carolina voters.
"""
from django.db import models
from django.contrib.postgres.functions import RandomUUID
from .voter import Voter
class Election(models.Model):
"""
An election in which a voter may have voted.
"""
id = models.UUIDFi... |
print("Сніцаренко Анна Сергіївна \nКМ-91 \nЛабораторна робота №1 \nЗнайти max {min (a, b), min (c, d)} \n")
a = float(input("Введіть значення a"))
b = float(input("Введіть значення b"))
c = float(input("Введіть значення c"))
d = float(input("Введіть значення d"))
print(max(min(a, b), min(c, d))) |
from nose.tools import assert_equals, with_setup
def setup():
"""setting up the test"""
# TODO here we add the useful global vars
global global_var
global_var = "is this a global?"
def teardown():
"""teardowning the test"""
# TODO add something to do when exiting
pass
@with_setup(setup, t... |
from datetime import datetime
from regobj import HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CURRENT_USER
from commit import Commit
KEYS = (HKEY_LOCAL_MACHINE, HKEY_USERS)
KEYS = (HKEY_CURRENT_USER, )
class Snapshot():
def __init__(self, initial=False):
self.name = str(datetime.now())
self.values = {}
... |
from PyQt5 import QtWidgets, QtGui, QtCore
from core.Utils.BasePanel import BasePanel
from view.UiMainPanel import UiMainPanel
import openpyxl
from core.Utils.ExcelPanel import *
import os
from src.datalink.DataLinkPanel import DataLinkPanel
from core.Manage.SignalManage import *
import json
import time
class MainPan... |
#PRINTING NUMBER IN SPIRAL PATTERN IN SQUARE
N=int(input("Enter the user Input: ")) #Taking user input
chakra=[[0 for i in range(N)] for i in range(N)]
co=1
print("Square - Sprial Pattern")
for i in range(N//2):
row,col=i,i
end_col=N-i-1
while(col<end_col): #printing first row
chakra[row][col]=co
... |
import string
import os
import re
import sys
class Ethernet :
def __init__(self, dest, src, type_protocole) :
self.dest = dest
self.src = src
self.type_protocole = type_protocole
def affichage_dest(self) :
dest = ':'.join(self.dest)
print ( "\tDestination (... |
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016
import unittest
import sys
import itertools
import test_vers
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import schema
import streamsx.topology.context
import streamsx.spl.op as op
@unit... |
from modules.commands.utils import *
from modules.commands.kick import initiate_kicks
from vkwave.bots.storage.storages.ttl import TTLStorage
async def exec_catch_runner(box, user_id):
if user_id not in stor.vault['enters'].keys():
stor.vault['enters'][user_id] = {
'chats':[box.msg.peer_id],
... |
import obspy
from obspy import Stream
from obspy.clients.syngine import Client as synClient
from obspy.clients.fdsn import Client as fdsnClient
from obspy.core.util.attribdict import AttribDict
from obspy.geodetics.base import degrees2kilometers, gps2dist_azimuth
from bowpy.util.array_util import dist_azimuth2gps, geom... |
# This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our i... |
"""Main integratopm abstract class.
This is the main module of spradius. It contains the abstract definition
of any time integrations strategy to be implemented within this software
and the main routine for computing the spectral radius, based on the
numerical strategy presented in
1. Benítez JM, Montáns FJ. The valu... |
# -*- coding: utf-8 -*-
"""
Archivo de importación de datos para Medias móviles.
"""
#%% Importar librerías.
from mylib import mylib
import time as _time
import datetime
yahooKeyStats = mylib.yahooKeyStats
#%% Descargar datos históricos.
stock = ['AC.MX','ALFAA.MX','ALPEKA.MX','ALSEA.MX','ELEKTRA.MX','IE... |
from django import forms
from .models import ArcGISLayerImport
class ArcGISLayerImportForm(forms.ModelForm):
class Meta:
model = ArcGISLayerImport
fields = ['url']
widgets = {
'url': forms.TextInput(attrs={
'id': 'layer-url',
'required': True,
... |
import gevent
def testfn(name, count):
for i in range(count):
print("In {}, count = {}".format(name, count))
while True: pass
gevent.sleep(1)
g1 = gevent.spawn(testfn, "foo", 10)
g2 = gevent.spawn(testfn, "bar", 15)
g3 = gevent.spawn(testfn, "baz", 20)
gevent.joinall([g1, g2, g3])
|
#!/usr/bin/env python3
# encoding: utf-8
# time : 2019/10/10 3:46 下午
from _sha256 import sha256
from ssl import SSLContext
from typing import Optional, Dict, Any, Mapping, Union
import ujson
from aiohttp import BasicAuth, ClientTimeout, Fingerprint
from aiohttp.helpers import sentinel
from aiohttp.typedefs import S... |
# 연습문제 4-4
original_text = 'I think, therefore I am.'
replaced_text = original_text.replace('think', 'eat')
print(replaced_text)
|
from functools import partial
from typing import Iterable
from sqlalchemy import Column, Integer, String, Float, create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
import pandas as pd
from common.constatns import _DB_FILE_LOCATION
Ba... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Author:Qingshui Wang
# @Email:apecoder@foxmail.com
# @Time:2018/5/1 21:10
# @File:Main.py
"""
|
from selenium import webdriver
import time
import selenium.webdriver.chrome.service as service
# browser = webdriver.Chrome()
# browser.get('http://www.baidu.com')
driver = webdriver.Chrome() # Optional argument, if not specified will search path.
driver.get('https://www.baidu.com') # set up the destin... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('price/', views.price),
] |
# This is the Egg class file
import Global_Variables as gv
import pygame as pg
class Egg:
# Egg constructor
def __init__(self, egg_size, egg_pos):
self.size = egg_size
self.pos = egg_pos
# updates the location of the egg
def update(self, display):
pg.draw.circle(display, gv.R... |
import numpy as np
import scipy.interpolate as si
def bspline(cv, n=100, degree=3, periodic=False):
""" Calculate n samples on a bspline
cv : Array ov control vertices
n : Number of samples to return
degree: Curve degree
periodic: True - Curve is closed
... |
def solution(numbers):
answer = 0
result = sum(numbers)
return result/len(numbers); |
from django.conf.urls.defaults import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
# Examples:
url(r'^$', 'django_hell... |
import pandas as pd
import codecs
from textrank4zh import TextRank4Keyword, TextRank4Sentence
import jieba.analyse
def textRank4zh():
# 加载数据
df = pd.read_csv("C:/Users/11245/Desktop/好好看好好学/毕业设计/中文数据集/ChnSentiCorp_htl_all.csv", encoding='utf-8')
x_data = df['review'].astype(str).to_list()
# 创建分词类的实例
... |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import mmcv
import numpy as np
from ..utils import get_root_logger
from .base import BaseDataset
from .builder import DATASETS
@DATASETS.register_module()
class PoseDataset(BaseDataset):
"""Pose dataset for action recognition.
The datase... |
Q = int(input())
is_prime = [True]*(2000000 + 1)
# エラトステネスの篩
is_prime[0] = False
is_prime[1] = False
now = 2
while now * now <= 2000000:
if is_prime[now]:
for i in range(now * 2, 2000000 + 1, now):
is_prime[i] = False
now += 1
ok = [0]
for i in range(1, 2000001):
if i % 2 == 1 and is_... |
# Generated by Django 3.2.3 on 2021-07-07 21:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='empleo',
name='idEmpleo',
fi... |
"""
GreenThumb REST API.
GreenThumb Group <greenthumb441@umich.edu>
"""
from greenthumb.api.catalog import (get_catalog, get_catalog_plant_page)
from greenthumb.api.guides import(get_guides, get_guide_page)
# import greenthumb.api.usergarden
from greenthumb.api.usergarden import (get_user_gardens, get_garden, add_g... |
### PreScript ###
lastindex = 0
cn_last = 0
soundfile1 = r'C:\TFS\Doc\3-ZIS\3-Development\Discussions\ExperimentFeedback\Release_DVD\SoundFiles\PsychoScream.wav'
soundfile2 = r'C:\TFS\Doc\3-ZIS\3-Development\Discussions\ExperimentFeedback\Release_DVD\SoundFiles\YEAH.WAV'
### LoopScript ###
# get parameters
fra... |
#!/usr/bin/python3
import ev3dev.ev3 as ev3
import time
irSensor = ev3.InfraredSensor()
print("ready")
def runLoop():
while True:
print(irSensor.proximity)
time.sleep(1)
runLoop()
|
import os
import torch
from torch.utils.data import Dataset
from skimage.io import imread
import numpy as np
import torchvision.transforms as tvt
cityscapes_classes = np.array([
[ 0, 0, 0],#static
[111, 74, 0],#dynamic
[ 81, 0, 81],#ground
[128, 64,128],#road
[244, 35,232],#sidewalk
[250,1... |
# %load BJ_humidity_lightgbm.py
# %load BJ_humidity_lightgbm.py
#!/usr/bin/env python3
"""
Created on Thu Apr 12 11:03:29 2018
@author: dedekinds
"""
import os
import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt
import lightgbm as lgb
from sklearn.externals import joblib
%matplotlib in... |
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = "greenlet", # note that we fake the name here! this is artififical after all...
version = "0.1", # but what version should it be?
packages = find_packages()
)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-05 20:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('redcrossmain', '0002_auto_20160705_2345'),
]
operations = [
migrations.Creat... |
#
# File: results_ECC.py
# Author: Alexander Craig
# Project: An Analysis of the Security of RSA & Elliptic Curve Cryptography
# Supervisor: Maximilien Gadouleau
# Version: 2.0
# Date: 19/03/19
#
# Functionality: gathers results for RSA in given range
#
# CLI: python3 results_ECC.py -h (to see p... |
from prepareImages import prepareImages
from facial_landmarks import findFace
import os, os.path
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import argparse
import imutils
import dlib
def main():
dir_path_list = []
new_dir_path_list = []
PROCCES_IMAGES = False
D... |
# -*- coding: utf-8 -*-
import os
import argparse
import sqlite3
import xml.etree.cElementTree as ET
import math
parser = argparse.ArgumentParser(description='Testing argparser')
parser.add_argument('-EPSG', type=int, help='UTM EPSG for data', required=True)
parser.add_argument('-i', help='input file destination', req... |
############
# QUESTION 4
############
def interpolate(xy, x_hat):
# Assume x_hat values are within x values range
if len(xy) <= 1:
raise ValueError('please enter at least two valid measurements')
times_list = sorted([measure_tup[0] for measure_tup in xy])
if all([req_x in times_list for req_x ... |
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import fix_path
from src import config, sane
class Handler(webapp.RequestHandler):
def set_header(self, name, value):
self.response.headers[name] = value
def write(self, text):
s... |
#!/usr/bin/env python
import time
import subprocess
budget = 16
reach = 20000
workers = [None] * budget
unit = 0
def hire(slot):
global unit
print unit
workers[slot] = subprocess.Popen(['python', 'getmeta.py', str(unit)])
unit += 1
for i in range(budget):
hire(i)
while True:
if unit > reach:
break
for i i... |
#! /usr/bin/python
from __future__ import division
import json
from collections import defaultdict
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import time
import os
plt.style.use('ggplot')
os.chdir('/Users/deniz/Research/Organized-Hashtags')
startTime = t... |
"""TODO"""
from .Expression import Expression, ExpressionError
from .Equation import Equation
from .Inequation import Inequation
from .ExpressionSystem import ExpressionSystem
from .EquationSystem import EquationSystem
|
import numpy as np
from .propagator import Propagator
from ..optics import Wavefront, make_agnostic_optical_element
from ..field import Field
@make_agnostic_optical_element()
class FraunhoferPropagator(Propagator):
'''A monochromatic perfect lens propagator.
This implements the propagation of a wavefront through a... |
import json
from jsonschema import validate
class ConfLoader:
def __init__(self, c):
self._conf = c
self._mainConfJson = None
self._logConfJson = None
mainconfschemaPath = './res/mainconfschema.json'
logconfschemaPath = './res/logconfschema.json'
mainconfschema = None
logconfschema = None
try:
... |
// https://leetcode.com/problems/longest-turbulent-subarray
class Solution(object):
def maxTurbulenceSize(self, A):
"""
:type A: List[int]
:rtype: int
"""
one = 1
mo = 1
for i in range(len(A)-1):
if i%2:
if A[i] > A[i+1]:
... |
import math
from magicbot.state_machine import AutonomousStateMachine, state
from networktables import NetworkTable
from automations.filters import RangeFilter, VisionFilter
from automations.manipulategear import ManipulateGear
from automations.profilefollower import ProfileFollower
from components.chassis import Cha... |
from collections import defaultdict
class UF:
def __init__(self):
self.parent = {}
def find(self, x):
self.parent.setdefault(x, x)
while x != self.parent[x]:
x = self.parent[x]
return x
def union(self, p, q):
self.parent[self.find(p)] = self.find(q)
... |
import csv
import numpy as np
from collections import OrderedDict
from PIL import Image
import copy
import flask
from flask import Flask, render_template, request, redirect, url_for
from tools.vis_web import _get_train_stats
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return render_temp... |
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
# arguments-run
parser.add_argument("--sim", action='store_true', help="run simulation")
parser.add_argument("--plot3Dpos", action='store_true', help="plot static 3d position plot")
parser.add_argument("--anim", acti... |
'''
Created on 09.10.2012
@author: cbalea
'''
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
import time
class BasePage(object):
def __init__(self, driver, wait):
self.driver = driver
self.wait = wait
... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pages.base_page import Page
from time import sleep
class ProductPage(Page):
SELECT_SIZE_LOCATOR = (By.XPATH, "//*[@id='picker-1']/button")
... |
import unittest
from pingout import pingout
class TestPingout(unittest.TestCase):
def test_first_check(self):
i = 1
print('Testing:', i)
assert pingout(i) == "PING"
def test_check_signal_strength(self):
for i in [3, 6, 9, 18]:
print('Testing:', i)
asse... |
from django.contrib import admin
from expenses.models import *
# Register your models here.
admin.site.register(Client)
admin.site.register(EmployeeSalaryAdjustment)
admin.site.register(File)
admin.site.register(SubContractorProject)
admin.site.register(SubContractorProjectDay)
class FileInline(admin.StackedInline):... |
from bs4 import BeautifulSoup
html_doc="""
<html><head><title>The dormouse's story</title></head>
<body>
888
<div class='c1'>
<p class='c2'>
</p>
<div id='i1'>
<a>link</a>
</div>
</div>
</body>
</html>
"""
from bs4.element import Tag
soup=Beautifu... |
#!/usr/bin/env python3
'''
Created on Jul 23, 2017
@author: Daniel Sela, Arnon Sela
'''
from rotseana.findburst.matchcoords import matchcoords
from rotseana.findburst.findburst_gd import findburst_gd
from rotseana.findburst.read_data_file import get_data_file_rotse
import itertools
import matplotlib
matplotlib.use('... |
import redis
import time
r = redis.Redis(host='localhost', port=6379, db=0, charset="utf8", decode_responses=True)
r.set("15991030771", "1234")
# 设置过期时间
r.expire('mobile', 60*10000)
time.sleep(1)
print(r.get("15991030771"))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib, urllib2, json
from django.core.validators import URLValidator, ValidationError
class GooglUrlShort(object):
api_url = "https://www.googleapis.com/urlshortener/v1/url"
def __init__(self, url):
self.url = url
if isinstance(url, unicod... |
from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfilename
from convert import start_convert
def selectPath():
path_ = askdirectory()
path.set(path_)
def selectFile():
file_ = askopenfilename()
file.set(file_)
def convert():
if not file.get... |
import json
from server.BaseHandler import BaseHandler
from server import jsonEncode
from server.UserModele import User
class AuthHandler(BaseHandler):
def get(self):
self.response.write('')
def post(self):
mode = self.request.GET.get("mode", self.request.url.split("/")[-1].split('?')[0])
... |
import threading
import time
import queue
import os
import sys
import serial
def clear():
if os.name == 'nt':
os.system('cls||echo -e \\\\033c')
else:
os.system('clear||echo -e \\\\033c') # change if this doesn't work on Unix systems
def flush_input():
try:
import msvcrt
wh... |
#ImportModules
import ShareYourSystem as SYS
#Need to define before either it is not setted
object.MyInt=0
#Define an Object
MyObject=object(**{'MyInt':4})
#print
print('MyObject is '+str(MyObject))
#print
print('MyObject.__dict__ is '+str(MyObject.__dict__))
|
import asyncio
import requests, json
from src.objs import *
from src.commands.addTorrent import addTorrent
from src.functions.floodControl import floodControl
from src.functions.referralCode import referralCode
from src.functions.keyboard import mainReplyKeyboard, githubAuthKeyboard
# Start handler
@bot.message_handle... |
"""""
Object Oriented Programming
Class:
A class is a template that defines the object
You can create a class for anything
"""""
class Car(object):
def __init__(self, make, model):
self.make = make #self is just the first parameter received to create the object
self.model = model
c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
def original_sequences(k):
for x in itertools.product('GL', repeat=k):
yield ''.join(x)
def produce_artwork(os, c):
a = os
g = 'G' * len(os)
for i in xrange(c-1):
a = ''.join([os if t == 'L' else g for t in a])
... |
from csv import DictReader
from .TileNode import TileNode
from .NodeSet import NodeSet
# Read in locations.txt and parse data as ImageData class, compile into ImageSet
def parse_locations(locationsFile):
nodes = []
with open(locationsFile) as csvFile:
reader = DictReader(csvFile, delimiter=' ')
... |
# base decimal
a = int('23', 10)
print(f'Resultado: {a}')
# base binario
a = int('10111', 2)
print(f'Resultado: {a}')
# base octal
a = int('27', 8)
print(f'Resultado: {a}')
# hexadecimal
a = int('17', 16)
print(f'Resultado: {a}')
|
# 1. Pedir dos números por teclado e imprimir la suma de ambos.
print("Ejercicio 1")
def sumar (numero_1, numero_2):
resultado = numero_1 + numero_2
return resultado
numero_1 = float(input("Introduce el primer número: "))
numero_2 = float(input("Introduce el segundo número: "))
resultado = sumar (numero_1, ... |
__author__ = 'Hk4Fun'
__date__ = '2018/1/7 19:02'
'''题目描述:
判断两个无环链表listA和listB是否相交,如果相交,返回相交的节点在listB中的索引(从0开始),否则返回False
'''
'''主要思路:
可以让其中一个链表(不妨设是listA)的尾节点连接到其头部,这样在listB中就一定会出现一个环,
这样就将问题分别转化成了15_3和15_4(交点即为环的入口点)
(参考题37,给出其他算法思路,不要被前面几道题的思路给局限了)
'''
class ListNode:
def __init__(self, x):
self.val =... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 22:56:10 2018
@author: Inigo
"""
# =============================================================================
# LIBRARIES
# =============================================================================
import pandas as pd
import numpy as np
import matplotlib.pyplot ... |
import os
import urllib.request
class GetPoliticalParty:
def __init__(self, estados, partidos):
os.system("rm -r DadosEleitorais")
os.system("mkdir DadosEleitorais")
self.estados = estados
self.partidos = partidos
self.get_data()
@classmethod
def _ma... |
"""mineral_catalog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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... |
"""
Stochastic Gacs-Korner common information. See "Gacs-Korner Common Information
Variational Autoencoder" for details.
"""
import numpy as np
from ...algorithms import BaseAuxVarOptimizer
from ...helpers import normalize_rvs
from ...utils import unitful
__all__ = (
'StochasticGKCommonInformation',
)
class S... |
#在这里添加这行代码,站点才能显示中文的app名字
#如果我们在注册app的时候就用了users.apps.UsersConfig的方式注册了,这行代码就可以省略
default_app_config='users.apps.UsersConfig' |
class Solution:
ret = []
def DFS(self, candidate, target, start, valuelist):
length = len(candidates)
if target == 0:
return Solution.ret.append(valuelist)
for i in range(start, length):
if target < candidates[i]:
return
if i > 0 and candidates[i] == candidates[i - 1]: # remove duplicate
cont... |
import os
from math import log, floor
from pathlib import Path
import argparse
import tensorflow as tf
from data_pipeline import load_image, preprocess_image_tfRecord, preprocess_label, preprocess_dataset, get_data_generator_single
from optional import count_files_by_extension, create_dirs, str2bool
from configuratio... |
import pyDes
from PIL import Image
with open("twitter.bmp", "rb") as imageFile:
f = imageFile.read(138)
b = bytearray(f)
a = imageFile.read(1441910)#a = imageFile.read(363049472)para la del pinguino
imageFile.close()
data=a
k = pyDes.des(b"Asegurar", pyDes.ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=py... |
"""
演示文件的读操作
"""
# file1 = open('hello.txt','r')
# data = file1.read()
# print(data)
# file1.close()
# 如果说一个文件里面的内容太多了 read() 会讲里面的内容一次性读取出来, 负荷太大,,,
# 第一种方式 read(参数) # 每次读取参数大小的内容
# file1 = open('hello.txt','r')
# while True: # 循环取值, 把里面的内容都读取出来,, 每次都多少由参数决定
# data = file1.read(5) # 字符来作为单位 一次读取出来的大小 5 hel... |
from apps.forms import BaseForm
from wtforms import StringField, IntegerField
from wtforms.validators import Email,InputRequired,Length,EqualTo
from utils import rmcache
from wtforms import ValidationError
from flask import g
class LoginForm(BaseForm):
email = StringField(validators=[Email(message='邮箱格式不正确'),Inpu... |
import re
class LocationIndex:
def __init__(self, location_str):
self.location_str = location_str
def __str__(self):
return "{}".format(self.location_str)
"""main location function, gives response to building number, pool and map"""
def location_passer(self, message_text):
if... |
# Import Panda3D Modules
import sys, os, math
from pandac.PandaModules import loadPrcFileData, TextNode, NodePath, CardMaker,TextureStage, Texture, VBase3, TransparencyAttrib, WindowProperties, TextProperties, TextPropertiesManager
from direct.actor.Actor import Actor
from direct.interval.LerpInterval import LerpHprInt... |
from tkinter import *
from tkinter import messagebox
window=Tk()
window.title("SIMPLE CALCULATOR")
window.geometry('312x370')
window.resizable(0,0)
def btn_click(item):
global expression
expression=expression+str(item)
input_text.set(expression)
def btn_clear():
global expression
expression=""
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2007-2013 NovaReto GmbH
# cklinger@novareto.de
from .interfaces import IPageTop, IFooter, INavigation, IAboveContent, IBelowContent
from five import grok
from grokcore.layout import Layout
from plone import api as ploneapi
from uvc.api import api
from Products.CMFCore.interface... |
import rospy, os, sys, time
from sensor_msgs.msg import Image
import cv2, copy
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from detecto import core, utils, visualize
from PIL import Image as Img
import matplotlib.pyplot as plt
class Digit_Perception:
def __init__(self):
rospy.Subscriber('/forwa... |
"""
test_generator.py
tests the solution to the generator lab
can be run with py.test or nosetests
"""
import generator as gen
def test_intsum():
g = gen.intsum()
assert next(g) == 0
assert next(g) == 1
assert next(g) == 3
assert next(g) == 6
assert next(g) == 10
assert next(g) == 15
... |
#import math
n=int(input("enter num"))
result=n**0.5
#result=math.sqrt(n)
print("square root of", n ,"is : ",result) |
# -*- coding: utf-8 -*-
import glob
import numpy as np
import matplotlib.image as mpimg
def EST_NOISE(images):
"""Implementation of EST_NOISE in Chapter 2 of Trucco and Verri."""
num = images.shape[0]
m_e_bar = sum(images)/num
m_sigma = np.sqrt(sum((images - m_e_bar)**2) / (num - 1))
return m_sig... |
st11, st22 = map(str, input().split())
if len(st11) < len(st22):
s = len(st11)
zero_pop = len(st22)
else:
s = len(st22)
zero_pop = len(st11)
lst1 = list('0') * zero_pop
for i1 in range(s):
if st22 in st11 or st11 in st22:
lst1[i1] = '1'
if st11[i1] == st22[i1]:
lst1[i1] = '1'
pr... |
# Lint as: python3
#
# Copyright 2020 Google LLC
#
# 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 a... |
from Bio import SeqIO
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
file_name = 'MATN3_DES136-7_2-1RD072018-02-14-16-04-15_copy.ab1'
record = SeqIO.read(file_name, 'abi')
sequence = record.annotations['abif_raw']['PBAS1']
def abi_trim(seq_record):
start = False # flag for starting position of ... |
import os
import zipfile
for file in os.listdir():
print(file)
if(file.endswith(".zip")):
with zipfile.ZipFile(file, 'r') as zip_ref:
zip_ref.extractall('.')
os.remove(file)
|
Title: Creative Crossroads
Overview: Website dedicated to a full cross section of artistic talents.
Capstone Goals:
-Images
-Writings
-Voting system
-User Accounts
-Comments
-Some sort of API integration
Extended Goals:
-Audio works
-Videography (embedded, not hosted)
-Combination ... |
from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User, Group
from django.core.urlresolvers import reverse
import datetime
from ..models.projects import Project, ProjectSeries
from ..models.authors import Author
from ..models.artifacts import Artifact
from ..forms.... |
# Ejercicio 6
# Dada una frase introducida por teclado, guarda en un conjunto todas las palabras que contengan la letra
# indicada por el usuario.
frase = input("Frase: ")
letra = input("Letra: ")
frase = frase.lower()
letra = letra.lower()
palabras = frase.split(" ")
baul_letra = set()
for i in palabras:
if let... |
import sys
import traceback
import logging
import logging.config
import importlib
import bson.objectid
import config.global_configuration as global_conf
import database.client
import util.database_helpers as dh
def main(*args):
"""
Import a dataset into the database from a given folder.
:args: First argu... |
#13.2_chisq
import rpy2.robjects as ro
r = ro.r
table = r("read.table('smoking_and_lung_cancer.txt', header = TRUE, sep = '\t')")
print(r.names(table))
cont_table = r.table(table[1], table[2])
chitest = r['chisq.test']
print(chitest(cont_table)) |
## do not change anything in here!!!!
## go to run program, you should not have to save it to run it!
## put the grades you have recieved already and the grades you hope to get.
# it will print out your grade number and letter grade for the class
print("Welcome to Dr.Dornshuld's Chemistry Calculator")
again = 'y'
w... |
#!/usr/bin/env python
import sys
import socket
import os
import json
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
config = json.load(open('config.json'))
# probably no necessary --> remote kv stor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.