text stringlengths 8 6.05M |
|---|
class SimpleArithmetic:
def simple_add(x,y):
print(x+y)
def simple_subtract(x,y):
print(x-y)
def simple_multiply(x,y):
print(x*y)
def simple_divide(x,y):
print(x/y)
def floor_divide(x,y):
#the double-slash operator performs division and then rounds the result down to the next-lowest integer
#this ... |
# encoding: utf-8
#@author: newdream_daliu QQ:279129436
#@file: aaa.py.py
#@time: 2021-05-05 18:13
#@desc:
print('test01')
print('test02')
print('test04')
print('test05')
print('test06') |
#!/usr/bin/python
import torch
def prepare_data(train_path, max_len=20):
print('Loading data...')
# read sents and get vocab
sents = []
vocab = {'<UNK>': 0, '<pad>': 1}
i = len(vocab)
with open(train_path) as... |
import json
import shapely.wkb
import tile_gen.util as u
import tile_gen.vectiles.mvt as mvt
import tile_gen.vectiles.geojson as geojson
from tile_gen.geography import SphericalMercator
from ModestMaps.Core import Coordinate
from StringIO import StringIO
from math import pi
from psycopg2.extras import RealDictCursor
fr... |
import csv
import pickle
import string
from nltk.corpus import wordnet as wn
#this script is intended to be run from the python command line
def save_senti_data():
#read SentiWordNet data file to get list of positive and negative sentiment polarities for each word with a given part of speech
senti_file = ope... |
# import blender gamengine modules
from bge import logic
from .settings import *
from . import bgui
import logging
allowDuplicate = True
class Logger:
"""Message logger singleton"""
def __init__(self, widget):
self.bigList = []
self.panel = widget
# init secondary UI elements
self.logger1 = bgui.Label(sel... |
import robots
AGENT = "test_robotparser"
parser = robots.RobotsParser.from_file("robots.txt")
if parser.errors:
print("ERRORS:")
print(parser.errors)
if parser.errors:
print("WARNINGS:")
print(parser.errors)
assert parser.can_fetch(AGENT, "/tmp")
assert not parser.can_fetch(AGENT, "/tmp/")
assert n... |
#034: Error Correction in Reads
#http://rosalind.info/problems/corr/
#Given: A collection of up to 1000 reads of equal length (at most 50 bp) in FASTA format. Some of these reads were generated with a single-nucleotide error. For each read s in the dataset, one of the following applies:
titles = ['>Rosalind_52', '>Ro... |
from ffl import app, db, models, espn, nfl, shark
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
import csv
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def delete_data():
db.session.execute(models.playerPosition.... |
"""
"""
class Solution(object):
def pivotIndexSol(self, nums):
pivot = -1
length = len(nums)
if length == 0: return pivot
i, leftSum, rightSum = 1, [0 for _ in range(length)], [0 for _ in range(length)]
leftSum[0] = nums[0]
rightSum[length - 1] = nums[length - 1]
... |
# https://leetcode.com/problems/string-compression/?envType=study-plan-v2&envId=leetcode-75
class Solution:
def compress(self, chars: List[str]) -> int:
res = ""
count = 1
c = chars[0]
for ndx in range(1, len(chars)):
if c == chars[ndx]:
count += 1
... |
__author__ = 'joshgenao'
import cv2
import numpy as np
from matplotlib import pyplot as plt
def FlannMatcher(queryImage, image):
MIN_MATCH_COUNT = 10
img1 = cv2.imread(queryImage,0) # queryImage
img2 = cv2.imread(image,0) # trainImage
# Initiate SIFT detector
sift = cv2.SIFT(... |
from django.db import models
from django.contrib.auth import get_user_model
from django.core.validators import MinValueValidator,MaxValueValidator
import datetime
# Create your models here.
User=get_user_model()
class Doctor(models.Model):
#identificador=models.IntegerField(default=2)
dni= models.IntegerField... |
"""
LeetCode - Easy
"""
class Solution:
def intersect(self, nums1, nums2):
dict_int_1 = dict()
dict_int_2 = dict()
index_1 = 0
index_2 = 0
flag = True
while flag == True:
if index_1 != len(nums1):
if nums1[index_1] in dict_int_1:
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^register$', views.register),
url(r'^login$', views.login),
url(r'^dashboard$', views.dashboard),
url(r'^submit$', views.submit),
url(r'^add/(?P<quoteid>\d+)$', views.add),
url(r'^remove/(?P... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import struct
import os
import json
from .protocol import Message, PayloadItem, parse_messages_json_folder
from .protocol import ProtocolPayload, message
from .protocol import DefaultPluginMessagePayload, plugin_message
from .protocol import MessageID
def handle_undefined_message(*args):
pass
def handle_undefined... |
from collections import defaultdict
from fs import path
from fs.subfs import SubFS
from fs.copy import copy_dir
from fs.copy import copy_file
from fs.zipfs import WriteZipFS
from fs.tempfs import TempFS
from fs.osfs import OSFS
from fs.errors import NoSysPath
from sqlalchemy import desc
from onegov.core.csv import con... |
import sys
sys.path.append("../")
from src import verbalGraphGenerator
import random
from src import logger
import logging
import uuid
from src import utils
from src import constants
import argparse
import codecs
import os
import time
import pdb
from tqdm import tqdm
cur_Intents_String = ""
class controller:
de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 15 15:55:01 2017
@author: brian Cechmanek
Implementation of a classifier Perceptron from scratch. with extensive/excessive documentation
We'll later use it for exploration of the Iris data set.
"""
import numpy as np # this is to drastically speed... |
from django.forms import ModelForm
from .models import Post, Comment, Like
from datetime import datetime
class PostForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['author'].widget.attrs.update({'class': 'form-control'})
self.fields['titl... |
import csv as csv
import numpy as np
# Read the file
csv_file = csv.reader(open('train.csv', 'rb'))
header = csv_file.next()
data = []
for line in csv_file:
data.append(line)
data = np.array(data)
|
#Copyright (C) Practica Ana Sollars & Co.
#Permission is granted to copy, distribute and/or modify this document
#under the terms of the GNU Free Documentation License, Version 1.3
#or any later version published by the Free Software Foundation;
#with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Text... |
#!/usr/bin/env python
"""
Provides functionality to crawl and extract news articles from a single WARC file from commoncrawl.org. Filter criteria, such as publish date
and host list, can be defined. Currently, the WARC file will be downloaded to the path WORKINGDIR/cc_download_warc, if
not otherwise specified.
"""
impo... |
# import sys
# input = sys.stdin.readline
#A1 ~ Aiまでの和 O(logN)
#A1 ~ Aiまでの和 O(logN)
# def BIT_query(BIT,idx):
# res_sum = 0
# if idx == 0:
# return 0
# while idx > 0:
# res_sum += BIT[idx]
# idx -= idx&(-idx)
# return res_sum
# #Ai += x O(logN)
# def BIT_update(BIT,idx,x,n):
# ... |
import random
n = 50
print n
xs = []
for ix in range(n):
xs.append(random.randrange(10))
print ' '.join(map(str, xs))
print n
for ix in range(n):
x = random.randrange(1, n + 1)
y = random.randrange(1, n + 1)
print min(x, y), max(x, y)
|
# 8-queens Problem
def make_board() :
d={}
for col in range(0,8) :
for row in range(0, 8) :
d[col, row] = 0
return d
#print(d)
def show_board(d) :
for row in range(0,8) :
print(d[(0,row)],d[(1,row)],d[(2,row)],d[(3,row)],d[(4,row)],d[(5,row)],d[(6,row)],d[(7,row)] )
de... |
from catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from ... |
import numpy as np
import cv2
cap=cv2.VideoCapture('video.mp4')
fgbg=cv2.createBackgroundSubtractorMOG2()
while True:
ret,frame=cap.read()
fgmask=fgbg.apply(frame)
cv2.imshow('fgmask',fgmask)
cv2.imshow('orjinal',frame)
k=cv2.waitKey(25) &0xff
if k==27:
break
cap.release(... |
from django.db import models
from django_extmodels.manager import ExtManager
from django_extmodels.options import ExtOptions
from django_extmodels.settings import ext_settings
META_CLASS_NAME = ext_settings['META_NAME']
META_ATTR_NAME = ext_settings['META_ATTR']
class ExtModelBase(models.base.ModelBase):
def __new... |
from collections.abc import Callable
from inspect import FullArgSpec
from typing import Any, TypeVar
from typing_extensions import ParamSpec
_T = TypeVar('_T')
_P = ParamSpec('_P')
def arginfo(callable: Callable[..., Any]) -> FullArgSpec: ...
def is_cached(callable: Callable[..., Any]) -> bool: ...
def get_callable_i... |
import os, sys, time
# force run on CPU?
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
caffe_root = os.path.dirname(os.path.abspath(__file__))+'/../../'
sys.path.insert(0, caffe_root+'python')
#os.environ['GLOG_minloglevel'] = '2'
import numpy as np
np.set_printoptions(linewidth=200)
import cv2
import caffe
if not os.p... |
import numpy as np
import adios2 as ad
import io
from PIL import Image
from ast import literal_eval as make_tuple
#Given a writable opened adios file (returned by adios2.open), image data of the form used by PIL (or corresponding numpy array), and variable name, write the image to the adios file.
def write_image_hl (... |
from question1 import clearConsole,bcolors
from stackclass import stack
from stackclasswithLL import stack as LLstack
isStackWithLL= False ## True : Implementation with linked list stack | False : ##Implementation with array stack
def run(isstackWithLL):
global isStackWithLL
isStackWithLL = isstackWithLL
... |
import os
from configparser import ConfigParser
""" This file simply loads and store all information needed for the bot. """
# Reading Config File
config = ConfigParser()
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
CONFIG_PATH = os.path.join(PROJECT_ROOT, 'credentials.ini')
config.read(CONFIG_PATH)
# B... |
import sys
import os
TMP = "/tmp/demacro"
os.system("mkdir -p %s" %TMP)
arg = sys.argv[1]
if ".tex" in arg:
file_root_name = arg[0:-4]
elif arg[-1] == ".":
file_root_name = arg[0:-1]
else:
file_root_name = arg
current_dir = os.getcwd()
preamble = ""
doc_started = False
with open("%s.tex" %file_root_name) as f, o... |
'''
server.py
---------
v-1.0.0
It is a basic web server built to be used for development and debugging,
it is not intended for production use!
'''
import socket
# Handling the request so that we can serve the response
def handle_request(request):
"""Handles HTTP requests"""
# I will add the code later on... |
liste = [5,8,7,3,2,4,6,1]
for i in range(len(liste)):
val = liste[i]
j = i
while j > 0 and liste[j - 1] > val:
liste[j] = liste[j-1]
j -= 1
liste[j] = val
print(liste) |
from django.apps import AppConfig
class LugdunumConfig(AppConfig):
name = 'Lugdunum'
|
class Solution(object):
def gameOfLife(self, board):
if len(board) == 0 or len(board[0]) == 0: return
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
nnb = self.findLiveNeighbor(board, i, j)
if board[i][j] == 0 or board[i][j]... |
from itertools import izip
from copy import deepcopy
import socket
import re
def is_bool(obj):
return isinstance(obj, bool) and not isinstance(obj, int)
def dict_to_dictlist(d):
return [{k: v} for k, v in d.items()]
def dictlist_to_dict(l):
res = {}
for d in l:
if len(d) != 1:
rai... |
import xlwt
import xlrd
import names
from random import randint
from firesdk.user_classes.users import XLSUser
def generate_users(number_of_users):
first_names = []
last_names = []
for _ in range(number_of_users):
first_names.append(names.get_first_name())
last_names.append(names.get_las... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 5 21:30:56 2016
@author: sautt
"""
import matplotlib.pyplot as plt
import numpy as np
load = []
disp = []
with open("load.txt", "r") as fol:
for line in fol:
load.append(abs(float(line)))
fol.close()
with open("displacement.txt", "r") as fod:
for line i... |
import consus
c = consus.Client()
t = c.begin_transaction()
assert t.put('the table', 'the key', 'the value')
t.commit()
|
import base64
import io
import csv
import json
import os
import shutil
import glob
import cv2
import numpy as np
from datetime import datetime
from PIL import Image
from flask import render_template, url_for, request, redirect, Blueprint, session
from libs.utils import (
app_dir,
touch,
)
from collections ... |
#!/home/zain101/Documents/Django_Stuff/polls/polls_venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'PyJWT==1.4.0','console_scripts','jwt'
__requires__ = 'PyJWT==1.4.0'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('PyJWT==1.4.0', 'console_scripts',... |
from onegov.core import Framework
from onegov.quill import QuillField
from pytest import fixture
from pytest_localserver.http import WSGIServer
from tests.shared.utils import create_app
from wtforms import Form
from onegov.quill import QuillApp
@fixture(scope='function')
def quill_app(request):
class QuillTestAp... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/', views.user_login),
url(r'^logout/', views.logout),
url(r'^register/', views.register),
url(r'^order/', views.order),
url(r'^order1/', views.order1),
] |
# Generated by Django 2.2.11 on 2020-06-07 20:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pokryvala', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='pokryvala',
options={'verbose_name': 'Пок... |
"""狄克斯特拉算法的Python实现
这里用了换钢琴的例子
"""
# 首先构建这个图
def generate_graph():
# 图
graph = {}
# 记录边的权重
graph['score'] = {}
graph['score']['poster'] = 0 # 乐谱换海报
graph['score']['disc'] = 5 # 乐谱换唱片
graph['disc'] = {}
graph['disc']['guitar'] = 15 # 唱片换吉他
graph['disc']['drum'] = 20 # 唱片换架子鼓
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# informe_final.py
#%% ejercicio 7.7
import fileparse
def leer_camion(nombre_archivo):
'''Computa el precio total del camion (cajones * precio) de un archivo'''
with open(nombre_archivo) as f:
camion = fileparse.parse_csv(f, select = ['nombre', 'cajones'... |
# que https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/solution/
# solution 1
def findDisappearedNumbers(arr):
n = len(arr)
arr = list(set(arr))
for i in range(1, n+1):
if(i in arr):
arr.remove(i)
else:
arr.append(i)
return arr
print(find... |
#!/usr/local/bin/python3
#-*-coding:utf-8 -*-
############### FONCTION ###############
#le but de ce script est d'effectuer des opérations sur des courbes; elle permet de soustraire
#à un .dat, un autre .dat pour s'affranchir des certain phénomènes parasites de fond
############### VERSION 1 ###############
#version... |
from rest_framework import serializers
from accounts.serializers import UserSerializer
class SubmissionSerializer(serializers.Serializer):
id = serializers.IntegerField()
grade = serializers.IntegerField()
repo = serializers.CharField()
user_id = serializers.IntegerField()
activity_id = serializers... |
'''
merge all file in the folder data/name match/json/
in a single json file in data/name match/
filter and create two files one for home_team an one for away_team
with the separete events
'''
import os
import json
events = []
events_home_team = []
events_away_team = []
count = 0
count_home = 0
count_away = 0
fil... |
# -*- coding:utf-8 -*-
"""
求出1~13的整数中1出现的次数,并算出100~1300的整数中1
出现的次数?为此他特别数了一下1~13中包含1的数字有1、
10、11、12、13因此共出现6次,但是对于后面问题他就没
辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很
快的求出任意非负整数区间中1出现的次数(从1 到 n 中1
出现的次数)。
"""
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
countSum = 0
for ... |
import copy
import base64
import random
import string
import xml.etree.ElementTree as ET
import os
import json
from uuid import uuid4
import zipfile, os
from collections import OrderedDict
import shutil
def get_zip_file(input_path, result):
"""
对目录进行深度优先遍历
:param input_path:
:param result:
:return... |
"""
Given values for various macronutrients in grams, determine the number of
food points represented.
"""
def calculate_food_points(protein=0.0,
carbs=0.0,
fat=0.0,
fiber=0.0,
alcohol=0.0,
... |
from bs4 import BeautifulSoup
import requests
source = requests.get('https://www.flipkart.com').text
soup = BeautifulSoup(source, 'lxml')
itemName = []
itemDicount = []
for nameofitem in soup.find_all('div', class_='iUmrbN'):
textnameofitem = nameofitem.text
itemName.append(textnameofitem)
for discount in so... |
from django.apps import AppConfig
class OnmyojiModelsConfig(AppConfig):
name = 'onmyoji_models'
|
from bibliopixel.animation import BaseMatrixAnim
from bibliopixel import colors
from websocket import create_connection
import threading
import numpy as np
import PIL
from PIL import Image
import cv2
WS_FRAME_WIDTH = 640
WS_FRAME_HEIGHT = 480
WS_FRAME_SIZE = WS_FRAME_WIDTH * WS_FRAME_HEIGHT
def clamp(v, ... |
#!/usr/bin/python
"""
+-----------------------------------------------------------------------+
| This is an ETL process which extracts invoice line data from the Xero|
| finance application and stages it into S3 before loading into the |
| Redshift data Warehouse. |
| |
| The ove... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python3
import config
#from time import time
import time
import telebot
from telebot import types
import requests
from aiohttp import web
import ssl
bot = telebot.TeleBot(config.TOKEN)
@bot.message_handler(commands=['start']) # работает
def handler_start(message):
user_... |
"""
Storing model data in the database
FIXME: Most of this has nothing to do with database storage, but rather manipulating
pandas DataFrames. Move/rename so as not to imply anything I/O related
"""
import logging
from typing import List
import pandas as pd
import yaml
from summer.model import CompartmentalModel
fr... |
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
from allauth.socialaccount import app_settings
class PinterestAccount(ProviderAccount):
def get_profile_url(self):
return ... |
# Osuran Uzaylilar
def run():
# importing required modules
from sys import exit
from random import randint
from textwrap import dedent
class Death:
quips = ["Ben olsam daha iyi oynardım",
"Bir daha dene şansını",
"Sen oynayamıyorsun"]
def enter... |
# Generated by Django 2.0.6 on 2019-09-04 12:08
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AuthGroup',
fields=[
('id', models.AutoFiel... |
"""
#------------------------------------------------------------------------------
# simple_crane_trapezoidal.py
#
# Generate a simple crane model to compare feedback control and input shaping methods
# I hope to use this in a jupyter notebook to serve as a tutorial on input shaping
#
# Created: 1/30/18 - Daniel Newma... |
import math
import pyproj
coords = [
(37.4001100556, -79.1539111111, 208.38),
(37.3996955278, -79.153841, 208.48),
(37.3992233889, -79.15425175, 208.18),
(37.3989114167, -79.1532775833, 208.48),
(37.3993285556, -79.1533773333, 208.28),
(37.3992801667, -79.1537883611, 208.38),
(37.399244111... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from emailr.settings.config import DB_USERNAME, DB_PASSWORD, DB_ENDPOINT, \
DB_DATABASE
'''Database model for the application.'''
# The code below was mostly copied... |
# -*- coding: utf-8 -*-
"""
S3: some wrong functions on binarytrees
"""
from algopy import bintree
def searchBST(x, B):
if B == None:
return None
elif x == B.key:
return B
else:
if x < B.key:
searchBST(x, B.left)
else:
searchBST(x, B.right)
def inse... |
# Script to web scrape vulnerability information into mongodb
from bs4 import BeautifulSoup
from pymongo import MongoClient
from urllib.request import Request, urlopen
import csv
import os
client = MongoClient('localhost', 27017)
db = client.project
vulns = db.vulnerabilities
vulns.drop()
vulns = db.vulne... |
import jax.numpy as jnp
def zero_mean(X):
return jnp.zeros(X.shape[0])
|
import math
import numpy as np
class OffloadPCA:
def __init__(self, model, scaler):
self.scaler = scaler
self.n_components = model.n_components_
self.mean_vector = model.mean_
self.pca_components = model.components_.T
self.dim = len(self.mean_vector)
if scaler:
... |
""" Common class/style used on tables """
table_class = ['table',
'table-bordered',
'table-striped',
'vertical-table',
]
table_style = ['margin-left: auto;',
'margin-right: auto;',
'width: auto;',
]
table_args = "cla... |
import geoipgen
from os import _exit
from gui import time
import connection as connection
def byCountryCode(country_code):
cur = connection.mydb.cursor()
cur.execute("select cidr from cidr where country_code='"+country_code+"' and scaned=0 and scanning=0 ORDER BY RAND() LIMIT 1")
resultado = cur.fetchall(... |
from jinja2 import Environment, select_autoescape, FileSystemLoader
class Config:
# Markup
CONTENT_POST_DIR = "./content/posts"
# Static directory
IMAGE_DIR = "./static/img"
TEMPLATE_DIR = "./static/templates"
CSS_DIR = "./static/stylesheets"
# Jinja environment variable
JINJA_ENV = ... |
import os
import sys
import subprocess
import json
cpumachines = [3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,28,29,31,32,33,34,35,36,37,38]
gpumachines = [3,5,6,7,10,11,12,13,14]#[2,3,4,6,7,8,10,11,12,14,15,20]#[2,3,5,7,8,10,11,12,13,14,20]
cmd = []
for m in cpumachines:
cmd.append('ssh -f visio... |
import sys
import numpy as np
import pandas as pd
sys.path.append("../util/")
import dataloader as dl
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
class MatrixFactorization:
def __init__(self, dim_of_factor=10, learning_rate=1e-5, regularization=0.015, max_ite... |
from geopy.geocoders import Nominatim
from geopy import distance
import ipregistry
# in the scope of chatbot responses, the Location class is solely responsible for distanceByLatLong.
# getLocation is a helper function because many of the requests require lat/long coords
class Location(object):
#takes in a place as... |
import logging
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils.timezone import utc
from django.contrib.auth import authenticate, login, get_user_model, logout
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib impo... |
""" Parts of the U-Net model """
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
... |
import nltk
import pandas as pd
import pickle
from nltk.corpus import stopwords
from textblob import TextBlob
from flask import Flask, render_template, url_for, request
from editdistance import distance
from random2 import choice
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes impor... |
class Container(object) :
def __init__(self, **kwargs) :
for name, val in kwargs.iteritems() :
setattr(self, name, val)
|
import pytest
from chess.board import Board
def test_board_init_play_white(start_board):
assert start_board.player_white is True
assert start_board.white_to_move is True
assert start_board.moves == []
def test_board_to_array_white(start_board, game_grid_white):
assert start_board.to_array() == gam... |
class vehicle:
def __init__(self, name, wheels, engines, seats):
self.name = name
self.wheels = wheels
self.engines = engines
self.seats = seats
def getDetails(self):
print("The vehicle",self.name,"has wheels:",self.wheels,"has engines:",self.engines,"has seats:",self.s... |
"""Init file for visualization package."""
from __future__ import division, print_function, absolute_import
from fury._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
"""
@file
@brief Data mostly for the first year.
"""
import os
def anyfile(name, local=True, cache_folder=".", filename=True):
"""
Time about marathons over cities and years
@param name file to download
@param local local data or web
@param cache_fo... |
import binascii
file = open("rgb.bin", "rb")
for i in range(65536*3):
d0 = file.read(1)
x = binascii.b2a_hex(d0)
d1 = file.read(1)
y = binascii.b2a_hex(d1)
d2 = file.read(1)
z = binascii.b2a_hex(d2)
print hex(i),x,y,z
|
"""
state_ps01.py: Get and set vehicle state, parameter and channel-override information. Modified vehicle_state.py
-removed arming code
It also demonstrates how to observe vehicle attribute (state) changes.
Full documentation is provided at http://python.dronekit.io/examples/vehicle_state.html
"""
from droneapi.lib... |
# database object
from app import db
# auth model
from app.auth.models import User
# password / encryption helper tools
from werkzeug import check_password_hash, generate_password_hash
# flask dependencies
from flask import url_for
# utils
import re
import string
import random
# generates random strings
def gene... |
from caboard import CaBoard
import time
class Controller:
def __init__(self):
self.caboard = CaBoard(50)
def draw(self):
self.caboard.draw()
self.caboard.update()
time.sleep(0.1) |
from django.contrib import admin
from chat.models import UserProfile, Message, Room
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'created_at', 'avatar')
raw_id_fields = ('user', )
class MessageAdmin(admin.ModelAdmin):
list_display = ('sender', 'timestamp', 'content')
raw_id_fiel... |
# APIs Configuration
from django.urls import include, path
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('api/v1/product', views.product_Set)
router.register('api/v1/seller_product', views.seller_product_Set)
urlpatterns = [
... |
import numpy as np
from numpy import pi
from numpy.fft import fft2
from numpy.fft import ifft2
from numpy.fft import fftshift
from numpy.fft import ifftshift
import matplotlib.pyplot as plt
from skimage.data import shepp_logan_phantom
from skimage.transform import resize
FFT = lambda x: fftshift(fft2(ifftshift(x)))
I... |
import textwrap
from onegov.core.utils import module_path
from onegov.form import FormCollection
from onegov.org.initial_content import add_filesets, load_content, add_pages
from onegov.org.models import Organisation
def create_new_organisation(app, name, create_files=True, path=None,
loc... |
"""
Test for using a configuration file
"""
import os
import unittest
import tempfile
import logging
import scitokens
import scitokens.utils.config
import configparser
class TestConfig(unittest.TestCase):
"""
Test the configuration parsing
"""
def setUp(self):
self.dir_path = os.path.dirname(... |
import os
import sys
import torch
from torch.autograd import Variable
import torch.nn as nn
from qpth.qp import QPFunction
def computeGramMatrix(A, B):
"""
Constructs a linear kernel matrix between A and B.
We assume that each row in A and B represents a d-dimensional feature vector.
Parameters:... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import sqlite3
import os
import pylast
import time
# "congif"
url = "http://rockradio.si/api/module/json/RadioSchedule/JsonModule/GetStreamInfo"
post = {'RadioStreamId': '1', 'SystemName': '', 'Title=': '', 'Description' : '', 'Icon%5BId%5D' :... |
# Une y triunfarás
# Se recibieron distintos postulantes para un empleo de traductor. Crear un diccionario en el cuál la key de cada elemento sea el nombre de un candidato y el contenido sea un set con los idiomas que aprendió. Inventar valores para 5 candidatos.
# Mostrar en pantalla los idiomas que todos los candida... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.