text stringlengths 38 1.54M |
|---|
import urllib3
import threading
import queue
import argparse
import sys
import signal
""" Argument parser """
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--url", help="url to brute force", required=True)
parser.add_argument("-w", "--wordlist", help="wordlist to use, defautl is common.txt", default='.... |
class string():
def __init__(self, text):
self.text = text
def uppercase(self):
self.text = self.text.upper()
var = string("Hello")
var.uppercase()
print(var.text) |
from __future__ import annotations
from dataclasses import dataclass
from typing import ByteString
from struct import unpack_from, pack
from ndr.structures import NDRType
from ndr.structures.conformant_varying_string import ConformantVaryingString
from ndr.structures.pointer import Pointer, NullPointer
@dataclass
cl... |
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL.shaders import *
import math
width, height = 1200, 768
def draw_rect(x, y, width, height):
glBegin(GL_QUADS) # start drawing a rectangle
glVertex... |
# longest_stretch.py: writes the longest contiguous sequence of equal
# integer values, from the sequence of integers read from the
# command line.
import stdio
import sys
# Create a list a consisting of the integers from the command line.
a = []
for v in sys.argv[1:]:
a += [int(v)]
# Identify the starting posit... |
from Util import *
"""
read data from file of this experiment.
return orig_x, x, contro_switch
"""
def read_data(filename):
# data format (orig_x, x, contro_switch, failed_switch_loc, flow_switch)
matrix = np.loadtxt(filename, dtype=np.int)
orig_x = matrix[0].tolist()
x = matrix[1].tolist()
... |
import urllib.request
import json
from fetchingmodule import bitish,gucci,fptshop,converse,nemfashion
from bs4 import BeautifulSoup
from unidecode import unidecode
import string
with open("json/bitish.json","w") as f:
json.dump(bitish("https://theme.hstatic.net/1000230642/1000378739/14/storesjs.json?v=44"),f)
wit... |
from common import config
from version_control import git_control
config = config.get_from_json()
#validation_result = access_validation.check() # todo: nesmuki. sho vajadzeetu infa konstruktoraa
#if not validation_result: exit (1) # exit vajadzeetu validatoraa
#infa_connection = pmrep.Pmrep(config.content) # tod... |
import json
import pickle
from abc import ABCMeta, abstractmethod
from collections import namedtuple, Counter, defaultdict
from pyspark import SparkConf, SparkContext, RDD, Broadcast
from qanta.util.environment import QB_SPARK_MASTER
from qanta.datasets.quiz_bowl import QuizBowlDataset
from qanta.wikipedia.cached_wiki... |
from app.celery import make_celery
from flask import current_app
from app.model.User import User
celery = make_celery(current_app)
@celery.task(bind=True)
def add(self, a, b):
u = User.query.first()
import sys
print("---------------- {}".format(self.request.id))
print("**************** {}".format(u.... |
# Comparision operator with type.
hungry = True
z = 'Feed the bear' if hungry else 'Do not see the bear'
print (z) |
'''
Created on Mar 7, 2015
@author: niko
'''
import numpy as np
import matplotlib.pyplot as plt
from common import *
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
def initializeModel(mdl, pretrainedMdl, binaryProtoFile, imageDims):
... |
import numpy as np
from scipy import misc
import matplotlib
import matplotlib.pyplot as plt
import sys
sys.path.insert(0, '$CAFFE_ROOT/python')
import caffe
import os
import pickle
import math
import csv
import copy
import allsharp_source.allsharp_selective_search as ss
from operator import add
from collections import ... |
from math import pow
f = 0
i = 1
b = ''
n = int(input("Введите количество билетов\n"))
if n < 1 or n > pow(10, 9):
print ("Неверный ввод")
print ("Введите билеты через 'ENTER'")
for i in range (n):
a = str(input())
if a[0] == 'a' and a[4] == '5' and a[5] == '5' and a[6] == '6' and a[7] == '6' and a[8] == '1... |
height = float(input('what is your height? (cm) '))
weight = float(input('what is your weight? (kg)'))
#convert unit from cm to m
height_cm = height / 100
#BMI calculate
BMI = weight / (height_cm * height_cm)
print('your height is: %.f (cm) = %.2f (m)' % (height, height_cm))
print('your weight is: %.f (kg)' % (weigh... |
# This Software (Dioptra) is being made available as a public service by the
# National Institute of Standards and Technology (NIST), an Agency of the United
# States Department of Commerce. This software was developed in part by employees of
# NIST and in part by NIST contractors. Copyright in portions of this softwar... |
"""
Common helpers
"""
import annealing
from hashlib import sha224
import pp_sha224
bin_format_dict = dict((x, format(ord(x), '8b').replace(' ', '0')) for x in '0123456789abcdef')
def bin_convert(string):
return ''.join(bin_format_dict[x] for x in string)
def bin_convert_orig(string):
return ''.join(fo... |
from build import FullTextBuild
from search import FullTextSearch
"""
采用whoosh搜索,会将结果高亮,并打印bm25的分数
"""
if __name__ == "__main__":
fulltextbuild = FullTextBuild('/home/xiaoxinwei/data/index')
fulltextbuild.add_doc(title="document-1", path="/c", content="现在,我代表国务院,向大会报告政府工作,请予审议,并请全国政协委员提出意见。",
... |
import collections
PREAMBLE_SIZE = 25
invalid = 0
q = collections.deque()
with open('9.txt') as fp:
for i in range(PREAMBLE_SIZE):
q.append(int(fp.readline().strip()))
for line in fp:
curr = int(line.strip())
hashset = set()
valid = False
for num in q:
if n... |
from collections import deque
import unittest
import pygame as pg
from config import NATIVE_RESOLUTION
from core.prepare import create_demo_party
from core.keys import Keys
from database.initialise_db import initialise_db
from ui.renderer import Renderer
from combat.battle import Battle
class StubEventHandler:
d... |
#1 /usr/bin/env python
from sense_hat import SenseHat
sense = SenseHat()
pink = (255,0,127)
speed = 0.05
message = "YEEEEEE 8======================================D~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~EEEEEEEEEEEEEE!"
sense.show_message(message, speed, pink, (0,255,0))
sense.clear()
|
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
# import sqlite3
# import mysql.connector
imp... |
num=int(input("enter a number:"))
sum=0
for num>0:
for i in range(1,num,1):
sum+=1/num
break
print(f"Result is {sum}") |
import torch
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss
from torch.utils.data import DataLoader
from torch.optim import Adam
import sys
from utils import get_device, format, plot
from models import get_model
from dataset import Dataset
MODEL_TYPE = 'NEG' # CBOW | NGRAM | SKIPGRAM | NEG
CONTEXT_SIZE = 1
... |
"""
Task D - WORLD MAP
Given a "large" image and a set of smaller patches (of constant dimensions)
find x,y coordinates of each smaller patch in the large image.
Patches can be exact copies or filtered in some way.
"""
from PIL import Image
import numpy as np
# from scipy import signal, fftpack
# ... |
import math, h5py, time, numpy as np
from mpi4py import MPI
rank = MPI.COMM_WORLD.Get_rank()
numProcs = MPI.COMM_WORLD.Get_size()
def report(status):
print "%s : %d/%d : %s" % (time.asctime(time.localtime()), rank + 1, numProcs, status)
def reportroot(status):
if rank == 0:
report(status)
def chunk... |
nombres = ["fran","esther","roberto","daniel"]
print(nombres)
# largo de la lista
print(len(nombres))
#Acceder a un elemento
print(nombres[0])
#Navegacion inversa
print(nombres[-1])
print(nombres[-2])
#Recuperar un rango de la lista
print(nombres[0:3]) # sin incluir el indice 3
print(nombres[:3]) # mostar la list... |
# -*- coding: utf-8 -*-
# --------------------------------------------------
#
# tools.py
#
# Written by cetinsamet -*- cetin.samet@metu.edu.tr
# April, 2019
# --------------------------------------------------
import random
random.seed(123)
import numpy as np
np.random.seed(123)
import scipy.io as sio
def load_dat... |
heroes = ["Luke Skywalker".casefold(),
"Indiana Jones".casefold(),
"James Bond".casefold(),
"Gandalf".casefold(),
]
choice = input("\nPlease choose an option from the list below: "
"\n\n"
"1. Luke Skywalker\n"
"2. Indiana Jones\n"
... |
print("hello")
data = "Hello World"
print(data)
print(data[2])
print(data[7])
data2 = "Hi %s!" % "ALex"
print(data2)
print('Hello')
def sum(i1, i2):
result =0
for i in range(i1,i2+1):
result += i
return result
def main():
print("Sum for 1 to 10: ", sum(1,10))
print("Sum for 20 t0 37: ", sum(20,37))
print("... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 21:22:06 2021
@author: pepe
This script evaluates the generations on the test set of a Baseline model. The
procedure is to split the reference text in half, so that the first half is the
prompt for the generations, and the second half is evaluated against the second
h... |
import pandas as pd
df = pd.read_csv('budget_data_2.csv')
df.head()
print('Financial Analysis')
print('---------------------------')
df['Date'].value_counts()
#all values in data column are unique
#The total number of months included in the dataset
total_months = 'Total Months: ' + str(len(df))
print... |
from .. import BaseApi, NamedEndpoint
from .urls import ChampionApiV3Urls
class ChampionApiV3(NamedEndpoint):
"""
This class wraps the Champion-v3 Api calls provided by the Riot API.
See https://developer.riotgames.com/api-methods/#champion-v3 for more
detailed information
"""
def __init__(s... |
import networkx as nx
from tqdm import tqdm
import heapq
class AdventOfCode:
def __init__(self, filename):
with open(filename) as f:
self.input = f.read().strip().splitlines()
self.key_to_key1 = None
self.key_to_key2 = None
def define_graph(self, lines):
keys = {}... |
# Example using PIO to drive a set of WS2812 LEDs.
import array, time
from machine import Pin
import rp2
# Configure the number of WS2812 LEDs.
NUM_LEDS = 8
PIN_NUM = 11
brightness = 0.2
######################## NEOPIXEL UTILITY ######################################
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_s... |
"""
Read in validation data, call predict method.
- The model itself is not just the estimator, but also
includes other data transformations
"""
import os
import pickle
import numpy as np
import pandas as pd
from sklearn.metrics import classification_report, accuracy_score
# constants
import settings
# UDFs
from util... |
"""Support for Snoo Device."""
from pysnooapi.const import (
MANUFACTURER
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_VIBRATION,
BinarySensorEntity,
)
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, SNOO_COORDINATOR, SNOO_GATEWAY
... |
import logging
from ftplib import FTP
logger = logging.getLogger(__name__)
def cd_tree(ftp, ftp_dir):
if ftp_dir != "":
try:
ftp.cwd(ftp_dir)
except Exception as e:
cd_tree(ftp, "/".join(ftp_dir.split("/")[:-1]))
ftp.mkd(ftp_dir)
ftp.cwd(ftp_dir)
... |
from ComputerVision import *
import io
import matplotlib.pyplot as plt
from PIL import Image
import time
import numpy as np
cam = ComputerVision()
#cam.startCapture()
#time.sleep(4)
#past = cam.image
cam.startCapture()
time.sleep(2)
while True:
print(cam.arucoExist())
cam.stopCapture() |
#!/usr/bin/env python
'''
Check that all links resolve.
Usage: checklinks.py /path/to/_config.yml /path/to/source_file.md ...
'''
import sys
import re
import yaml
LINK_USE = re.compile(r'\[.+?\]\[(.+?)\]')
def main(links_path, terms_path, file_paths):
'''
Main driver.
'''
defined = set(config_selec... |
import tensorflow as tf
from tf_helper.nn import weight, bias, variable_summary
from dmn_helper.attn_gru import AttnGRU
class EpisodeModule:
""" Inner GRU module in episodic memory that creates episode vector. """
def __init__(self, num_hidden, question, facts, is_training, bn):
self.question = quest... |
from src.chess_zero.agent import chinese_chess
board = chinese_chess.Board()
for mov in board.generate_legal_moves():
print(mov) |
import os
from pygame import display,font
scr = display.get_surface()
scrrect = scr.get_rect()
font.init()
print("path: ", __file__)
imgdir = os.path.dirname(os.path.dirname(__file__))
#police = font.Font('Roboto.ttf', 40)
police = font.Font(os.path.join(imgdir, 'Roboto.ttf'), 40)
class Score(object):
score = ... |
import urllib.request
def traffic_mark():
"""Вытаскивает значение пробок с сайта Екатеринбурга"""
url = "http://www.ekburg.ru/information/probki/"
f = urllib.request.urlopen(url)
s = f.read()
text = str(s)
value_litter = text.find('road')
value = int(text[text.find('</a>', value_litter) + ... |
#!/usr/bin/python3.4
# Setup Python ----------------------------------------------- #
import pygame, sys
import cloth
# Setup pygame/window ---------------------------------------- #
mainClock = pygame.time.Clock()
from pygame.locals import *
pygame.init()
pygame.display.set_caption('cloth?')
screen = pyga... |
s = input().split(' ')
cur_time = eval(s[0][0:-2]) * 60 + eval(s[0][-2:])
diff = eval(s[1])
then_time = cur_time + diff
r = str(then_time // 60) + '{0:0^2}'.format(then_time % 60)
print(r) |
count = 0.00
line = open("dna_samp.txt").read()
for x in range (0,len(line)):
if(line[x] == 'G' or line [x] == 'C'):
count = count +1
print "The file contains", count, "C and G."
prc = (count/len(line))*100
print "The percentage of GC to DNA is: "+str(prc)+"%"
|
#!/usr/bin/env python3
#Задача 7.3a
#ПОЧЕМУ Я НЕ МОГУ ПРОПУСТИТЬ ПУСТУЮ СТРОЧКУ?!?!?!?!?
#Не решил эту задачу
f = open('CAM_table.txt')
vlans = []
for line in f:
if line.split()[0].isdigit():
vlans.append(line.split()[0])
for word in line.split():
if '.' in word:
print(li... |
fileList = list(range(2000,2018,2))
print(fileList)
print(fileList[0])
print(fileList[0:3])
print(fileList[2:5])
print(fileList[:2])
print(fileList[2:])
print(fileList[-1])
print(fileList[-2:])
print(fileList[:-2])
"""
Output:
[2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016]
2000
[2000, 2002, 2004]
[2004, 2006... |
"""
Package for special functions.
"""
from . import gamma_functions
from . import error_functions
from . import zeta_functions
from . import tensor_functions
from . import delta_functions
from . import elliptic_integrals
from . import beta_functions
from . import polynomials
|
#!/usr/bin/env python
from stdatamodels.jwst.datamodels import CubeModel, TsoPhotModel
from ..stpipe import Step
from ..lib.catalog_utils import replace_suffix_ext
from .tso_photometry import tso_aperture_photometry
__all__ = ['TSOPhotometryStep']
class TSOPhotometryStep(Step):
"""
Perform circular aperture... |
from simphony_metaparser.flags import NoDefault
from simphony_metaparser.nodes import (
Ontology, CUBADataType, CUDSItem, FixedProperty,
VariableProperty)
def trivial_ontology():
ontology = Ontology()
ontology.data_types.extend([
CUBADataType(name="CUBA.CUBA_DATA_ONE",
ty... |
import re
import numpy
import pytesseract
from PIL import ImageDraw, Image, ImageFont
from fontTools.ttLib import TTFont
def fontConvert(fontPath): # 将web下载的字体文件解析,返回其编码和汉字的对应关系
font = TTFont(fontPath) # 打开字体文件
# print(font)
map_dict = font["cmap"].getBestCmap()
# print(map_dict)
... |
from node import Node
from minimax import alpha_beta_search
from helpers import *
import argparse
def get_parser():
'''
Returns a cli argument parser for the game
return: ArgumentParser
'''
parser = argparse.ArgumentParser(description='Play a game of nim')
parser.add_argument('--piles',
help='<pile1 count> <pi... |
#!/usr/bin/env python
PUZZLE="""11111
S1X11
11111
X11E1
1111X""".split('\n')
import copy
ROWS = len(PUZZLE)
COLS = len(PUZZLE[0])
def print_puzzle(puzzle):
for line in puzzle:
print(''.join([ch for ch in line]))
print('')
def find_path(puzzle, row, col, distance_so_far):
# Find all possible p... |
#help()
def tes (b):
a = 8
b += 4
c = 2
print(f'''A dentro vale {a}
B dentro vale {b}
C dentro vale {c}''')
a = 5
tes(a)
print(f"A fora vale {a}") |
import xml.etree.ElementTree as ET
import xmltodict
from imageai.Detection import ObjectDetection
import os
from scipy.spatial import distance
import numpy as np
def get_bbox_yolo(path_to_images, path_to_weights='/home/user/aylifind/weights/yolo.h5', output_folder='/home/user/aylifind/output/'):
detector = Object... |
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
Board = [list(map(str, input().strip())) for _ in range(N)]
def to_num(x, y):
return ord(Board[x][y]) - ord('A')
visited = [0] * 26
visited[to_num(0,0)] = 1
answer = 1
def DFS(currX, currY, depth):
global answer
dx, dy = [1,-1,0,0], ... |
# -*- coding: utf-8 -*-
import sys
import logging
from app import config
from colorlog import ColoredFormatter
class CustomLog:
def __init__(self, name, level, env: str):
pass
def log(*args):
logging.info(' '.join(map(str, args)))
logging.basicConfig(level=config.LOG_LEVEL)
LOG = logging.... |
# Written by Sahil Jayaram (saj2163) for COMS 6998 (Topics in Computer Science): Fundamentals of Speech Recognition
from abc import ABC
import torch
from transformers import RobertaModel
from torch.nn.modules import Module
from torch.nn import Linear, BatchNorm1d, Dropout, LSTM
from torch.nn.functional import softmax... |
# --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# code starts here
df = pd.read_csv(path)
p_a = df[df.fico > 700]
p_a = len(p_a) / df.purpose.count()
p_b = df[df.purpose == 'debt_consolidation']
p_b = len(p_b) / df.purpose.count()
df1 = df[df.purpose == 'debt_consolidation']
... |
import requests # pip install requests
from bs4 import BeautifulSoup # pip install bs4 # pip install html5lib
import pyttsx3 # pip install pyttsx3
engine = pyttsx3.init('sapi5')
voice = engine.getProperty('voices') # getting details of current voice
engine.setProperty('voice', voice[0].id)
def speak... |
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.models import Group, User
from django.core.mail import EmailMultiAlternatives
from django.http import JsonResponse
from django.shortcuts import redirect, render
from listArch.Forms.UserForm import UserForm
from listArch.... |
#!/usr/bin/env python2
"""
upload-to-devnull is the utility for the test upload perfomance for the CPE.
This script receive files that not related to size and redirect it to /dev/null on the server side.
According to this you can upload 1G, 10G, 100G or 1T file and don't think about size.
usage:
$ chmod +x ./u... |
import time
import datetime
import os
import subprocess
import azure
from azure.storage.blob import BlockBlobService
from azure.storage.blob import ContentSettings
block_blob_service = BlockBlobService(account_name='account_name' , account_key='account_key')
class camera:
def __init__(self,n=None,m=None):
... |
"""
2.6
*Реализовать структуру данных «Товары».
Она должна представлять собой список кортежей.
Каждый кортеж хранит информацию об отдельном товаре.
В кортеже должно быть два элемента — номер товара и словарь
с параметрами (характеристиками товара: название, цена, количество, единица измерения).
Структуру нужно сфо... |
import sys
sys.path.append('../..') # noqa
import numpy as np
from time import time
from src.base.base_eval import BaseEval
from src.utils.qpath import *
class UserGruEval(BaseEval):
def __init__(self, sess, model, config,
data_loader, logger=None, init_graph=False):
super(UserGruEval... |
"""
among other things
"""
import base64
class ObjectExt(object):
"""
methods extended
"""
def __init__(self, KEYS={}, TYPES={}):
self.__secret_key = '1234567890123456'
self.__KEYS = KEYS
self.__TYPES = TYPES
def get(self, item):
"""
get lol
"""
... |
from tkinter import *
root = Tk()
root.title('Basic calculator')
# creat an entry. specify width and border width
e = Entry(root, width=30, borderwidth=5)
# the grid is to make the size of all calculator elements consistent with each other
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def button_press(num):... |
# import beautifulsoup4 & connection requests library
from bs4 import BeautifulSoup
from requests import get
import pandas as pd
import itertools
import matplotlib.pyplot as plt
import seaborn as sns
import re
from time import sleep
import random
sns.set()
headers = ({'User-Agent':
'Mozilla/5.0 (Windows NT ... |
val = 65
for i in range(5):
for j in range(3):
if i+j < 2 or i-j > 2:
print(" ",end=" ")
else:
print(chr(val),end=" ")
val += 1
print()
|
#!/bin/env python3
#python script to parse publications from zotero in html for my academic homepage
# the produced html (written to stdout) is intended to be used as a partial layout for the hugo generated webpage
# aug 2016, Roelof Rietbroek
# This script is called in the following way:
# mkPubList.py STORAGESUBDIROF... |
"""
Create a zip with all recording folders required for evaluation - instead of having to store all recordings"""
import argparse
import os
from glob import glob
from os.path import join
from shutil import copytree
import numpy as np
import pandas as pd
from PIL import Image
from config import STATIONS
from helpers ... |
##
## Author: Kristina Striegnitz and Daniel W. Wolf
##
## 10-31-2013
##
## shooting-monsters-task4
##
## This program shows a player character (orange ball) which can be
## controlled using the 'a'and 'd' keys. It also displays a score.
##
#import the modules
import pygame
import random
import math
RADIUS = 0
X = 1... |
import math
class Triangle:
def __init__(self, side_a, side_b, side_c):
self.side_a = side_a
self.side_b = side_b
self.side_c = side_c
self.diameter = side_a+side_b+side_c
def area(self):
s = self.diameter/2
area_calc = (s*(s-self.side_a)*(s-self.side_b)*(s-s... |
from abaqusConstants import *
class SlidingTransitionAssignment:
"""The SlidingTransitionAssignment object stores the sliding transition assignment
definition for surfaces in ContactStd objects. The SlidingTransitionAssignment object
has no constructor or members.
Notes
-----
This object can ... |
import json
from pathlib import Path
from .aws import read_file, list_files
class Configurations:
def __init__(self, dir, s3, bucket, prefix):
self.loaded = self.load_specs(dir)
self.s3 = s3
self.bucket = bucket
self.prefix = prefix
def load_specs(self, dir):
return {... |
import numpy as np
import polychrom.forcekits
import polychrom.forces
import polychrom.polymerutils
import polychrom.starting_conformations
from polychrom.hdf5_format import HDF5Reporter, list_URIs, load_URI
from polychrom.simulation import Simulation
def test_basic_simulation_and_hdf5(tmp_path):
data = polychro... |
from Models import load_optimize_fit_select_and_predict
if __name__ == '__main__':
load_optimize_fit_select_and_predict()
|
import numpy as np
import tensorflow as tf
import keras.backend as K
from PIL import Image
input_image_path = ''
# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="model_dce.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.ge... |
import os
import gzip
import _pickle as cPickle
import wget
import numpy as np
# from https://github.com/kdexd/digit-classifier
def load_mnist():
if not os.path.exists(os.path.join(os.curdir, 'data')):
os.mkdir(os.path.join(os.curdir, 'data'))
wget.download('http://deeplearning.net/data/mnist/mnis... |
# Setup QPCR experiments
import math
from ..Experiment import reagents, clock, logging
from ..Experiment.JobQueue import JobQueue
from ..Experiment.experiment import Experiment
from ..Experiment.sample import Sample
from .TRP import diluteName
from . import trplayout
class MSetup(object):
TGTINVOL = 4
def __... |
import cv2
import numpy as np
import HandTrack as ht
import WhiteBoard as wb
from tkinter import *
def manage_statusbar_1(srcimg, isGettingSample , isMarking , isRecording):
status_string = "Status: "
if(isGettingSample):
status_string += "-Getting Sample"
else:
status_string += "-Trackin... |
#4-3
for num in range(1,21):
print(str(num).ljust(5),end = "")
print()
#4-4
"""print(1~1000000)"""
#4-5
million = [i for i in range(1,1000001)]
print("Min in million: "+str(min(million)))
print("Max in million: "+str(max(million)))
print("Sum of million: "+str(sum(million)))
#4-6
odd_number = [i for i in range(1,21... |
# Significance Test API
from flask import Flask, request
from flask_restful import Resource, Api
from flask_cors import CORS
from flask.helpers import make_response
import statsmodels.stats.api as sms
import pandas as pd
from scipy import stats
import s3fs
import io
import json
app = Flask(__name__)
CORS(app)
api = Api... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-29 00:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('uni', '0004_auto_20180328_1329'),
]
operations = [
migrations.AlterField(
... |
from flask import Flask, jsonify, json
import PrimeTools as pt
import os
deploy_port = int(os.environ.get('PORT', 5000))
api = Flask(__name__)
help_text = """
<h3>PrimeTools Web API:</h3>
<table style="width:100%">
<tr>
<th style="text-align:left">HTTP Method</th>
<th style="text-align:left">Route</th>
</tr>... |
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import Skill
# Register your models here.
admin.site.register(get_user_model())
admin.site.register(Skill)
|
from drdown.medicalrecords.models.model_medicines import Medicine
from django import forms
class MedicineForm(forms.ModelForm):
class Meta:
model = Medicine
fields = [
"medicine_name",
"medicine_dosage",
"medicine_use_interval",
"medicine_in_use",
... |
from Shoes.shoes import shoes
from Shoes.Shoe.shoe import shoe
from Map.Map import EntMap
from Robot.robot import Robot
import simpy
class generator:
def __init__(self, env):
self.map = EntMap()
self.shoes = []
self.pair_slot = []
self.robot = Robot()
self.sh... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-17 07:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0010_collection_samples_visible'),
]
operations = [
migrations.Alt... |
import numpy as np
import cv2
import time
from screenGrab import grabscreen
import os
from Xlib import display, X
from utils import countDown, move_body, move_head, get_Keras_model
import uinput
import pickle
from keras.models import load_model
# Load model
WIDTH = HEIGHT = 224 # I don't like how split up this is and ... |
import pandas as pd
import urllib3
from bs4 import BeautifulSoup
http = urllib3.PoolManager()
urls = []
for index in range(107000000, 107267472):
url = "http://dbpub.cnki.net/grid2008/dbpub/detail.aspx?dbcode=SCPD&dbname=SCPD2017&filename=CN" + str(
index) + "A&uid=WEEvREcwSlJHSldRa1FhdkJkcGp4dXFrc... |
from tkinter import *
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
current_word = {}
all_words = {}
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
original_data = pandas.read_csv("data/french_words.csv")
all_words = original_data.to_dict(orient="records")
else... |
import sys
def letter_starter(email):
name = email.split('@')[0].split('.')[0].capitalize()
return f'Dear {name}, welcome to our team.'
if __name__ == '__main__':
if len(sys.argv) == 2:
print(letter_starter(sys.argv[1]))
else:
print('usage: python3 letter_starter e-mail')
|
from PyQt5 import QtWidgets as qw
from PyQt5 import QtCore as qc
from PyQt5 import QtGui as qg
from Point3D import Point3D
class Pane(qw.QLabel):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.color = qc.Qt.white
self.thickness = 3
self.grid = Fals... |
from flask import Flask, render_template, request
#from config import Config
import os
import pickle
import nltk
import numpy as np
import pandas as pd
from nltk.corpus import stopwords
mystops = set(stopwords.words("english"))
from bs4 import BeautifulSoup
import re
from p6_functions import *
app = Flask(__na... |
#by using math module
import math
sine_60=math.sin(math.radians(60))
print("the sine of 60 indegree is :",sine_60,"\n")
import math
print("the value of cos π is :",math.cos(math.pi),"\n")
import math
print("the value of tan 90° is :",math.tan(90),"\n")
import math
x=5^8
print("factorial of 5^8 is:", math.factorial (... |
from pyne.material import Material, MaterialLibrary
from pyne import mcnp
from string import Template
import numpy as np
import math
import sys
import physical_constants as pc
class PinCellMCNP:
"""Class to write MCNP
"""
mat_numbers = {'fuel' : 1, 'clad' : 2, 'cool' : 3}
base_string = Template("""\
... |
#!/usr/bin/env python
import urllib2
import re
import os
OUTPATH='../metareadability'
def parse_us_census( urls, outfilename ):
""" download and parse the names from the 1990 US census, and output one per line """
line_pat = re.compile(r'^\s*(\S+)\s+')
names = set()
for url in urls:
print("p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.