text stringlengths 38 1.54M |
|---|
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django import forms
from accounts import validators as account_validators
from accounts.models import BOOL_CHOICES, OnlineDisclaimer, DISCLAIMER_TERMS, \
OVER_18_TERMS, MEDICAL_TREATMENT_TERMS
class SignupForm(forms.Form):
... |
"""
Django settings for benchmark project.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
#import djcelery
from environ import Path
from benchmark.utils.enviro... |
import cv2
import os
import sys
#カスケードの読み込み(from github/opencv/data)
cascade_file = './Cascade/haarcascade_frontalface_alt.xml'
cascade = cv2.CascadeClassifier(cascade_file)
def mosaic(img,rect,size):
(x1,y1,x2,y2) = rect
w = x2 - x1
h = y2 - y1
tmp_img = img[y1:y2,x1:x2]
i_small = cv2.resize(tmp... |
from django.contrib import admin
from django.urls import include,path
from profile.views import profile_form,update_profile,get_profile_data,return_profile_page
urlpatterns = [
path('<int:user_id>/edit/',profile_form,name="profile_form"),
path('update_profile/',update_profile,name="Update Profile"),
path('... |
"""
Reads in an entire file, removes extraneous whitespace, and returns the
data as an array of strings
"""
def ingestFile(fname):
print "Attempting to read" + fname
f = open(fname)
return [line.strip() for line in f.readlines() if len(line.strip()) > 0] # Get rid of all the extra whitespace
""" S... |
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
#reserve 'a' for all positions
k -= n
num = [0] * n
for i in range(n-1, -1, -1):
#assign 26-1 = 25 if it's min o
add = min(25, k)
num[i] = chr(ord('a') + add)
k -= add
... |
import shapely.geometry
class Feature:
def __init__(self, geometry: shapely.geometry.base.BaseGeometry, tags: dict = None):
"""
:type geometry: shapely.geometry.base
"""
assert isinstance(geometry, shapely.geometry.base.BaseGeometry)
self.geometry = geometry
if tags... |
"""Module tests functionalty in write.py"""
import unittest
from src.write import simple_writer, list_writer, writers, text_writer
from src.file_type import get_data_type
class TestWriteSimple(unittest.TestCase):
"""Tests functionality in the write.py module"""
def setUp(self) -> None:
self.sample_d... |
from ossConfig import ossConfig
import Oss
access_key = 'XXXXXXXXX'
secret_key = 'XXXXXXXXXXXXXXXXXXX'
endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'
config = ossConfig(access_key, secret_key, endpoint_url)
bucket_name = 'ddddd1'
# get_corsConfig
CORSConfiguration = Oss.get_bucket_cors(config, bucket_name)
if CORSCon... |
from mock.mock import Mock
from base import GAETestCase
from web import listar
from usuario.model import Usuario
import json
class RestTests(GAETestCase):
def test_listar(self):
usuario = Usuario(nome='teste', email='teste@teste.tst', google_id=123)
usuario.put()
usuarios = Usuario.... |
# Copyright 2021 Intel Corporation
#
# 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 agreed to in wr... |
import grpcapi.server.v1
from route_guide_pb2 import (
Point,
Feature,
Rectangle,
RouteNote,
RouteSummary,
)
import grpc
from concurrent.futures import ThreadPoolExecutor
from typing import Iterable
import logging
logging.basicConfig(level=logging.DEBUG)
app = grpcapi.server.v1.App()
@app.unary_... |
import time
class MemoryMetrics():
def __init__(self, percent, available, total, pc_id):
self._percent = percent
self._available = available
self._total = total
self._created_at = time.strftime('%Y-%m-%d')
self._hour_at = time.strftime('%H:%M:%S')
self._pc_id = pc_i... |
from random import seed
from random import random
f = open("List2.txt", "r")
y = f.read().rstrip().split(",")
d = list(map(int, y))
def main(x):
i = 0
while i < len(d):
if (x[i] == 1):
opcode1(x, i)
if (x[i] == 2):
opcode2(x, i)
if (x[i] == 99):
bre... |
from adder import adder
def multiplier(nb1, nb2):
result = 0
loop_count = 0
while nb2 != 0:
if nb2 % 2 == 1:
tmp_result = nb1 << loop_count
result = adder(result, tmp_result)
loop_count += 1
nb2 >>= 1
return result
|
import sys
from webbpsf_ext.logging_utils import setup_logging as setup_logging_wext
from . import conf
import logging
_log = logging.getLogger('pynrc')
_DISABLE_FILE_LOGGING_VALUE = 'none'
import warnings
warnings.filterwarnings('ignore')
### Helper routines for logging: ###
class FilterLevelRange(object):
... |
# coding: utf-8
"""
Xero Finance API
The Finance API is a collection of endpoints which customers can use in the course of a loan application, which may assist lenders to gain the confidence they need to provide capital. # noqa: E501
Contact: api@xero.com
Generated by: https://openapi-generator.tech... |
# -*- coding: utf-8 -*-
from pysped.xml_sped import *
#from soap_100 import SOAPEnvio, SOAPRetorno, conectar_servico
from pysped.nfe.manual_300 import ESQUEMA_ATUAL
import os
import random
DIRNAME = os.path.dirname(__file__)
class ISSQN(XMLNFe):
def __init__(self):
super(ISSQN, self).__init__()
... |
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self, data):
if data is None:
return
print(data)
self.datas.append(data)
pass
def output_html(self):
fout = open("formatter.html", "w")
fout.write("""
... |
# encoding=utf-8
from telebot import types
from module import CourseList, StartBot
from config import TOKEN
from app import server
bot = StartBot(server, TOKEN)
course = CourseList()
@bot.message_handler(commands=['start'])
def update_course(message):
bot.send_message(message.chat.id, 'Привет, ' + message.from_... |
import sys
import dlib
import cv2
import numpy as np
TEMPLATE = np.float32([
(0.0792396913815, 0.339223741112), (0.0829219487236, 0.456955367943),
(0.0967927109165, 0.575648016728), (0.122141515615, 0.691921601066),
(0.168687863544, 0.800341263616), (0.239789390707, 0.895732504778),
(0.325662452515, 0.9... |
from typing import Dict
from pydantic import BaseModel
class ProductoInDB(BaseModel):
codigo: str
nombre: str
precio: float
cantidad: int
seccion:str
database_producto = {
"1001": ProductoInDB(**{"codigo": "1001",
"nombre": "Mause",
"... |
"""Runtime Errors."""
def bad_type(item):
"""
(str) -> TypeError
Arguement must be a alpha string.
Attempts to convert a given word or string into an integer.
>>>bad_type('John')
Traceback (most recent call last):
File "<error_library.py>", line 36, in <bad_type>
T... |
#!/usr/bin/env python
PROJECT = 'clifford'
# Change docs/sphinx/conf.py too!
VERSION = '0.1'
from setuptools import setup, find_packages
try:
long_description = open('README.rst', 'rt').read()
except IOError:
long_description = ''
setup(
name=PROJECT,
version=VERSION,
description='Clifford, ec... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-26 18:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('registration', '0002_customuser_avatar'),
]
operations = [
migrations.Alter... |
# coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
class GoSpider(HackingTool):
TITLE = "Gospider"
DESCRIPTION = "Gospider - Fast web spider written in Go"
INSTALL_COMMANDS = ["sudo go get -u github.com/jaeles-project/gospider"]
PROJECT_URL = "https://github.com/jaeles... |
# -*- coding: utf-8 -*-
import wx
from docpage import DocPage
from settings import FILENAME_FONT, COMMENT_FONT
class DocListBox(wx.VListBox):
def __init__(self, parent, docs):
super(DocListBox, self).__init__(parent)
self.docs = docs
"""
@type : Document
"""
self.Se... |
#P1_A Write a program to store the elements in
1-D array and provide an option to perform
the operations like searching, sorting,
merging, reversing the elements.#
Code: searching
def linear_search(values, search_for):
search_at = 0
search_res = False
# Match the value with each data element
while s... |
__author__ = 'ayost'
import sys
def buildUpdate():
f = open("/home/.emails/updates.txt", "rb")
contents = f.read()
f.close()
contents = contents.replace("\n","<br />")
email = "<h2>Updates are available for your computer</h2><p>The following updates are available for your computer. You should log o... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dates = pd.date_range('20130101', periods=6)
print(dates)
df = pd.DataFrame(np.random.rand(6,4), index=dates, columns=list('ABCD'))
print(df)
|
#!/usr/bin/env python3
from pprint import pprint
from collections import deque, defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.buffer.readline
inf = float("inf")
n_item, w_volume = map(int, input().split())
weight, value = [], []
for _ in range(n_item):
w, v = map(int, input().split())
... |
import mxnet as mx
import numpy as np
import cv2
from vgg_mx.symbol_vgg import VGG
from caffe_io import Transformer
from collections import namedtuple
import symbol_sentiment
import config
ctx = [mx.cpu()] if len(config.gpus) == 0 else [mx.gpu(int(i)) for i in config.gpus.split(',')]
feature_names = ['object', 'scene... |
"""
Final exam, problem 3.
Authors: David Mutchler, Dave Fisher, Matt Boutell, their colleagues,
and Joshua Eckels.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
run_test_shape()
def run_test_shape():
""" Tests the shape ... |
from unittest import TestCase
from unittest.mock import patch
import io
from game import print_class_description
class TestPrintClassDescription(TestCase):
@patch('sys.stdout', new_callable=io.StringIO)
def test_print_squire_class(self, mock_output):
print_class_description("Squire")
actual ... |
from __future__ import print_function
def run():
input = open("input.txt", 'r')
lines = file.read(input)
abbas = 0
for line in lines.split("\n"):
if len(line) == 0:
continue
sliding_window = []
bracket_mod = False
abba_mod = False
try:
fo... |
import codecs
import json
import os
def getProjectPages(start=0, end=100, cache=False):
if not cache:
print 'WARNING: API queries not supported yet'
return []
basedir = os.path.dirname(__file__)
with codecs.open(os.path.join(basedir, 'config/medicine_dump.json'), encoding='utf-8') as jsonfile:
data = jso... |
a = [1, 1.2, 'sagar', True]
print(a)
print(a[0])
#print(a[4])
# access index using a[x]
a[0] = 'one'
print(a)
#list slicing
b = ["sagar", 13, 12, 1998, "neha", 30, 9, 1998]
print("sagar = ", b[1:4])
print("neha = ",b[5: ])
|
import networkx as nx
import rw
import numpy as np
subs=['S101','S102','S103','S104','S105','S106','S107','S108','S109','S110',
'S111','S112','S113','S114','S115','S116','S117','S118','S119','S120']
#subs=['S1','S2','S3','S4','S5','S7','S8','S9','S10','S11','S12','S13']
toydata=rw.Toydata({
'numx': 3,
... |
''' Faça um programa que calcule a soma entre todos os números impares que são múltiplos de três e que se
encontram no intervalo de 1 até 500. '''
soma = 0
conta = 0
for count in range(1, 501, 2):
if count % 3 == 0:
conta += 1
soma += count
print('A soma de todos os valores {} solicitados é {}'.for... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
#This program is to find next greater number from a given number
"""
Input: n='231'
Output: 'next greater value=321'
"""
#NOTE: Using permutations will not give you efficient time complexity if number will be too large
from itertools import permutations
import time
n='231'
#Start and end will give you actual time the p... |
# -*- coding: utf-8 -*-
"""
Created on 2020-03-10
@author: duytinvo
Copy from HuggingFace examples and adapt with NNlib
Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa).
GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fin... |
import numpy as np
import cv2
from scipy.spatial import distance
import math
import os
def distpp(p1, p2):
'''Méthode rendant la distance entre les deux points entrés en paramètres'''
return math.hypot(p2[0] - p1[0], p2[1] - p1[1])
def findangle(datas, w, h, qdens):
'''Méthode grossière pour trouver les... |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
from tkinter import *
from tkinter import messagebox
import nltk
from nltk.corpus import words
from time import gmtime, strftime
import time
from collections import Counter
nltk.download('words')
word_list = words.words()
Matrix_list = ['a', 'r', 'b', 'z', 't', 'n', 'd', 'h', 'm',
'v', 's', 'x', 'l', 'u... |
import pandas as pd
import os
import matplotlib.pyplot as plt
datasets = ['cifar10_binary', 'stl10_binary']
for dataset in datasets:
log_path = f'logs/{dataset}'
title = ['step_size', 'iters', 'batch_size', 'intervals', 'pool_size']
params = [
(0.05, 0.1, 0.2, 0.3, 0.4, 0.5),
(500, 1000,... |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
# 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 agreed... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
from graficas.models import Empresa, GrafanaData, GrafanaDashBoards
class EmpresaAdmin(admin.ModelAdmin):
model = Empresa
search_fields = ('nombre', 'slug')
list_display = ('nomb... |
################################################################################
#
# Copyright (c) 2017 University of Oxford
# Authors:
# Geoff Pascoe (gmp@robots.ox.ac.uk)
#
# This work is licensed under the Creative Commons
# Attribution-NonCommercial-ShareAlike 4.0 International License.
# To view a copy of this li... |
#!/usr/bin/env python3
# sutimar pengpinij
# 590510137
# Lab 05
# Problem 5
# 204111 Sec 003
def main():
year = int(input(""))
print(zodiac_element(year))
def zodiac_element(year):
zodiac = year%12
element = year%10
if element == 0 or element == 1:
ans = "Metal"
elif el... |
import pandas as pd
df1 = pd.read_csv('/home/vade1057/solar-flares/code/topology/geometry/results/merged.csv')
df2 = pd.read_csv('/home/vade1057/solar-flares/code/topology/cubical_complexes/results/cubical_complexes_320K/cubical_complexes_440K_debug.csv')
print(df1.columns)
print(df2.columns)
df1['merge_label'] =... |
# coding: utf-8
import os
import sys
import ssl
import time
import socket
from urllib.request import urlopen, Request
def get_dirname(path):
return os.path.dirname(os.path.realpath(path))
file_dir = get_dirname(__file__)
root_dir = os.path.dirname(file_dir)
py_dir = os.path.join(root_dir, 'python')
icon_gotox = ... |
"""
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: 2.py
Автор: 2020 © Д.П. Юткина, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 11/11/2020
Дата последней модификации: 11/11/2020
Связанные файлы/пакеты: min, max
Описание: Решение ... |
import sys, boto3
args = sys.argv
if __name__ == "__main__":
fileName=args[1]
bucket='pakuty-mujin-backet'
client=boto3.client('rekognition','us-east-2')
response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':fileName}})
print('Detected labels for ' + fileName)
for label ... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 o... |
import reports
# Export functions
result1 = reports.get_most_played('game_stat.txt')
result2 = reports.sum_sold('game_stat.txt')
result3 = reports.get_selling_avg('game_stat.txt')
result4 = reports.count_longest_title('game_stat.txt')
result5 = reports.get_date_avg('game_stat.txt')
result6 = reports.get_game('game_stat... |
from torch.utils.data import Dataset
import os
from PIL import Image
class LSUNImageDataset(Dataset):
def __init__(self,img_dir,dir_size=1000,transform=None):
self.img_dir = img_dir
self.dir_size = dir_size
self.transform = transform
subdirs = os.listdir(self.img_dir)
... |
import pandas as pd
import matplotlib.pyplot as plt
df_schema = pd.read_csv('survey_results_schema.csv')
df_public = pd.read_csv('survey_results_public.csv',
usecols=['Respondent', 'YearsCodePro',
'WorkWeekHrs', 'Gender'],
index_co... |
"""
app0.py illustrates use of pitaxcalc-demo release 2.0.0 (India version).
USAGE: python app0.py > app0.res
CHECK: Use your favorite Windows diff utility to confirm that app0.res is
the same as the app0.out file that is in the repository.
"""
from taxcalc import *
# create Records object containing pit.csv an... |
# Name:
# Date:
# proj01: A Simple Program
# This program asks the user for his/her name and age.
# Then, it prints a sentence that says when the user will turn 100.
# If you complete extensions, describe your extensions here!
name = raw_input("Enter your name: ")
age = int(raw_input("Enter your age: "))
birthday = ... |
from server.util import Plugin
# Reloads the Python scripts
def admin_command_reloadscripts(player, playerCommand):
Plugin.load(); |
'''
题目描述
统计一个数字在排序数组中出现的次数。
'''
# -*- coding:utf-8 -*-
class Solution:
#用双指针比较快,注意处理好特殊情况即可
def GetNumberOfK(self, data, k):
# write code here
right = len(data) - 1
left = 0
while left <= right:
if data[left] == k and data[right] == k:
break
... |
import os
import datetime, pytz
import pandas as pd
import capnp
from scipy.optimize import curve_fit
from datetime import datetime, timedelta
from xbos import get_client
from xbos.services.mdal import *
from xbos.services.pundat import DataClient, make_dataframe
from xbos.services.hod import HodClient
from sklearn.uti... |
import math
import numpy as np
from config import Config
from core.logger import TensorBoardLogger
from core.util import get_output_folder
class Trainer:
def __init__(self, agent, env, config: Config):
self.agent = agent
self.env = env
self.config = config
self.outputdir = get_outp... |
from kafka import KafkaConsumer
# To consume latest messages and auto-commit offsets
consumer = KafkaConsumer('my-topic',
group_id='my-group',
bootstrap_servers=['localhost:9092'])
for message in consumer:
# message value and key are raw bytes -- decode if necessary... |
class StatusBytes:
"""Enumerating of status bytes with corresponding event types
"""
meta = {0: 'Sequence Number', 1: 'Text', 2: 'Copyright', 3: 'Sequence / Track Name', 4: 'Instrument Name',
5: 'Lyric', 6: 'Marker', 7: 'Cue Point', 8: 'Program Name', 9: 'Device Name', 32: 'MIDI Channel Prefix',... |
from django.shortcuts import render
from django.template.loader import get_template
def main(request):
return render(request, 'index.html', {})
|
#!/usr/bin/env python
# coding: utf-8
import json
from sklearn_crfsuite import CRF
import numpy as np
from scipy.stats import entropy
from nltk import word_tokenize, pos_tag
import random
import pickle
import os
from bs4 import BeautifulSoup
from bs4 import Tag
from collections import Counter
from flask import Flask... |
import pandas as pd
import numpy as np
import re
from sklearn.preprocessing import MultiLabelBinarizer
our_features = ['budget', 'vote_count', 'runtime', 'Year', 'Friday', 'Monday', 'Saturday',
'Sunday', 'Thursday', 'Tuesday', 'Wednesday', '20th Century Fox',
'Columbia Pictures', 'Metro... |
from flask import Flask, session, g, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect,generate_csrf
from redis import StrictRedis
from flask_session import Session
from config import config_dict
import logging
from logging.handlers import RotatingFileHandler
from info.util... |
"""
Think Python
Exercise 9.2
Sol by : Nitin Kumar
Date 14 June 2009
Note : In 1939 Ernest Vincent Wright published a 50,000 word novel called Gadsby that does
not contain the letter “e.” Since “e” is the most common letter in English, that’s not easy to do.
In fact, it is difficult to construct a solitary thought wi... |
import sys, os
# path = os.path.abspath(os.path.join('..'))
# sys.path.append(path)
from feature import *
from lr import *
from tqdm import tqdm
import matplotlib.pyplot as plt
from scipy.sparse import csr_matrix
train_in = "./handout/largedata/train_data.tsv"
val_in = "./handout/largedata/valid_data.tsv"
test_in = ".... |
#!/usr/bin/env python
import simplejson
import unittest
from table import ColumnQuery, JunctionQuery, MultiJunctionQuery, NotQuery
class JsonParser:
JUNCTION_OP_MAP = {
'and': JunctionQuery.OP_AND,
'or': JunctionQuery.OP_OR
}
COLUMN_OP_MAP = {
'=': ColumnQuery.TYPE_EQ,
... |
## change these paths accordingly
background_image_fp = 'background.jpg'
sprite_image_fp = 'ornament.png'
import pygame
from pygame.locals import *
from sys import exit
import time
pygame.init()
screen = pygame.display.set_mode((200, 200), HWSURFACE | DOUBLEBUF, 32)
pygame.display.set_caption("Horizontal Spraight M... |
import cv2
import os
import numpy as np
import pointImg
import skeletonization
class data_generation():
def __init__(self, raw_img):
self.raw_img = raw_img
def get_data(self, tag):
sk = skeletonization.skeletonization(self.raw_img)
skeleton_img = sk.get_skeleton().ast... |
"""
"""
import math
"""
"""
def box_area( box=None ):
return ( box[2] - box[0] ) * ( box[3] - box[1] )
"""
"""
def box_overlap_area( box1, box2 ):
x_overlap, y_overlap = (
max( 0, min( box1[2], box2[2] ) - max( box1[0], box2[0] ) ),
max( 0, min( box1[3], box2[3] ) - max( box1[1], box2[1] )... |
class Film:
bubble_sort_comparison_counter = 0
bubble_sort_swap_counter = 0
heap_sort_comparison_counter = 0
heap_sort_swap_counter = 0
def __init__(self, name, runtime_in_min, num_of_responses):
self.name = name
self.runtime_in_min = runtime_in_min
self.num_of_responses = n... |
# Generated by Django 2.0 on 2017-12-25 20:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Branch',
fields=[
... |
#!/usr/bin/env python
__version__ = "20190114"
__author__ = "Decaff_42"
__copyright__ = "2019 by Decaff_42"
__license__ = """Only non-comercial use with attribution is allowed without
prior written permission from Decaff_42."""
import os
import re
def get_dats(ysfpath, airplanes):
"""Get the DAT contents for e... |
# -*- coding: utf-8 -*-
import glob, sys, os, re, string, time, random, dateparser
from dateparser.search import search_dates
#!/usr/sfw/bin/python
"""
dateparser_export_to_BIEO_format, a script to call dateparser on
sentences in French and export the result to the BIEO format
(Beginning / Inside /... |
import csv
import requests
with open('Test.csv') as filestream:
for line in filestream:
currentline = line.split(",")
print(currentline[0])
url="https://test.com/test/test/{0}".format(currentline[0])
print(url)
print(requests.delete(url))
|
def count_holes(n):
c = 0
nums = ['0', '4', '6', '9']
if isinstance(n, int):
for i in str(n):
if i in nums:
c += 1
elif i == '8':
c += 2
return c
elif isinstance(n, float):
return 'ERROR'
else:
return 0
print(count_holes('123'))
print(count_holes(906))
print(count_holes('001'))
print(count_h... |
import pygame
import random
import constants
from Player import *
from Bullet import *
from platforms import *
from Level import *
from Level_01 import *
def main():
pygame.init()
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Witches!!")
... |
from django.contrib import messages
from decouple import config
from pathlib import Path
import os
import django_heroku
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See ht... |
from turtle import*
color("green", "yellow")
speed(-1)
for i in range(6):
circle(100)
lt(60)
mainloop() |
from factories import loader
for factory_name in 'jeep_factory', 'NotExist':
factory = loader.load_factory(factory_name)
car = factory.create_auto()
car.start()
car.stop() |
# Importing Libraries
import matplotlib.pyplot as plt
import pandas as pd
# Importing the Dataset
dataset = pd.read_csv("Real estate.csv")
# Taking variables x1 to x5 as shown by RMSE
X = dataset.iloc[:, 1:-2].values
y = dataset.iloc[:, 2].values
# Encoding the dataset accordingly
from sklearn.preprocessin... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 1 17:11:46 2019
@author: Jonathan
"""
import numpy as np
import matplotlib.pyplot as plt
import math
import sys
import os
import pathlib
import pywt
from scipy import optimize
from pylab import rcParams
'''Setting the global figure size'''
rcParams['f... |
import requests
from sqlalchemy import create_engine
from api import basepay
engine = create_engine("mysql+pymysql://root:root@localhost:3306/vpc", echo=True)
conn = engine.connect()
class DeductRequest(basepay.BasePay):
def psrseParam(self):
pass
def request(self):
#根据接口获取对应的url
url... |
from wandb_gql import gql
UPSERT_VIEW = gql(
"""
mutation upsertView(
$id: ID
$entityName: String
$projectName: String
$type: String
$name: String
$displayName: String
$description: String
$spec: String!
) {
upsertView(
input: ... |
from ..db.models import Datum, TestDatum, Action, ActionType
def test_can_create_test(client, user, test_dict):
assert len(user.tests) == 0
resp = client.post('/tests', headers=user.auth_headers, json=test_dict)
assert 'created_at' in resp
assert 'id' in resp
assert set(resp['data'].keys()) == set... |
import tensorflow as tf
import numpy as np
class CNN8class(object):
def __init__(self, dense_units=8, name="cnn", sess=None):
self.name=name
self.dense_units = dense_units
with tf.variable_scope(self.name):
self.x = tf.placeholder("float", shape=[None, 105])
... |
# Based on Numerical Recipes
import numpy
from scipy.linalg import solve_banded
import pdb
def splint(spl, x):
npts = len(spl.x)
lo = numpy.searchsorted(spl.x, x)-1
lo = numpy.clip(lo, 0, npts-2)
hi = lo + 1
dx = spl.x[hi] - spl.x[lo]
a = (spl.x[hi] - x)/dx
b = (x-spl.x[lo])/dx
y = (a*s... |
from pyspark.ml.fpm import FPGrowth
from pyspark.sql import Row
from pyspark.sql import SparkSession
import pandas as pd
TRANSACTIONS = [
["a", "b", "c", "d"],
["a", "b", "d", "e"],
["b", "d", "e"]
]
MAX_MEMORY = "8g"
class AR(object):
def __init__(self, transactions):
self.result = self.ar... |
import tensorflow as tf
def convstack_generator(
net, depth=8, channels=32, dropout=False, norm='instance'
):
'''At hand! quoth Pickpurse.
In the generator, each residual module consists of two 3d
convolutions with (3, 3, 3) kernels, 32 feature maps, operating in
VALID mode, with the ReLU activat... |
from tkinter import *
from tkinter import messagebox
import sqlite3
import turtle
import random
window = Tk()
window.title("아마추어를 위한 타구 분석 프로그램")
window.geometry("1040x500")
window.resizable(False, False)
mainMenu = Menu(window)
window.config(menu = mainMenu, background="linen")
#야구장 이미지 사진
photo = PhotoImage(file ... |
"""
"""
import os
import sys
class SubProcess:
def __init__(self, core, **kwargs):
print(self.__class__.__name__)
self.core = core
self.ill_run = core.ill_run
self.dir_input = core.dir_input
self.dir_output = core.dir_output
self.first_snap_with_bhs = core.first_... |
#!/usr/bin/env python
# Author: Ryan Balsdon <ryanbalsdon@gmail.com>
#
# I dedicate any and all copyright interest in this software to the
# public domain. I make this dedication for the benefit of the public at
# large and to the detriment of my heirs and successors. I intend this
# dedication to be an overt act of r... |
def failTable(pattern):
# Create the resulting table, which for length zero is None.
result = [None]
# Iterate across the rest of the characters, filling in the values for the
# rest of the table.
for i in range(0, len(pattern)):
# Keep track of the size of the subproblem we're dealing with... |
#In this program you have to input an audio speech file and the api will transcribe the speech to text
#The output will be printed in text
#IMPORTANT : You will have to convert your .p3 file into .flac
#You can use this link for conversion of .mp3 to .flac --- "ttps://audio.online-convert.com/convert-to-flac"
import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.