index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
15,200 | 748e1f32a9632642ef19f549317e884a560dd531 | from app.models import Pagination, Product, Offer, Category, AllCategories
class TestCategory:
def test_init(self):
category = Category(1, 'Category 1')
assert category.obj_id == 1
assert category.title == 'Category 1'
class TestAllCategories:
def test_init(self):
categories ... |
15,201 | d6dce521cf38954586b365a0218b1267f609cc79 |
class Tree():
def __init__(self, value, partition_key, lookup_key):
self.value = value
self.partition_key = partition_key
self.lookup_key = lookup_key
self.left = None
self.right = None
def insert(self, value, partition_key, lookup_key):
if self.left == None and... |
15,202 | 3f1247bd1a37dcab9108c09a5dcf3293eb7b6964 | #!/bin/python
class Board:
def __init__(self):
self.aliveCells = set()
def isCellAlive(self, x, y):
return (x, y) in self.aliveCells
def bringToLife(self, x, y):
self.aliveCells.add((x, y))
def evolve(self):
cellsToDie = set()
newBornCells = set()
for cell in self.aliveCells:
i... |
15,203 | 556de5347af6037564145c21b38e02a236d51166 | __author__='callMeBin'
#!/usr/bin/env Python
# coding=utf-8
import re
import requests
import jieba
import numpy as np
import codecs
import matplotlib
from bs4 import BeautifulSoup
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
import pandas as pd
import time
from pandas import Seri... |
15,204 | 0db08499236031e7d081f3f4fa2e1cb906b0f44f | # Copyright 2020 Francesco Ceccon
#
# 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 writ... |
15,205 | d2025e3a027bf2a9d9eaf429004af20c16992c35 | #encoding=utf8
import json
import re,os
from wox import Wox,WoxAPI
class Shadowsocks(Wox):
def get_pac_path(self):
with open(os.path.join(os.path.dirname(__file__),"config.json"), "r") as content_file:
config = json.loads(content_file.read())
return config["pacPath"]
def add_n... |
15,206 | 453b56b0f7a20faf6b6733ab1db9a85b525dfda0 | n=int(input())
array=list(map(int,input().split()))
ans=1
if 0 in array:
ans=0
else:
for i in range(n):
if ans>10**18:
break
else:
ans=ans*array[i]
if ans>10**18:
print(-1)
else:
print(ans) |
15,207 | 9ba3438bb8b82d599777d27f8a2dec5210c5d245 | # coding: utf-8
import sys
assert sys.version_info >= (3,4)
ROOT_DELIM = '_'
IGS_DELIM = '.'
class Tag(object):
def __init__(self, root, ig):
self.root = root
self.ig = ig
self.fine_ig = None
self.coarse()
self.xpos()
self.conll_analysis()
def __repr__(self):
... |
15,208 | 6460fdaa934c80168b6f1ffa3a54e936464d16ef | from django.urls import path
from . import views
urlpatterns = [
path('projectcategory/', views.ProjectCategoryList.as_view(), name='projectcategory_list'),
path('projectdetails/', views.ProjectDetailsList.as_view(), name='projectdetails_list'),
path('userDetails/', views.UserDetail.as_view(), name='user-... |
15,209 | c4b284a77bc6f1d59ac1aada1c4f4596d89a3e67 |
lines = [line.rstrip('\n ') for line in open('input.csv')]
outFile = open('input_one_line.csv', "w")
outFile.write("%s\n" % lines[0])
lines.pop(0)
dc = {}
for line in lines:
key = line.split(",")[0]
value = line.split(",")[1]
if dc.get(key) is None:
dc[key] = value
else:
dc[key] = d... |
15,210 | 995617be8a20a829ede13e01407ccf2132ca2ce0 | #!/usr/bin/python3
#Automate Ecoli
#Ben Lorentz 2.22.19
import sys
import os
import logging
dir = os.getcwd()
cwd = dir+"/OptionA_Ben_Lorentz"
if(not os.path.exists("OptionA_Ben_Lorentz")):
os.system("mkdir OptionA_Ben_Lorentz")
os.chdir(dir+"/OptionA_Ben_Lorentz")
else:
os.chdir(dir+"/OptionA_... |
15,211 | a5ae78d9c43569237b899b4b736573079e0cb014 | from urllib.parse import urljoin
import requests
import logging
from bs4 import BeautifulSoup as Bs
from requests import HTTPError
from application.models.model import Radio
_URL = "http://radios.sapo.ao"
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77... |
15,212 | 64e5169f31e74b95c90687ab7fb8884577a51557 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
class Vector(object):
def __init__(self, list):
self.list = list
def __len__(self):
return len(self.list)
def __str__(self):
return str(self.list)
def __add__(self, vector1):
svector = []
for i in xrang... |
15,213 | 2f60afa8200f278152252247b40a8ce73ec8227d | # -*- coding: utf-8 -*-
"""
####
Main
####
Main model runner
Note: This is intended to be run from the command line
"""
import time
import os
start = time.time() # start run clock
import shutil
import logging
import yaml
from pathlib import Path
import concurrent.futures
import click
from fetch3.__version__ impo... |
15,214 | a7e8b1bae0e3ab0be7c09a5e66923b0c563a0a87 | import numpy as np
import pandas as pd
import pandas_datareader as web
import statsmodels.api as sm
from statsmodels.regression.rolling import RollingOLS
from collections import OrderedDict
import streamlit as st
"""
To run from command line, install streamlit, then type:
streamlit run oil.py
"""
tickers = ["USO",
... |
15,215 | 76acb2de81774cf981d445641e3df0112485420a | import tensorflow as tf
#定义一个变量用于计算滑动平均,这个变量的初始值为0,注意这里手动指定了变量的类型为tf.float32,因为所有需要计算滑动平均的变量必需是实数型
v1 = tf.Variable(0,dtype=tf.float32)
#这里step变量模拟神经网络中迭代的轮数,可以用于动态控制衰减率
step = tf.Variable(0, trainable=False)
#定义一个滑动平均的类(class),初始化时给定了衰减率(0.99)和控制衰减率的变量step
ema = tf.train.ExponentialMovingAverage(0.99,step)
# -*- ... |
15,216 | 656419e3df9dd1622270cb6589e0884033c46f3e | import unittest
from munch import Munch
from mock import patch, NonCallableMagicMock
from controller.array_action.array_mediator_ds8k import DS8KArrayMediator
from controller.array_action.array_mediator_ds8k import shorten_volume_name
from controller.array_action.array_mediator_ds8k import IOPORT_STATUS_ONLINE
from pyd... |
15,217 | 0dff14935f71bda4c7793951ccdcc7f07f3b72ab | import arcpy,os,math
inputFC = arcpy.GetParameter(0)
inputCenter = arcpy.GetParameter(1)
outputFC = arcpy.GetParameterAsText(2)
path=os.path.dirname(outputFC)
outputFC=os.path.basename(outputFC)
#path=r"D:\Benutzer\issh1011\Documents\ArcGIS\Default.gdb"
#arcpy.env.workspace = path
with arcpy.da.SearchCursor(inputCe... |
15,218 | 4597b0d2e3499f4a3910b5ca35805d7b85d13e15 | # Créez une liste "x" de 4 tuples de forme (x, y)
listx=[("a","b","c","d")]
print(listx)
listx=[("a","b","c","d"),"a"]
print(listx)
listx=[("a","b","c","d"),"a"]
listx.insert(2,"b")
print(listx)
listy=[1, 2, 3]
listx.extend(listy)
print(listx)
listx.insert(4,2)
print(listx)
del listx[4]
print(listx)
print(list... |
15,219 | ccbf5946bf6b2fc437a7294686efe7e25456988a | #!/usr/bin/env python
"""
'multimutect.py', by Sean Soderman
Parallelizer for MuTect.
"""
from itertools import izip
from synchrom import Synchrom
from time import time
import argparse
import multiprocessing
import os
import re
import subprocess
import sys
try:
from concurrent.futures import ThreadPoolExecu... |
15,220 | b7d431ae6399d30dbc9f605546dde44d23a99393 | from twisted.trial import unittest
from tests.utils import make_sydent
class StartupTestCase(unittest.TestCase):
"""Test that sydent started up correctly"""
def test_start(self):
sydent = make_sydent()
sydent.run()
|
15,221 | af0f541201a2a5921f98982cf7d4d92321110626 | # model settings
# retinanet_obb_r50_fpn_2x.py
model = dict(
type='R3Det',
pretrained='modelzoo://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
style='pytorch'),
neck=dict(
type='FPN',
... |
15,222 | 6dfdd776ab800727eaa4af00ddcc810e9704c8fa | import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
class Operation():
def __init__(self, input_nodes=[]):
self.input_nodes = input_nodes
self.output_nodes = []
# for every node in the input, we want to append the particular
# operation to th... |
15,223 | 9dea205696cdc1804c554cb67533b73ceb7242bf | """Example of using hangups to send hangouts notifications to the Ergodox"""
import asyncio
import hangups
import serial
from libs.ergodox_infinity_display import ErgodoxInterface
# Path where OAuth refresh token is saved, allowing hangups to remember your
# credentials.
REFRESH_TOKEN_PATH = 'refresh_token.txt'
def... |
15,224 | 2f38fbc4fb46ad1623ed255281ad128354ae259e |
from django.conf.urls import url, include
from django.contrib import admin
from foodtaskerapp import views
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
#resturant
url(r'^admin/', admin.site.urls),
url(r'^$',... |
15,225 | c38c5d12ea21f8e342c2de7c31337cec49a758f6 | from django import forms
from salesforce.SalesforceClient import SalesforceClient
class ReportForm(forms.Form):
sf_id = forms.CharField()
def clean(self):
cleaned_data = super(ReportForm, self).clean()
sf_id = cleaned_data.get('sf_id')
sfc = SalesforceClient()
try:
... |
15,226 | c3f29c51fbb4ece54c0426c10d61c33798c522b6 | """
Module to read configuration files
"""
from configobj import ConfigObj, ConfigObjError, ParseError
from .config import (
HOLLANDCFG,
BaseConfig,
ConfigError,
load_backupset_config,
setup_config,
)
__all__ = ["HOLLANDCFG", "setup_config", "load_backupset_config", "BaseConfig"]
|
15,227 | efd2415b8ce639f6e01e51f71cf22b509b26f46f | import errno
import os
import shutil
import sys
def make_sure_dir_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def _config_template():
return os.path.join(sys.path[0], "darkwallet.cfg")
def make_sure_file_exists(fi... |
15,228 | ec51b1246e5ee4d9e8d5e0cf4413c286718869a7 | #!/usr/bin/python
__author__ = "Bassim Aly"
__EMAIL__ = "basim.alyy@gmail.com"
import subprocess
print(subprocess.Popen("ifconfig"))
# You can re-write the code and use the list
import subprocess
print(subprocess.Popen(["ifconfig"]))
# using a list, you can bypass additional args to the command
import subprocess
... |
15,229 | 579dd47402991ee2f70e9e30d06024113dcc966f | def cutTheSticks(ar):
while(max(ar)!=min(ar)):
print(len(ar))
x=min(ar)
for i in range(len(ar)):
ar[i]=ar[i]-x
while (0 in ar):
ar.remove(0)
print(len(ar))
try:
n=int(input())
ar=list(map(int,input().split()))
except:
print("ERROR! Enter numer... |
15,230 | c69e53558a98c9cd45125b1e64a255fcbeda9f7e | # program to find square of the number
N = eval(input("enter the limit"))
if 1 <= N and N <= 20:
for i in range(N):
print(i * i)
|
15,231 | dd3b389c63929b37b7152473e1c8d084b2fc2d04 | from django.contrib import admin
from .models import Movie, Showing, Theatre
# Register your models here.
admin.site.register(Movie)
admin.site.register(Theatre)
admin.site.register(Showing)
|
15,232 | 40fa273c5a82bab805d38a05723bea382d4c7462 | strings = input().split()
result = ""
for string in strings:
result += string * len(string)
print(result)
|
15,233 | fe9dc8c887b05a87d851743e42fd77ce975fb5e1 | # Lists - lists are "mutable"
friends = ['Amila','Samith','Daniel']
# Add new friend to the list.
friends.append("Zusan")
print(friends)
# Count number of times an element appears
count = friends.count("Amila")
print(count)
# Number of elements in the list.
ln = len(friends)
print(ln)
|
15,234 | 9452d5de7d0a81c9edcf24054031db1ed7d985e0 | #-*- coding:utf-8 -*-
from __future__ import print_function
from datetime import datetime, timedelta
import copy
import pprint
from crawl import Crawl
from wrapdb import Db
from names import names
# dados da sabesp estao disponiveis desde 2003
# TODO
"""
fazer isso rodar mais rapido
"""
mainData = {names.year: N... |
15,235 | 6fa57a62aa92d036cfba9a7dfa5dce31fcfae07c | from pros import pros_vision_function
from time import sleep
import cv2
import numpy as np
from PIL import Image
i = 0
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
input_img = cv2.imread('C:/Users/hp/downloads/trekar.jpg')
gray_input = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
inputim... |
15,236 | 53bde934c39a2d795f856f4ef76f25e10e158593 | '''
Created on Nov 14, 2010
@author: pekka
'''
import unittest
from shallowspace.eventmanager import EventManager
from shallowspace.event import CharactorPlaceEvent, FreeSectorAction
from shallowspace.map import Sector, MapState
from shallowspace.constants import DIRECTION_UP, DIRECTION_LEFT, DIRECTION_DOWN, DIRECTION... |
15,237 | c52d2436677d945d3ddd5b2c5c39d6dc4c034249 | from __future__ import print_function, absolute_import, division
import enum
import logging
import os
import typing as tp
import uuid
from logging import Logger
from satella.coding import silence_excs
from satella.files import DevNullFilelikeObject
from satella.instrumentation import Traceback
from .exception_handler... |
15,238 | 21394e88f381b61305ee94012aac4b98a9c753cd | #!/usr/bin/env python
# coding: utf-8
# ## Real state price predictor
# In[1]:
import pandas as pd
# In[2]:
housing = pd.read_csv("data.csv")
# In[3]:
housing.head()
# In[4]:
housing.info() #information about the data
# In[5]:
housing['CHAS'].value_counts() #counting the value
# In[6]:
housing... |
15,239 | 5970eb7b10cc92b695c6565335d7028e1e37c734 | import csv
import sys
with open('D://PythonProject//drawMember//membersBig5.csv', 'rt', encoding='cp950') as f:
r = csv.DictReader(f)
for row in r:
print(row['Name'], ' ', row['Group'])
|
15,240 | cf2d977c8caf7ac18e798b52dd15bd34658de428 |
import requests
from bs4 import BeautifulSoup
import csv
import time
import re
import traceback
URL = 'https://book.douban.com/subject/26943161/comments/new'
# ?p=2
def get_html():
try:
page = 1
user_agent = {'user-agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, lik... |
15,241 | 6a235a9537991534b712f9a4f00e30e3c6aadfa3 | """
.. module: lemur.endpoints.cli
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from flask_script import Manager
import arrow
from datetime import timedelta
from sqlalch... |
15,242 | ef87ab11987d77d1b3d763f6e5d4b34867589999 | # -*- coding:utf-8 -*-
# __author__ = 'dayinfinte'
from flask import request, jsonify, url_for
from ..models import Post
from .. import db
from . import api
@api.route('/posts/')
def get_posts():
posts = Post.query.all()
return jsonify({'posts': [post.to_json() for post in posts]})
@api.route('/post/<int:id>... |
15,243 | c8a6b333f636800db76e2c0c57032e43f1261236 |
#! /usr/bin/env python
def take_child(str_arg):
long_person(str_arg)
print('number')
def long_person(str_arg):
print(str_arg)
if __name__ == '__main__':
take_child('find_long_part_at_life')
|
15,244 | f07f6f85ee3bb8bbbe0282be3cd6604afb721bff | import json
import logging
from pprint import pprint
from time import sleep
import requests
from bs4 import BeautifulSoup
from elasticsearch import helpers
from elasticsearch import Elasticsearch
def search(es_object, index_name, search):
"""
This method will display results with respect to queries.
... |
15,245 | 1d07feabf575dcc3372264678328eaffe30d44bf | __author__ = 'bourgeois'
import math
from math import pi
print("I was taught Python3 course. Hello bourgeois")
#CIRCLE
#Perimeter of a Circle
def circle_perimeter(radius):
'''
Calculate perimeter of a circle from radius
:param radius: the radius
:return: the perimeter (same units as the radius)
'... |
15,246 | eecec84441514adfc6302435b0a73af928b950ae | import shutil
import logging
from pathlib import Path
from main import RUNNING
from f1.config import CACHE_DIR
"""Delete the contents of the ./cache directory.
Ensure the bot is not running. A new cache will be built when starting the bot.
"""
logger = logging.getLogger("f1-bot")
if __name__ == "__main__":
i... |
15,247 | 42ed07779a34ded965f71df87c45c2f21535430c | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
#defining functions to be used
tau = 2.2
#exponential function
def p(x):
return (1/tau)*np.exp(-1*x/tau)
#cumulative function of p(x)
def g(t):
return (1-np.exp(-t/tau))
#inverse of the cumulative function
def g_i(y):
return (-tau*np.... |
15,248 | 625b855c2e4944b2ac9d158ddeda89b6309ca449 | from django import forms
class AddProposal(forms.Form):
alum_current_institute = forms.CharField(max_length=50, required=True)
alum_current_address = forms.CharField(widget=forms.Textarea,
required=True, max_length=100)
title = forms.CharField(
max_length... |
15,249 | 97d85acf557d6c6c766c254574baf4b91d29dfc3 | '''
Created on 3 Apr 2016
@author: John Beard
'''
import requests
from urllib.parse import quote
from mnem import mnem
class RequestDataLoadError(mnem.MnemError):
'''
Error thrown when a request fails to acquire required data
'''
def __init__(self, engine, url, query, exception=None):
self.... |
15,250 | 4376150d332e5cf996f9662a72839f5fff22a5ff | #!/usr/bin/env python2.7
import atexit
import logging
import sys
import threading
import time
from PyQt4 import QtGui
from biosignals.print_biosignal import PrintBiosignal
from biosignals.tagger import Tagger
from controller.MESSAGE import Message
from controller.controller import Controller
from controller.processor ... |
15,251 | 3fe511ef7f4d35db14569aa392a223fe7328685d | from django.shortcuts import render, redirect, get_object_or_404
# Create your views here.
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from .models import Board
from django.contrib.auth.decorators import login_required
... |
15,252 | 6b3ad5abd41c72d4454b7b26e2f7911384e008b1 | import string
import re
import unicodedata
from nltk.corpus import wordnet as wn
from nltk.stem import WordNetLemmatizer
def clean_punctuation(s, punc_to_keep=[]):
"""
Strip string of punctuation
:param s: a string to strip of punctuation
:param punc_to_keep: a set with all the punctuation mar... |
15,253 | 28752ceee915b1e4c54427f32eb3084323b2e79d | #!/usr/bin/env python3
""" normalizes (standardizes) a matrix """
def normalize(X, m, s):
"""
m is the number of data points
nx is the number of features
"""
return ((X - m) / s)
|
15,254 | a787dbd96833cf3c06dad4cdbcd665f298e9fcee | # Generated by Django 2.2.7 on 2020-01-18 22:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student_Datasss', '0011_result_extra'),
]
operations = [
migrations.AddField(
model_name='result_extra',
name='stude... |
15,255 | 62831699cf999516dda3e6ce524ac24e3359473a | # -*- coding: utf-8 -*-
#!/usr/bin/env python3
#filename handle.py
import hashlib
import web
class Handle(object):
def POST(self):
pass
# get方法,验证token
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "token success!"
si... |
15,256 | fff3f3591382f95564103523692c8b36e9a79a03 | """Run the EasyInstall command"""
import sys
import os
import textwrap
import contextlib
def bootstrap():
# This function is called when setuptools*.egg is run using /bin/sh
import setuptools
argv0 = os.path.dirname(setuptools.__path__[0])
sys.argv[0] = argv0
sys.argv.append(argv0)
main()
... |
15,257 | 08d38fa2ba8622caa8a5eca41e43f1cb14dd6b0b | # Exercício Python 082: Crie um programa que vai ler vários números e colocar em uma lista.
# Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente.
# Ao final, mostre o conteúdo das três listas geradas.
randomNumber = []
evenNumbers = []
oddNumbe... |
15,258 | 7f9678113afcde3622ea80af051b059f91d8e153 | import numpy as np
x = np.arange(1,11)
print(x) |
15,259 | 018eefee22393c5987c0f8e8147bb943fce2201d | # from splinter.browser import Browser
# from time import sleep
# import traceback
#
# # 设定用户名,密码
# username = u"cl1911618290"
# passwd = u"wykqh101119"
#
# # 起始地址的cookies值要自己去找, 下面两个分别是上海, 营口东。如何找,我们在文#后有简单的介绍
#
# starts = u"%u6DEE%u6EE8%2CHVN"
#
# ends = u"%u9526%u5DDE%2CJZD"
#
# # 时间格式
#
# dtime = u"2018-09-01"
#
# ... |
15,260 | 27bbe3dc3e444fb6deb5b96fe152f9ca5beeaa6e | # Generated by Django 2.2.5 on 2019-10-05 03:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ChConversation',
... |
15,261 | d4ffe7b65fb8741f88d85e899135245087db4886 |
#! /usr/bin/env python
def child(str_arg):
tell_thing(str_arg)
print('part')
def tell_thing(str_arg):
print(str_arg)
if __name__ == '__main__':
child('young_part')
|
15,262 | 2db4e49ed4e80c3d0b817a13d1f12bb9debc5f11 | import math
import os
import random
import re
import sys
if __name__="__main__":
n=int(input().strip())
for i in range(1,11):
print(n,"x",i, "=",(n*i)) |
15,263 | b993047139638a683ccc2ae961f89d91f13ce367 | import re
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.clock import Clock
from kivy.properties import NumericProperty, ObjectProperty, BooleanProperty
from kivy.uix.bubble import Bubble
from .navigation import Navigation
from kivy.lang.builder import Builder
Builder.load_string("""
<-Text... |
15,264 | 0ab486ac522e7f0da27daf56b9a8c454256bb66f | ##############################################################################################
# PURPOSE
# Creates the multiple plots relating the Q_i parameter with the properties of the LCGs (oxygen abundances, sSFR and concentration)
#
# CREATED BY:
# Vitor Eduardo Buss Bootz
#
# ADAPTED BY:
#
# CALLING SEQUENC... |
15,265 | d2a2d058dda763c44ac09dd70be4b6c4b7045a56 | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ArtistaFavorit(models.Model):
id_artista = models.AutoField(primary_key=True)
nom = models.CharField(max_length=200)
usuari = models.ForeignKey(User) |
15,266 | 938699b3e64fb87d22f5f9d3dbd0550af73636b4 | import pyinputplus as pyin
while True:
prompt = 'want to know how to keep an idiot busy for hours?'
response = pyin.inputYesNo(prompt)
if response == 'no':
break
print('thank you bhai!!!!!!') |
15,267 | c4223f21ab110acd485704631d66e7285867fc78 | Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Dict.update({"Sarah":9})
print(Dict) |
15,268 | 6f8ec623cbc471911bd56fb24e9e453f044a464a | # EMAILFEATURES takes in a word_indices vector and produces a feature vector
# from the word indices
def emailFeatures(word_indices):
'''
x = EMAILFEATURES(word_indices) takes in a word_indices vector and
construct a binary feature vector that indicates whether a particular
word occurs in the email.
... |
15,269 | 5a0660f2733991a0a52b710245bdf23d9351c217 | def match(s1,s2):
count=0
s=[]
for char in s1:
if char in s2:
s.append(char)
count+=1
print(count)
return s
s1="snigdha"
s2="sniwqwq"
match(s1,s2) |
15,270 | cd8d3556f162a231d82c347e7cecadcaa6020e66 | import os
import json
import logging
import random
import shutil
import unittest
import functools
import tempfile
from nose.plugins.attrib import attr
import pbsmrtpipe.cluster as C
from pbsmrtpipe.engine import backticks, run_command
from base import (TEST_DATA_DIR, HAS_CLUSTER_QSUB, get_temp_cluster_dir, SLOW_ATTR... |
15,271 | 1e31b17710c3454a649155dde30d120856b43a59 | """
Author: Renato Durrer
Created: 25.03.2019
File in with helpful functions for data creation and processing are written.
"""
import Labber
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
def data_creator(logfile):
"""
Takes the Labber LogFile and creates a new data file for... |
15,272 | e4a18f3e06099e521ccfd4e83f7242b4c330c18f | #!/usr/bin/env python3
"""
TFTP Server Command.
"""
import sys
import os
import argparse
import tftp
TIMEOUT = 2
PORT = 6969
parser = argparse.ArgumentParser(prog='tftp-server')
parser.add_argument('-p', '--port', type=int, default=PORT)
parser.add_argument('-t', '--timeout', type=int, default=TIMEOUT)
parser.add_ar... |
15,273 | 01cd5a9c980ca6aa3129409fa8fdce0fadd9fba9 | import urllib, urllib2
from simplejson import loads
BASE_URL = 'http://rest.nexmo.com/sms'
JSON_END_POINT = BASE_URL + '/json'
XML_END_POINT = BASE_URL + '/xml'
class NexmoError(Exception):
pass
class Client(object):
"""
Send SMS using nexmo
"""
def __init__(self, username, password):
se... |
15,274 | c1896fc755d5106926aa7ed6b9cfc8b1731ee856 |
# Input
with open("coins.in") as f:
value = int(float(f.readline()) * 100)
# Define coin values in cents
coins = [1, 5, 10, 25]
# Greedy method
num = 0 # number of coins
cc = 3 # current coin
while value > 0:
while coins[cc] > value:
cc -= 1
value -= coins[cc]
num += 1
# Output
with open... |
15,275 | ae0c8b8223fd273e19d9c8def24161a4aa10e24a | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import os
import six
# os的常用api,比如文件功能,path功能等
def os_path():
print(os.path.abspath("."))
file_name = "pytest"
print(os.path.isfile(file_name))
print(six.PY3)
print(six.PY2)
|
15,276 | f644833bae221ccecaf4ae4032d1f9197b7b374f | from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
class Browser:
def __init__(self, driver_exe, path, options=[]):
if driver_exe == 'chromedriver':
chromedriver_path_location = path
if opt... |
15,277 | f02bf9918148011259262671ea75abbfe8537c41 | import os
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException, BinanceOrderException
# init
api_key = os.environ.get('binance_api')
api_secret = os.environ.get('binance_secret')
client = Client(api_key, api_secret)
## main
try:
order = client.create_oco... |
15,278 | ffe4e9c5b61ecf1664d946d5cb670f988025f1fc | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
with open('text1.txt', 'r', encoding="utf8") as f:
text1 = f.read()
# Заменить символы конца предложения.
text1 = text1.replace("!", ".")
text1 = text1.replace("?", ".")
# Удалить все многоточия.
whi... |
15,279 | bc0a8c66b7880cbf706030fb2b0712e0f787e3da | #!/usr/bin/env python
# encoding: utf-8
"""
exp1.py
First experiment: extremely simple region detection using thresholding.
Created by Oliver Smith on 2009-08-16.
Copyright (c) 2009 Oliver Smith. All rights reserved.
"""
import cv
import sys
val1 = 1
def chgv1(x):
global val1
val1 = x
def validate_contour(c):
... |
15,280 | e488dd4af33f95678b0ecbb9fac06ef97d4ef672 | __author__ = 'arsia'
class CpuPlayer:
def __init__(self, mark):
self.mark = mark
self.round = 1 # To track if it is the first or second or ... move by computer
self.op = '-' # What marker the opponent is using (x or o)?
self.moved = False # To make sure we do not mar... |
15,281 | 2998008e227da544663c29ccc79fa995ba2b42b6 | a=float(input('enter number '))
'''создание первого числа'''
min = a
max = a
'''присвоение значения первого числа максимальному и минимальному значению'''
for i in range(5):
'''цикл для создания чисел и проверки их на максимальность или минимальность'''
a=float(input('enter number '))
'''создание нового ... |
15,282 | 7b44214b45b2579f62d1b3067c15f784b2d11bca | #!/usr/bin/env python
import argparse
import logging
import os
import sys
import time
import parsers
import settings
from src import utils
logger = logging.getLogger(__name__)
MAIN_URL = "http://www.aemet.es/es/eltiempo/observacion/ultimosdatos"
STATE_URL = MAIN_URL + "?k=%s&w=0&datos=det&x=h24&f=temperatura"
STATI... |
15,283 | 80441a828b469490297f8a5a4f7970dd62d51b07 | #!/usr/bin/python
import marathon
import requests
import json
from jsonschema import validate
from marathon import MarathonClient
from marathon.models import MarathonApp, MarathonDeployment, MarathonGroup, MarathonInfo, MarathonTask, MarathonEndpoint, MarathonQueueItem
from marathon.exceptions import InternalServerErr... |
15,284 | 6437da8de33706f49143bb1ac396be3d45e4d200 | from django.db import models
class Bookinfo(models.Model):
bookname = models.CharField(max_length=30, verbose_name='书名')
autor = models.CharField(max_length=30, verbose_name='作者')
postedtime = models.DateField(auto_now_add=True, verbose_name='发表时间')
altertime = models.DateField(auto_now=True, verbose_... |
15,285 | b2d3cace82dd1e0b8b6842bac81b6edbb7846adb | ##LESSSE
##10 November 2018
##gmidi
##____________
##Python Organologic Midi Dictionary
##____________
organology_dict={}
organology_dict['flutes'] = [72,73,74,75,76,77,78,79]
organology_dict['oboes'] = [68,69]
organology_dict['clarinets'] = [71]
organology_dict['saxofones'] = [64,65,66,67]
organology_dict['bassoon... |
15,286 | 260916194d37710564b85914f46887f07406c4bd | import pyramid.testing
import pym.testing
import pym.models
def before_all(context):
args = pym.testing.TestingArgs
app = pym.testing.init_app(args, setup_logging=True)
# This essentially sets properties:
# settings, DbEngine, DbSession, DbBase
for k, v in app.items():
setattr(context, k,... |
15,287 | a4d4ec893c77f94f5666bff0352606e1e16a23bf | import torch.nn as nn
class SentimentLSTM(nn.Module):
"""
The RNN model that will be used to perform Sentiment analysis.
"""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.7):
"""
Initialize the model by setting up the layers.
"""
... |
15,288 | 9606b5349d79a3e0733f0009ec042b29614dabae | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
import time
offset = int(sys.argv[2])
random = random.Random()
random.seed(time.time() + offset)
data = ""
if sys.argv[1] == "right":
data += random.choice(["▙", "▛", "█"])
data += random.choice(["▚", "▞"])
data += random.choice(["▗",... |
15,289 | 16578416e62f731594c898e94affbb71d98de8f2 | # coding=utf-8
# Input:_2015_6_2015_6_7_in.csv,_2015_6_2015_6_7_out.csv
# Output:match
# Author:ZJW
import csvdata
import diffdata
import evlfunc
import connectingcar
import storage
import time
import codecs
'''
2轴车:1min26s 200duo
3轴车: 23s 100duo
4轴车:22s
5轴车: 2s
6轴车: 6min57 500duo
设置定时器进行验证
'''
def run(zss,k1,... |
15,290 | 21e2483fd03adfbfda85f4bbb453c22f326d3966 | fullTextPath = '/mnt/datasets/erudit/'
extractedTextPath = 'fullText/'
rankingsPath = 'rankings'
termsPath = 'terms/'
picklePath = 'pickles/'
SolrFilesPath = 'solr.files/'
|
15,291 | 1158351111741031adcd544e86e91a6f7548bec0 | from joueur.base_ai import BaseAI
from math import inf
from timeit import default_timer as timer
from collections import namedtuple, defaultdict
from itertools import count
from random import getrandbits
from operator import xor
import re
'''
This board representation is based off the Sunfish Python Chess Engine
Seve... |
15,292 | b2196821507fa49a1993c00ec0644c420eae8ebb | import math
import numpy
import os
import xboa.common
import ROOT
import utilities.root_style
class PlotAmplitudeData(object):
def __init__(self, amplitude_data, plot_dir, key):
self.data = amplitude_data
self.plot_dir = plot_dir
self.key = key
def plot(self):
self.plot_data_... |
15,293 | 2675ec4578a42e4f692af58596fbc2b8314f3bf3 | # -*- coding: UTF-8 -*-
import sys
import csv
import json
import time
from elasticsearch import Elasticsearch
from filter_rules import filter_activity, filter_ip, filter_retweet_count, filter_mention
reload(sys)
sys.path.append('../../')
from global_utils import R_CLUSTER_FLOW2, R_DICT, ES_DAILY_RANK, es_us... |
15,294 | bb7eb2c6f5a21e575c049f0e2de5a8cf5a941d1d | #!/usr/bin/python3
def print_last_digit(number):
if (number < 0):
ch = ((number * -1) % 10)
else:
ch = (number % 10)
print("{:d}".format(ch), end="")
return(ch)
|
15,295 | 654ae0182c187b903f23d7dca7b9769c0ed1952a | # Generated by Django 2.1.7 on 2019-08-04 20:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('paytm', '0007_auto_20190... |
15,296 | dee57002049b84494353582f35a73f95cd9e8797 | from django.urls import path
from . import views
urlpatterns = [
path('', views.generate, name='generate_barcodes'),
]
|
15,297 | 6611024e217dc540f6c8a05b47ccf337a4f2ce61 | price = [10, 20, 30, 40]
total = 0
for totall in price:
total += totall
print(f"Total: {total}") |
15,298 | 473697b305a3c345cec60836904b9f2c65d17852 | #! /usr/bin/python
import os
os.system ('clear')
# functions with specific args
def abc(x,y,z):
return sum([x,y,z])
r=abc(z=34,x=100,y=200)
print r
|
15,299 | 691dfd80930fcbc857bddd04504d78ed7fce3855 | """After the initial BioBank assessment, two later assessments were
performed. However, this data is not that helpful to us, as
the two later assessments were completed by a fraction of the original cohort.
This script takes in a BioBank file, and removes the extra instances.
"""
# BELOW: constants that often need... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.