text stringlengths 38 1.54M |
|---|
import files
name = input('What is the packname you want? ')
print('Creating pack...')
files.makeFolder(name)
files.makeFile(name+'/pack.mcmeta','''{
"pack":
{
"description": "This is a datapack using DRKDesigns' packhelper",
"pack_format": 1
}
}''')
files.makeFolder(name+'/data/pack/functions')
files.makeFolder... |
from util import *
import numpy as np
from collections import defaultdict
from collections import Counter
from nltk.corpus import wordnet
from sklearn.cluster import KMeans
# Add your import statements here
class InformationRetrieval():
def __init__(self):
self.index = None
def buildIndex(self, docs, docIDs):... |
from sklearn import datasets, metrics
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from skimage import io
from skimage.transform import resize
import numpy as np
digits = datasets.load_digits()
X, y = digits.data / 255., digits.target
X_train, X_test, y_train,... |
import torch
from torch import nn
class RNNEncoder(nn.Module):
def __init__(self, input_size, hidden_size, embedding_size):
super().__init__()
self.hidden_size = hidden_size
self.embedding_size = embedding_size
self.embedding = nn.Embedding(input_size, self.embedding_size)
... |
from functionlib import RK4
import matplotlib
import matplotlib.pyplot as plt
from math import log
e = 2.71828
dy = lambda u, y, x : u
ddy = lambda u, y, x : 1 - x - u
# Q2, a
# for x in range[-5, 5]
fig, ax = plt.subplots()
y1, x1 = RK4(ddy, dy, 1, 2, 0, -0.02)
y1.reverse()
x1.reverse()
y2, x2 = RK4(ddy, dy, 1,... |
from flask import Flask, session, request, redirect, render_template, flash
from mysqlconnection import MySQLConnector
import md5
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = '04c46b3b62477fc999e63d62c635d97c'
mysql = MySQLConnector(app, '... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-03-13 13:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chdfh', '0007_auto_20180313_1304'),
]
operations = [
migrations.AlterField(... |
import asyncio
import websockets
async def hello():
async with websockets.connect('ws://localhost:8765') as websocket:
await websocket.send('get')
f = await websocket.recv()
print("< {}".format(f))
asyncio.get_event_loop().run_until_complete(hello()) |
import mysql.connector
connection = mysql.connector.connect(host='localhost',database='behbes',user='root',password='pass')
cursor = connection.cursor()
with open('illnesses.txt') as illnessFile:
for line in illnessFile:
data= line.split('|')
update_illness = ("UPDATE behbes.Illnesses SET... |
# Arshdeep Singh
# TCSS 554 A
from nltk.stem.snowball import SnowballStemmer
import os
import re #Regular Expressions
import string
Stemmer_g = SnowballStemmer("english")
pyFileDir = os.path.dirname(os.path.realpath('__file__')) #the filepath of this python file.
vlogFolder = os.path.join(pyFileDir, "transcripts/"... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
import sys
import pprint
def removeTrailingNewline(line):
if line[-1] == '\n':
line = line[:-1]
return line
def parseFile(filename):
f = open(filename)
line = f.readline()
mainClass = {"name": "", "rules": [], "base": []}
currentClass = mainClass
classes = {"": mainClass}
canLi... |
import json
import django.views as views
from django.http import JsonResponse
from django.core import serializers
import server.source.db.interface.Database as Database
class UpdateUserData(views.View) :
def get(self, request) :
Database.updateData(request.GET)
return JsonResponse({'status' : 'ok'})
|
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.index, name="index"),
path('search', views.searchMovie, name="search"),
path('moviesingle/<str:id>', views.movieinfo, name="movieinfo"),
path('moviegridfw', views.movieg... |
"""
GUI class for analysis options prompt
"""
from PyQt5.QtCore import (QCoreApplication, QDate, Qt)
from PyQt5.QtGui import (QColor, QImage, QPainter, QIcon, QFont)
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QWidget, QAction, QMenu, QDialog, QLabel, QVBoxLayout, ... |
tupla = {''}
while True:
try:
joias = input()
if joias == '':
break
else:
tupla.add(joias)
except:
break
print(len(tupla)-1) |
import os, sys
for root, dirs, files in os.walk('.'):
#dirs[:] = [d for d in dirs if d != 'ru']
for name in files:
if name.endswith(".pq"):
full_name = os.path.join(root, name)
if name != '.pq':
os.makedirs(os.path.splitext(full_name)[0], exist_ok = True)
... |
# --^_^-- coding:utf-8 --^_^--
# @Remark:登录测试数据
from TestDatas.Comm_Datas import web_login_url
# 正常场景
success_data = {"user":"admin","pwd":123456,"check":web_login_url}
# 异常场景1
wrong_datas = [
{"user":"","pwd":"123456","check":"必填参数为空"},
{"user":"admin","pwd":"","check":"登录失败,帐号或密码错误"},
{"user":"adminn",... |
N, S = map(int, input().split())
A = list(map(int, input().split()))
left, right, hap, result, temp = 0, 0, A[0], 0, 0
while left <= right and right < N:
if hap < S:
right += 1
if right < N:
hap += A[right]
elif hap >= S:
temp = right - left + 1
if result == 0:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 12 23:03:40 2018
@author: Carvin
"""
import socket
import sys
import threading
import time
import os
import random
class VauleError(Exception):
def __init__(self, message):
self.message = message
class ParameterError(Exception):
def __init__(self, messa... |
# -*- coding: utf-8 -*-
from kcweb.config import session as kcwsession
from kcweb.common import globals as kcwglobals
import time,random,hashlib
from kcweb.utill.cache import cache as kcwcache
from datetime import datetime
def __md5(strs):
m = hashlib.md5()
m.update(strs.encode())
return m.hexdigest()
def s... |
'''
@author: gelareh.meidanipour@uni-siegen.de, manuel.ohrndorf@uni-siegen.de
'''
import concurrent.futures
from pathlib import Path
import numpy as np
import pandas as pd
from buglocalization.dataset.text_graph_data_set import (BugSampleTextGraph,
DataSetTextGr... |
import os
from http import cookies
def usertrack():
if 'HTTP_COOKIE' in os.environ:
data=os.environ['HTTP_COOKIE']
cookie=data.split(';')
(c2,v2)=cookie[0].split('=')
(c1,v1)=cookie[1].split('=')
return v1
else:
print ("<script>alert('Invalid user please login first...')</script>")
print ("<s... |
import sys
import random
import math
import time
def digit():
z = 1.23e-4 + 5.6e+89j
print("real",z.real)
print("imag",z.imag)
x = 4.5
y = 4
print("int",int(x))
print("float",float(y))
print("complex",complex(y))
print("type",type(x),type(y),type(z))
def string_operator():
s... |
"""
Channel module
Copyright (c) 2009 John Markus Bjoerndalen <jmb@cs.uit.no>,
Brian Vinter <vinter@nbi.dk>, Rune M. Friborg <rune.m.friborg@gmail.com>.
See LICENSE.txt for licensing details (MIT License).
"""
# Imports
import uuid
import pickle
from pycsp.parallel import protocol
from pycsp.parallel.exceptio... |
import torch
from gym.spaces import Box
import numpy as np
import torch_rl
from torch_rl.core import Sensor
from .spaces import PytorchBox
from .spaces import CheapPytorchBox
from .spaces import MultipleSpaces
'''
Defines different generic sensors, particulary used to build sensors based on some sensors
'''
class Py... |
#!/usr/bin/env python2.7
# encoding: utf-8
"""
@brief: 逻辑回归
@author: icejoywoo
@date: 26/03/2017
"""
import numpy
import random
def loadDataSet():
dataMat = []
labelMat = []
with open('testSet.txt') as fr:
for line in fr:
lineAttr = line.strip().split()
# x0, x... |
from enlace import *
import time
import numpy as np
import math
# serialName1 = "/dev/ttyACM2"
# com1 = enlace(serialName1)
# serialName2 = "/dev/ttyACM1"
# com2 = enlace(serialName2)
'''HEAD
Tipo de pacote (dados, comando etc.)
Versão (IPv4, IPv6)
Número do pacote (incremental durante a transmissão)
Tamanho do dad... |
#!/usr/bin/env python3
# vim: sw=4:ts=4:et
import argparse
import os
import os.path
import logging
import logging.config
import logging.handlers
import ssl
import sys
import io
import time
import traceback
import signal
import socket
from configparser import ConfigParser
from subprocess import Popen, PIPE, DEVNULL
P... |
from sg import *
exec(animation_code)
from phymin import *
scene(1920,1080)
grid()
rotate(10)
cube(0,200,50,400)
cube(0,200,50,400)
show(inline=True)
|
#!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
#!/usr/bin/env python3
import os
def storagePath(url):
url = url.split("//")[1]
folderName = url.split("/")[0]
dirPath = '/tmp/' + folderName
if not os.path.exists(dirPath):
os.mkdir(dirPath)
return dirPath
|
import FWCore.ParameterSet.Config as cms
from FastSimulation.Tracking.hltTracksForMuons_cff import *
from FastSimulation.Tracking.hltElectronGsfTracks_cff import *
from FastSimulation.Tracking.hltSeeds_cff import *
from FastSimulation.Tracking.hltPixelTracks_cff import *
# The hltbegin sequence (with L1 emulator)
HLT... |
# Generated by Django 2.2.3 on 2019-08-21 04:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('rbac', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UserInfo',
fields=[
... |
#! /usr/bin/python
# zCall: A Rare Variant Caller for Array-based Genotyping
# Jackie Goldstein
# jigold@broadinstitute.org
# May 8th, 2012
import sys
from optparse import OptionParser
from calcMeanSD import *
### Parse Inputs from Command Line
parser = OptionParser()
parser.add_option("-R","--report",type="string",... |
import sqlite3, json
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
class Item(Resource):
item_parser = reqparse.RequestParser()
# item_parser.add_argument(
# 'name',
# type = str,
# required = True,
# help = "Null value, this is a required field.")
item_parser.add_argument(... |
import sqlite3
connection = sqlite3.connect('database.db')
# execute database commands
connection.execute('CREATE TABLE IF NOT EXISTS movies (title TEXT, year INTEGER, genre TEXT)')
print('Table created successfully')
# close database connection
connection.close()
|
####Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (like the name of this kata).
###Strings passed in will consist of only letters and spaces.
###Spaces will be included only when more than one word is present.
def split_sente... |
import sys
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
import nn.losses as losses_utils
class DSBowlCLassifier:
def __init__(self, net, max_epochs):
"""
The classifier for carvana used for training and lau... |
from app import mongo
def insert(user):
print(mongo)
db=mongo.db
dbResponse=db.users.insert_one(user)
x=dbResponse.inserted_id
print(dbResponse)
return x |
from confound_prediction.utils import _ensure_int_positive
from nose.tools import assert_raises
def test_ensure_int_positive():
assert _ensure_int_positive(5, default=None) == 5
assert _ensure_int_positive(5.1, default=None) == 5
assert _ensure_int_positive(5, default=10) == 5
assert _ensure_int_posit... |
from datetime import datetime, timedelta
from github import Github
from pybuildkite.buildkite import Buildkite
from ray_release.test import (
Test,
TestState,
)
from ray_release.logger import logger
from ray_release.aws import get_secret_token
RAY_REPO = "ray-project/ray"
AWS_SECRET_GITHUB = "ray_ci_github_t... |
"""Dog-leg trust-region optimization."""
from __future__ import division, print_function, absolute_import
import numpy as np
import scipy.linalg
from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
__all__ = []
def _minimize_dogleg(fun, x0, args=(), jac=None, hess=None,
*... |
class DuplicateRegistration(Exception):
pass
class NoActiveScreen(Exception):
pass
class InvalidContent(Exception):
pass
|
from requests import Session
from bs4 import BeautifulSoup as bs
s = Session()
fd = open('second_all_data.txt',mode='w',encoding='utf-8',newline="")
url = 'https://driverbase.com/inventory?search.SortTypeId=3&search.DealershipId=0&search.Zip=10010&search.DistanceFromZip=100&search.InventoryType=all&search.MakeId=0&sear... |
import cv2
from matplotlib import pyplot as plt
import numpy as np
import math
def warp(img, mat):
mat = np.linalg.inv(mat)
A = np.zeros((img.shape[0] * img.shape[1] * 3, 9), dtype='float32')
X = np.float32([[mat[0, 0]], [mat[0, 1]], [mat[0, 2]], [mat[1, 0]], [mat[1, 1]], [mat[1, 2]], [mat[2, 0]],
... |
import os
import cv2
import glob
import pydicom
import argparse
import subprocess
import numpy as np
DESCRIPTION = """What is the script doing :
Takes in a DICOM folder with DICOM series
(Eg DICOM folder sturcture: dicom/37978.000000-T2reg-73187/)
Performs the following operations:
1. write the data out as jp... |
# Python implementation of left rotation of an array k times
def leftRotate(arr, n, k): # functioon to leftRotate array[] no. of times
k = k % n
for i in range(n):
print(str(arr[(k + i) % n]), end=" ") # print rotated array
arr = [1, 3, 5, 7, 9]
n = len(arr)
k = 2
leftRotate(arr, n, k) # function... |
import pygame
class Configuracoes():
def __init__(self):
# Tela
self.tela_largura = 1300
self.tela_altura = 600
self.tela_cor = [255, 255, 255]
self.tela_titulo = 'Jogo fofo'
self.tela_icone = './assets/coracao.png'
self.tela_texto_cor = [0, 0, 0]... |
#moving files
import os
#os.system('pip install pexpect')
from pexpect import pxssh
import getpass
dest="192.168.0.26"
dest_path = ':/home/dc'
filename = 'testfile.txt'
print("current cwd:",os.getcwd())
hostname='nlpdl.ddns.net'
username='dc'
filename='testfile.txt'
try:
s = pxssh.pxssh()
hostname = input('... |
from fastapi import APIRouter, Body
from fastapi.encoders import jsonable_encoder
from app.server.student_db import (
add_student,
delete_student,
retrieve_student,
retrieve_students,
update_student,
)
from app.server.models.student import (
error_response_model,
response_model,
Student... |
import socket
import hashlib
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
def get_desIP(message):
end_loc = message.find("|")
return message[1:end_loc - 1]
def pack_key(key, message):
return key + "|" + message
public_key = open('KDC_public_key', 'r').read... |
import json
import os
import numpy as np
from config import Config
from models.pytorch_models.ar_detector_cnn import ARDetectorCNN
from preprocess.feature_label_preparer import FeatureLabelPreparer
from utils.helper_functions import get_index_to_remove
class CNNModelManager:
def __init__(self, models, dataset):... |
"""
This is the main module.
"""
import os
print "Current directory is", os.getcwd()
def main():
"""
Main function
"""
print "This is the main function"
|
casa = float(input('Digite o preço da casa: R$'))
salario = float(input('Digite o seu salário: R$'))
anos = int(input('Digite em quantos anos você deseja pagar a casa: '))
num = casa/(anos * 12)
mínimo = salario * 30/100
print('Para pagar a casa em {} anos você precisará de R${:.2f} '.format(anos, num))
if num <= mínim... |
options = '' # schema
database = "" # dbname
user = "" # user
password = "" # password
host = "" # host
port = # port
path_to_json = '' # path to json file
instagram_target = '' # account to scrap
instagram_user = '' # your account
instagram_password = '' # your password
|
from prometheus_client import Gauge
metrics = {
"hu": Gauge("humidity", "humidity", ["device_name"]),
"il": Gauge("illumination", "illumination", ["device_name"]),
"mo": Gauge("movement", "movement", ["device_name"]),
"te": Gauge("temperature", "temperature", ["device_name"]),
}
|
#!/usr/bin/env python3
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import numpy as np
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from ._conv_block import *
from ._fc_block import *
... |
#! /usr/bin/python
def fourSumCount(A, B, C, D):
first_sum = {}
second_sum = {}
sol = []
sol_count = 0
for i in range(0, len(A)):
for j in range(0, len(B)):
addition = A[i] + B[j]
indices = [i,j]
... |
import numpy as np
from sigfeat.base import Feature
from sigfeat.feature.delta import Delta
from sigfeat.source.array import ArraySource
from sigfeat.extractor import Extractor
from sigfeat.sink import DefaultDictSink
def test_delta():
class A(Feature):
def process(self, data, res):
return fl... |
# ridge example of sklearn
from sklearn.linear_model import Ridge
import numpy as np
n_samples, n_features = 10, 1
np.random.seed(1428)
y = np.random.randn(n_samples)
X = np.random.randn(n_samples, n_features)
clf = Ridge(alpha=1.0)
F = clf.fit(X, y)
print(F.coef_, F.intercept_)
xm = np.mat(X)
w = np.mat(F.coef_)... |
from django import forms
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import CustomUser
def index(request):
return render(request, "customauth/index.html")
class MyUserForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordI... |
# -*- coding: utf-8 -*-
# Item pipelines are defined here
from w3lib.html import remove_tags
import pymongo
from datetime import datetime, date
from pymongo.errors import ConnectionFailure
from scrapy.conf import settings
from scrapy import log
class IsentiaScrapyPipeline(object):
collection_name = 'g_news'
... |
import random
# Pattern Function..
def diceFace(num):
print("\n=========")
if num == 1:
print("| " + " |"+"\n| " + "0" + " |"+" * 1(ONE) *"+"\n| " + " |")
if num == 2:
print("| " + " |"+"\n| " + "0 0" + " |"+" * 2(TWO) *"+"\n| " + " |")
if num... |
# Generated by Django 2.1.1 on 2018-09-20 12:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("backers", "0001_initial"),
("aids", "0027_auto_20180918_1047"),
]
operations = [
migrations.AddField(
model_name="aid",
... |
# #Hack logging for debug logs
# from __future__ import print_function
# import sys
from flask import Flask, json
from flask import request
import models
import os
from api import load_data, save_competitive_standings, load_competitive_standings
app = Flask(__name__)
app.json_encoder = models.JsonEncoder
@app.rout... |
# -*- coding:utf-8 -*-
import os
import config
import json
index = "law"
doc_type = "big_data"
dir_path = "/mnt/new/"
server_dir = os.path.dirname(os.path.realpath(__file__))
config_file = os.path.join(server_dir, 'config.py')
local_config_file = os.path.join(server_dir, 'local_config.py')
se = set()
def form(x):... |
# coding: utf-8
import sys
from setuptools import setup
import postmarker
install_requires = ["requests>=2.20.0"]
extras_require = {}
if sys.version_info[0] == 2:
extras_require["tests"] = "mock"
with open("README.rst") as file:
long_description = file.read()
setup(
name="postmarker",
url="htt... |
import numpy as np
import pickle
from math import sqrt
import timeit
from datetime import datetime
import os
import zipfile
###################
#helper methods creation of input files
#creates int-to-URI dicts for entities and relations
#input is the complete triple-store
def parse_triple_store(triples):
... |
class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
n = len(s)
dist = []
for i in range(n):
dist.append(abs(ord(s[i])-ord(t[i])))
#print(dist)
ans = 0
l,r = 0,0
cost = 0
while r < n:
cost += dist[r]
... |
#!/usr/bin/python3
import json
import os.path
import logging
import time
import requests
import math
import config
# import display
display_config = config.conf["atm"]["display"]
try:
display = getattr(__import__("displays", fromlist=[display_config]), display_config)
except AttributeError:
if config.conf["a... |
from django.utils import timezone
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.utils import formats
from django.db.models import (
Model,
CharField,
DateTimeField,
ForeignKey,
CASCADE,
PositiveI... |
import numpy as np
#from PSF_tools.gaussian_kernel_3D import gaussian_kernel_3D
from PSF_tools.applyPSFadjvar3Dz import applyPSFadjvar3Dz
from scipy.signal import convolve
from PSF_tools.h import h
def adjblur_alt_z(Iblurnoisy, z, Nh, Nx, Ny, Nz, Sx, Sy, Sz, Phiy, Phiz):
Htyz = applyPSFadjvar3Dz(Iblurnoisy, z, Nh,... |
class CaixaEletronico():
def __init__(self, notas_200=10, notas_100=20, notas_50=30, notas_20=50,
notas_10=100, notas_5=100, notas_2=150):
self.notas_disponiveis = [notas_200, notas_100, notas_50,
notas_20, notas_10, notas_5, notas_2]
self.notas_... |
from __future__ import print_function, division, absolute_import
import unittest
import numpy as np
from openmdao.api import Problem, Group, IndepVarComp
from openmdao.utils.assert_utils import assert_check_partials, assert_near_equal
from boring.util.spec_test import assert_match_spec
from boring.src.sizing.thermal_... |
'''
A class extends TestSuitBase for baidumap.
@author: U{c_chuanc<c_chuanc@qti.qualcomm.com>}
@version: version 1.0.0
@requires:python 2.7+
@license:
@see: L{TestSuitBase <TestSuitBase>}
@note:
@attention:
@bug:
@warning:
'''
from utility_wrapper import *
import fs_wrapper
from test... |
import re
class User:
def __init__(self, userInputValidator):
self.userInputValidator = userInputValidator
self.__firstName = None
self.__lastName = None
self.__email = None
self.__mobileNumber = None
self.__password = None
def setFirstName(self):
self... |
from pytrends.request import TrendReq
from pytrends.exceptions import ResponseError as PytrendsError
from data_loaders.market_cap import get_top_x_market_cap
from datetime import datetime, timedelta
import time
import pandas as pd
import requests
import calendar
import urllib.request
import json
pytrend = TrendReq(hl=... |
#####################################################################################
#
#
#
#####################################################################################
import math
import numpy as np
import collections
# Calculating reduced Mass given to masses (in AMU) of the nuclei involed.
m0 = 33.9802
... |
# to import fresh_tomatoes media files
import fresh_tomatoes
import media
# insatnces for class movie
Avengers = media.Movie("Avengers: Infinity War", "action",
"https://preview.ibb.co/icTDFo/avengers_infinity_war"
"_imax.jpg",
"https://www.you... |
__author__ = 'thanakorn'
class Follwer(object):
def __init__(self):
pass
def follow(self, publisher):
publisher.add_follower(self)
def receive(self, msg):
pass
|
from sulley.exceptions import InvalidConfig
class BaseProvider(object):
def __init__(self, key, secret, phone):
self.key = key
self.secret = secret
if not phone.startswith('+'):
raise InvalidConfig('Invalid phone number. '
'Phone numbers should ... |
import re
wt.add_rule(re.compile('^%s/(.*)$' % STATIC_URL), static_serve,
['static_file'])
wt.add_rule(re.compile('^%s/blog/([a-za-z0-9\-]+)$' % BASE_URL), blog_page,
['entry'])
wt.add_rule(re.compile('^%s/page/([a-za-z0-9\-]+)$' % BASE_URL), page_page,
['entry'])
wt.... |
from pygame import sprite
from pygame import font
from pygame.locals import *
import pygame
import random as rd
import ai
WINDOW = {
"WIDTH": 400,
"HEIGHT": 500
}
PANEL_A = {
"WIDTH": 400,
"HEIGHT": 100
}
PANEL_B = {
"WIDTH": 400,
"HEIGHT": 400,
"COLOR": (158, 158, 158)
}
BLOCK = {
"A"... |
import os
import sys
import xml.etree.ElementTree as ET
#xml_str='<xml><a id="10"><c><b>10</b></c></a><a id="20"><b>10</b></a></xml>'
xml_str=""
root=ET.fromstring(xml_str)
def add_attrib(data,temp):
for key in data.keys():
temp[key]=data[key]
return temp
def parse_xml(root):
d={}
for child in root:
if(len... |
def contacts(queries):
contactList = []
#
# Write your code here.
#
result = []
for query in queries:
if query[0] == 'add':
contactList.append(query[1])
if query[0] == 'find':
def filterGenerator(valueToFilter):
return lambda x : (x.find(qu... |
# -*- coding: utf-8 -*-
import datetime
from odoo import models, fields, api, tools, _
from odoo.exceptions import UserError, RedirectWarning, ValidationError
class trafitec_viaje_siniestrado.wizard(models.TransientModel):
_name = "trafitec.viaje.siniestrado.wizard"
_description = "Viaje Siniestrado Wizard"... |
# This concatenates all files that scraper has produces
# Run when command line in TextCompletion folder
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
import re
files = glob.glob('./scraper/threads/*.txt') # Assumes that in TextCompletion folder
def tsplit(string, delimiters):
"""Beha... |
from selenium import webdriver
import re
import time
webdriverpath='chromedriver.exe'
class Cfeiting(object):
"""docstring for Cfeiting"""
value = 4
def __init__(self, cookies,sessionID):
super(Cfeiting, self).__init__()
self.cookies = cookies
self.sessionID = sessionID
#线路一
... |
if __name__ == "__main__":
socks = list(map(int, input().strip().split()))
hip = min(socks)
maximum = max(socks)
maximum -= hip
maximum //= 2
print(hip, maximum)
|
import pytest
requests = pytest.importorskip("requests")
import utils
def setup_module(module):
utils.invoke('install', 'notebook')
@utils.remotetest
def test_salt_formulas():
project = utils.get_test_project()
kwargs = {'test': 'true', '--out': 'json', '--out-indent': '-1'}
out = project.salt('s... |
# Group 16
# Team members:
# Zenan Ji (Student ID: 1122396) - city: Nanjing
# Weijie Ye (Student ID: 1160818) - city: Fuzhou
# Wenqin Liu (Student ID: 807291) - city: Guangdong
# Jinhong Yong (Student ID: 1198833) - city: Kuala Lumpur
# Zixuan Zeng (Student ID: 1088297) - city: Melbourne
from cloudant.client imp... |
import paho.mqtt.client as mqttClient
import time
import json
import csv
import psycopg2
from datetime import datetime, timedelta
from pytz import timezone
import pytz
import requests
conn = psycopg2.connect(host="127.0.0.1", dbname="is614team9db", user="is614team9", password="password")
# Cursor is created by the Con... |
from django.contrib import admin
from Apps.Cni.models import *
# Register your models here.
admin.site.register(Profil) |
import sys
import tempfile
import hotshot
import hotshot.stats
from django.conf import settings
from cStringIO import StringIO
class ProfileMiddleware(object):
"""
Displays hotshot profiling for any view.
http://yoursite.com/yourview/?prof
Add the "prof" key to query string by appending ?prof (or &pro... |
#!/usr/bin/python3
# coding : utf-8
from openff.models import req_sql
class Category:
"""This class represents a category,
control and insert it into database
"""
def __init__(self, name, model):
"""This method initializes the class
:param name: category name
:param model: cur... |
# combine argv with raw_input function
from sys import argv
script, gates, zuck, steve = argv
print "This script is called:", script
print "Your gates variable is:", gates
print "Your zuck variable is:", zuck
print "Your steve variable is:", steve
fourth = raw_input("What is your fourth variable? ") |
import os
import numpy as np
import torch
import biotite.structure as struc
import biotite.structure.io as strucio
import biotite.application.dssp as dssp
from torch_geometric.data import Data
import config as cfg
def list2OHEdict(inList):
inLen = len(inList)
zeros = [0] * inLen
resDict = {... |
#!/usr/bin/env python3
# Inherit from the dictionary class
class DriverConfig(dict):
###############################################
def __init__(self, case, coupling_times):
###############################################
# this initializes the dictionary
super(DriverConfig,self).__init__... |
#<ImportSpecificModules>
import inspect
BaseModuleStr="ShareYourSystem.Standards.Objects.Debugger"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Tester")
#</ImportSpecificModules>
#<DefineLocals>
SYS.setSubModule(globals())
FunctingDecorationStr='Functer@'
#</DefineLocals>
#<DefineFunctions>
def getFuncte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.