index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
2,500 | cee77a97503cca517d03ce7cce189974da282a03 | """
Created on Wed Nov 6 13:03:42 2019
@author: antonio.blago
"""
#%% Connect to database
import sqlite3
conn = sqlite3.connect('Portfolio_dividens.db')
c = conn.cursor()
from sqlalchemy import create_engine #suport pd.dataframe to sql table
#import mysqlclient
engine = create_engine("sqlite:///Portf... |
2,501 | e05f545ca969e0c2330779ed54a33a594d6ebb25 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/10 14:26
# @Author : MengHe
# @File : c1.py
# @Software: PyCharm
import re
a = 'Python|Java|C#|C++|Kotlin|JavaScript'
r = re.findall('Java', a)
print(r)
# print(a.index('Python') > -1)
# print('Kotlin' in a) |
2,502 | eed79a3895975a0475c0b192bd8a42e80def2e78 | import os
import stat
from optparse import OptionParser
from bbpgsql.configuration import get_config_from_filename_and_set_up_logging
from bbpgsql.configuration.general import get_data_dir
from subprocess import check_output
import sys
VERSION = ''
class BadArgumentException(Exception):
def __init__(self, msg):
... |
2,503 | 35c4e26acbe99ca7f37b63b67f38d5c40fbf0ea4 | club_info = {'club_url': 'https://www.futbin.com///18/leagues/Major%20League%20Soccer?page=1&club=101112', 'club_logo': 'https://cdn.futbin.com/content/fifa18/img/clubs/101112.png', 'club_name': 'Vancouver Whitecaps FC'}
players = {}
players['Waston'] = {'player_url': 'https://www.futbin.com//18/player/15583/Kendall Wa... |
2,504 | a2d23c05e1ca04d25f5f5012881c4000e6316cb9 | left_motor = 1563872856371375
right_motor = 7567382956378165
servo = 9275392915737265
def autonomous_setup():
print("Autonomous mode has started!")
Robot.run(autonomous_actions)
def autonomous_main():
pass
async def autonomous_actions():
print("Autonomous action sequence started")
await Actions.s... |
2,505 | 94334f91b1556c05dce0ed6f23c074bb8875f185 | import re
s=input('enter the string:')
def end_num(s):
text = re.compile(r".*[0-9]$")
if text.match(s):
return 'Yes!Number is present at the end of string'
else:
return 'No!Number is not present at the end of string'
print(end_num(s))
|
2,506 | 9696e5799d46adb5b92c0900e2064b927addfd93 | # este script comprar diferente metodos de base2number
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
#from matplotlib import pyplot as plt
#from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib import pyplot
import math
import os
import sys
import ... |
2,507 | 89376b2464dfb724197a1c1e164af8277e03ad59 | from armulator.armv6.bits_ops import add_with_carry, bit_not
from armulator.armv6.enums import InstrSet
from armulator.armv6.opcodes.opcode import Opcode
class SubsPcLrThumb(Opcode):
def __init__(self, instruction, imm32, n):
super().__init__(instruction)
self.imm32 = imm32
self.n = n
... |
2,508 | 6d8c32fe51fadbe6b6ee14419e1e37c65d4f57bf |
BLUE = "#1A94D6"
GREEN = "#73AD21"
PALE_GREEN = "#BBF864"
PALE_BLUE = "#A2C4DA"
BRIGHT_BLUE = "#04BAE3"
ORANGE = "#FF8000"
DARK_ORANGE = "#E65C00"
LIGHT_ORANGE = "#FFAA3E"
PALE_ORANGE = "#F8C381"
GUAVA = "#FF4F40"
FUSCIA = "#E22EFF"
PALE_FUSCIA = "#DFA0E9"
PURPLE = "#AE37C1"
PALE_PURPLE = "#C3AACF"
COLORS = [BLU... |
2,509 | 38f41fa87230ddc0b3a8c411b4c569f59f0ea065 | from api import db
from api.models.author import AuthorModel
class QuoteModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey(AuthorModel.id))
quote = db.Column(db.String(255), unique=False)
rate = db.Column(db.Integer)
def __init__(self, au... |
2,510 | 91e1ac12ba99a8efd8f7f26310244d83bdd4aa52 | #!/usr/bin/python
##
# @file
# This file is part of SeisSol.
#
# @author Sebastian Rettenberger (rettenbs AT in.tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger,_M.Sc.)
#
# @section LICENSE
# Copyright (c) 2013, SeisSol Group
# All rights reserved.
#
# Redistribution and use in source and binary for... |
2,511 | fd907dbcea01679c08aeae6bcbf6e61786f40260 | """Test radix sort."""
import random
from collections import OrderedDict
from que_ import Queue
def test_stringify_nums():
"""."""
from radixsort import stringify_nums
nums = [1, 2, 3, 4, 5]
stringified_nums = stringify_nums(nums)
assert stringified_nums == ['1', '2', '3', '4', '5']
def test_wh... |
2,512 | 004a9cd0e459116bf3f88f3546ff4eded3dfb2a8 | import json
import struct
import pymel.core as pmc
import os.path
def exportVSSD(path, camName, wantTris=False, renderdata=None):
mainFileDict = {}
mainFilePath = path
mainFileStem = os.path.basename(path)[:-5]
mainFileDir = os.path.dirname(path)
resolution = pmc.ls('defaultResolution... |
2,513 | 8a0e781f29c426161240e33b9d2adc7537b3d352 | N,T=map(int,input().split())
nm=1000000
for i in range(N):
c,t=map(int,input().split())
if nm>c and T>=t:
nm=c
if nm==1000000:
print("TLE")
else:
print(nm)
|
2,514 | 03cc3bf37ea8d971550a89107161005901d842de | from typing import List
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
departCity = set()
destCity = []
for i in paths:
if i[1] not in departCity:
destCity.append(i[1])
if i[0] in destCity:
destCity.remove(i[0])
... |
2,515 | de2de26d0c82213393e8174d1144c3510c63b899 | import NLC
app = NLC.create_app()
if __name__ == '__main__':
app.run(port=NLC.port, debug=True)
|
2,516 | 8b4bd2d267f20775ee5d41f7fe9ef6f6eeab5bb0 | from scipy import misc
from math import exp
import tensorflow as tf
import timeit
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
IMAGE_WIDTH = 30
IMAGE_HEIGHT = 30
IMAGE_DEPTH = 3
IMAGE_PIXELS = IMAGE_WIDTH * IMAGE_HEIGHT
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], p... |
2,517 | 9ab119b32ceac370b744658e5fa679292609373a | def merge(items, temp, low, mid, high):
i = low
j = mid + 1
for k in range(low, high+1):
if i > mid:
# 왼쪽 리스트의 순회를 마쳤음
# 남은 오른쪽 리스트의 원소들은 모두 왼쪽 리스트 원소보다 작음
temp[k] = items[j]
# 뒤에 나머지는 정렬되어있으니 그대로 넣기
j += 1
elif j > high:
... |
2,518 | 8a2ab260f4758bcca7b1a68d1fb65b7eebab5533 | # coding:utf-8
class SpiderMiddlewares1(object):
def process_request(self, request):
print(u"SpiderMiddlewares1 process_request {}".format(request.url))
return request
def process_item(self, item):
print(u"SpiderMiddlewares1 process_item {}".format(item.data))
return item
cl... |
2,519 | 9c50a3abd353d5ba619eaa217dcc07ab76fb850c | from rest_framework import serializers
from books.models import Genres, Format, Book, Review, ExtraTableForPrice
class GenresSerializer(serializers.ModelSerializer):
class Meta:
model = Genres
fields = ('title', )
class PriceSerializer(serializers.ModelSerializer):
class Meta:
model... |
2,520 | 4bad45f8c135463fadea9b3eed52ab045a51e8db | '''
Дано предложение, в котором имеются буквы с и т. Определить, какая из них встречается
позже (при просмотре слова слева направо). Если таких букв несколько, то должны
учитываться последние из них. Оператор цикла с условием не использовать.
'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__'... |
2,521 | 3b531c5935f0be89536c95ff471f96b4249d951c | import logging
from sleekxmpp import ClientXMPP
from sleekxmpp.exceptions import IqError, IqTimeout
class EchoBot(ClientXMPP):
def __init__(self, jid, password):
ClientXMPP.__init__(self, jid, password)
self.add_event_handler("session_start", self.session_start)
self.register_plugin('xep_0... |
2,522 | 650f00dd9740d62546eb58724e6e5a74398b3e59 | from torch.utils.data import IterableDataset, DataLoader
from torch import nn
from torch.nn import functional as F
from triplet_training_generator import get_train_test_apikeys, training_generator
from pathlib import Path
from transformers import AutoModel
import torch
from tqdm import tqdm
import pandas as pd
MEMMAP_... |
2,523 | e2a50fbd277ab868fbe71f9ff113a68a30b9f893 | # from mini_imagenet_dataloader import MiniImageNetDataLoader
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from tqdm import tqdm
import torch.nn.functional as F
from torchmeta.utils.gradient_based import gradient_update_parameters
from libs.model... |
2,524 | 8c364a518ab615803ea99520e90ee1dd24d37a8c | import numpy as np
import os
pwd = os.path.dirname(os.path.realpath(__file__))
train_data = np.load(os.path.join(pwd, 'purchase2_train.npy'), allow_pickle=True)
test_data = np.load(os.path.join(pwd, 'purchase2_test.npy'), allow_pickle=True)
train_data = train_data.reshape((1,))[0]
test_data = test_data.reshape((1,))... |
2,525 | 358d4573ff386d6874d5bb5decfe71c71141bf1c | # %%
import numpy as np
from numpy import sin, cos, pi
import gym
import seagul.envs
from seagul.integration import rk4,euler
from control import lqr, ctrb
from torch.multiprocessing import Pool
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.use('Qt5Agg')
import time
global_start = time.time()
# %%
... |
2,526 | 3086f62d4057812fc7fb4e21a18bc7d0ba786865 | from numpy import *
import KNN_1
import KNN_3
import KNN_suanfa as clf
def datingClassTest():
horatio = 0.1
data, datalabels = KNN_1.filel2matrix("datingTestSet2.txt")
normMat = KNN_3.autoNorm(data)
ml = normMat.shape[0]
numTestset = int(ml*horatio)
errorcount = 0
a=clf.classify0(normMat[0:n... |
2,527 | f928eb34155046107c99db8ded11747d5960c767 | # -*- coding:utf-8 -*-
import sys
import time
class ProgressBar:
@staticmethod
def progress_test():
bar_length = 100
for percent in range(0, 101):
hashes = '#' * int(percent / 100.0 * bar_length)
spaces = ' ' * (bar_length - len(hashes))
sys.stdout.write("\... |
2,528 | 51b28650f8ae6cbda3d81695acd27744e9bfebd1 | import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt, ticker
from analysis.report import lib_plot
from analysis.report.lib_agent import known_agents
from analysis.report.lib_fmt import fmt_thousands
from lib_db import DBClient
def main(db_client: DBClient):
sns.set_th... |
2,529 | bd202e18cb98efc2b62ce4670fadcf70c35a33cb | #!/usr/bin/python3
# The uploader service listens for connections from localhost on port 3961.
# It expects a JSON object on a line by itself as the request. It responds
# with another JSON object on a line by itself, then closes the connection.
# Atropine CGI scripts can send requests to this service to tell it to:
#... |
2,530 | 2b141f12bec2006e496bf58a3fcb0167c95ab3b6 | from datetime import datetime, timezone, timedelta
import json
import urllib.request
from mysql_dbcon import Connection
from model import SlackChannel, SlackUser, SlackMessage
# TODO set timezone at config
jst = timezone(timedelta(hours=+9), 'JST')
def get_new_message_list(channel_id: int):
with Connection() a... |
2,531 | fe63d9b0939bc91d2da14e4d966b33575eab5394 | from sklearn.model_selection import train_test_split
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.metrics.cluster import homogeneity_score, completeness_score, v_measure_score
from sklearn import datasets
from random import shuffle
import os
import matplotlib
matplotlib.use('Agg')
imp... |
2,532 | a7deec1693c411988445528dceb602bf69e47d21 | from source import tools, setup
if __name__ == '__main__':
game = tools.Game(setup.STATE_DICT, 'menu')
game.run()
|
2,533 | 8f709af924820c77290f97731d9f96258c3db095 | from scrapy import Spider, Request
from urllib.parse import quote
from Product.items import ProductItem
class TaobaoSpider(Spider):
name = 'taobao'
allowed_domains = ['www.taobao.com']
start_urls = ['http://www.taobao.com/']
def parse(self, response, **kwargs):
pass
|
2,534 | bb335187dc61fae049ca4a9a55a93f856b3c7822 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import keras
from keras.layers import Dense, Dropout, Input, Embedding, LSTM, Reshape, CuDNNLSTM
from keras.models import Model,Sequential
from keras.da... |
2,535 | b6adb956aed934451fc21e51663be36d08c5b645 | import matplotlib.pyplot as plt
import matplotlib
import matplotlib.colors as colors
import matplotlib.cm as cm
def plot_hist(data_list):
plt.hist(data_list, bins=500)
plt.show()
return
def compare_hits_plot(np_array, compare=False):
if compare:
clist = list(np_array[:,2])
minima, maxima = ... |
2,536 | 44c4a1f4b32b45fd95eb8b0a42a718d05d967e04 | from math import log
result = []
formula = int(input("For exit press 0\nChoose the formula #1 #2 #3: "))
while (formula >= 0) and (formula <= 3):
a = float(input("Enter a:"))
min_x = float(input("Enter minx:"))
max_x = float(input("Enter maxx:"))
step = int(input("Enter steps:"))
x = min_x
if... |
2,537 | 661f94f5770df1026352ee344d0006466662bb3c | ###############################################################
# Yolanda Gunter
# Lab 4
# My program uses decisions, repetition, functions, files, lists
# and exception handling that will get the input from a file to
# run program that asks User for current date, reads a contact file
# list that contains... |
2,538 | 0016e38d39ed2a4c7a75bed103bc47a5b6fd0e8c | import numpy as np
import random
import sys
import canton as ct
from canton import *
import tensorflow as tf
time_steps = 16
def get_text_data(filename):
import codecs
with open(filename,'rb') as f:
text = f.read()
length = len(text)
print('got corpus length:', length)
return text
def mod... |
2,539 | d44c76ff7e94bea6e03324c45d139602c724c7be | import re
def password_validation(password):
return bool(re.search("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$", password)) |
2,540 | b27e89ff799f26b87a61254e1c4a5f782fcbe605 | class Model:
def derivativesDependsOn(self, models):
return []
def derivedVariablesDependsOn(self, models):
return []
def initializeSimplifiedModel(self, timeHistory, stateHistory, derivedVariablesHistory):
return False
def computeSimplifiedState(self, args, time):
return []
def comput... |
2,541 | 638e21e1eb1e2e14244628260d9c7ac179983721 | s=input()
count=0
while(len(s)!=1):
count+=1
a=0
for i in range(len(s)):
a+=int(s[i])
s=str(a)
print(count)
|
2,542 | 332e2945e34c861b2132f6b42ef59416a38455a5 | import unittest
import json
from app.tests.base import BaseTestCase
from app import db
from app.tests.utils import create_room, create_simple_device, create_rgb_device
class TestRoomService(BaseTestCase):
"""Test the room service"""
def test_get_room(self):
room = create_room()
with self.client:
response =... |
2,543 | 973fc3a973d952cb0f192221dfda63e255e4a8a0 | import sys
import queue as q
from utils import *
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lines = sys.stdin.readlines()
i_max = len(lines)
j_max = len(lines[0])
deltas = [
((0, 0), (0, 1), (0, 2)),
((0, 1), (0, 2), (0, 0)),
((0, 0), (1, 0), (2, 0)),
((1, 0), (2, 0), (0, 0)),
]
p... |
2,544 | d3382ead1d98ba2fb15fe3ea277430f1bb07131c | l,w,h=map(int,input().split())
TSA = 2*(l*w + w*h + h*l)
V = l*w*h
print(TSA,V)
|
2,545 | addf92a3d4060fa9464a802a4a4378cf9eeadde4 | # -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
class CreateCertificateRequest(TeaModel):
def __init__(self, domain=None, certificate=None, private_key=None, certificate_name=None, instance_id=None):
self.domain = domain # type: str
sel... |
2,546 | 9976eb2dd84448b37b81629d352f4a7490ab2316 | import argparse
import sys
def get_precision_values(input_file):
prec_values = []
all_precs = []
means = []
medians = []
methods = []
with open(input_file) as lines:
for line in lines:
if "RESULTS_AGGREGATION" in line:
tokens = line.strip().split(',')
... |
2,547 | 895ece0b8d45cd64e43f8ddc54824f7647254185 | from flask import Flask
from flask import render_template
import datetime
from person import Person
import requests
from post import Post
app = Flask(__name__)
all_posts = all_posts = requests.get(
"https://api.npoint.io/5abcca6f4e39b4955965").json()
post_objects = []
for post in all_posts:
post_obj = Post(po... |
2,548 | 6097840cdf4b42efaca3e197f88703d927abe889 | # written by Mohammad Shahrad @UBC
RECENT_NEWS_COUNT = 5
import json
with open("./all-news.json") as f:
allNews = json.load(f)
recent_news_counter = 0
with open("./recent-news.js", "w") as f:
f.write("document.write('\\\n")
f.write("<ul>\\\n")
for value in allNews.values():
f.write("<li>\\\n... |
2,549 | 3bc009271c7dd34ad09bcef81214387b63dfac59 |
#from tkinter import Tk, Text, INSERT
import mnemonicos as mne
class Ensambler(object):
def __init__(self, fileName):
#Nombre del archivo
self.fileName = fileName
#Lineas del Archivo
self.fileLines = []
#Contador de Localidades
self.cl = 0
#Tamaño
self.size = 0
#Opcode
self.code = ""
#Intr... |
2,550 | 380a28958fc6d1b403b29ede229860bf5f709572 | import time
import unittest
from unittest import TestCase
from selenium import webdriver
from simon.accounts.pages import LoginPage
from simon.header.pages import HeaderPage
from simon.pages import BasePage
class RegistrationBaseTestCase(TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
... |
2,551 | 486cfc4bb4b46d78715b11cba44656e8ba077c9b | # -*- coding: utf-8 -*-
import unittest
import torch
from pythainlp.transliterate import romanize, transliterate, pronunciate, puan
from pythainlp.transliterate.ipa import trans_list, xsampa_list
from pythainlp.transliterate.thai2rom import ThaiTransliterator
from pythainlp.corpus import remove
_BASIC_TESTS = {
... |
2,552 | 38c78a51a50ee9844aec8b8cdcdd42b858748518 | from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy
from django.utils import timezone
from time import time
import json
from .models import Attendance, Disciple
from users.models imp... |
2,553 | 7644dcd956e1ad179f42e44870864386744c6cdf | from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import AuthUser
class SignUpForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
pas... |
2,554 | 4d58926e812789768fdf5be59bd54f9b66850e57 | """
The epitome package is a set of command-line tools for analyzing MRI data, and a
set of scriptuit modules for stitching them (and others) together.
"""
from . import utilities
from . import stats
from . import signal
from . import plot
from . import docopt
|
2,555 | f59db28b669a41051cc6d0d4b8e14d1c7b0edd11 | import user
# or from user import User
from post import Post
app_user_one = user.User("rr@gg.com", "Riks R", "ppp1", "student")
app_user_one.get_user_info()
app_user_one.change_status("in job market")
app_user_one.get_user_info()
app_user_two = user.User("z43@gg.com", "Bobby L", "zz1", "student")
app_user_two.get_us... |
2,556 | a65ab0faf08c13f007a132fb92f358a35834fdb7 | N = int(input())
K = int(input())
xs = list(map(int, input().split()))
dist = 0
for x in xs:
dist += min(x, K-x)
print(dist*2) |
2,557 | 9f8065dfdfe07985244e18d92b59e1c045388a72 | import turtle
def distance(x1, y1, x2, y2):
return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5
x1, y1 = eval(input("Enter x1 and y1 for point 1: "))
x2, y2 = eval(input("Enter x2 and y2 for point 2: "))
distanceBetweenPoints = distance(x1, y1, x2, y2)
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown... |
2,558 | e73c4a99c421b3eca08c941ff1f83cb03faee97d | from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import Integer, Text, String, DateTime, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Model = declarative_base()
class User(Model):
__tablename__ = "users"
id = Column(Integer,
... |
2,559 | a6eab1e5e7985de917d707c904fcd90f223c108c | #!/home/liud/anaconda3/envs/python/bin/python
# -*- coding: utf-8 -*-
'''
线性回归
公式:W = 1/(xTx) * xT * y
'''
#导入的包
import numpy as np
from numpy import linalg
from numpy import corrcoef
from sklearn import linear_model
import matplotlib.pyplot as plt
#加载数据
def loadDataSet(filename):
xList = []
yList = []
with open(... |
2,560 | 0ebf5646ee9693b7d0c1de61436e05b3725b2c9f | import psycopg2
host = "datavis.cauuh8vzeelb.us-east-1.rds.amazonaws.com"
database = "top5"
user = "teamwonder"
password = "visproject"
Gentrifying = [10002,10003,10009,10026,10027,10029,10030,10031,10032,10033,10034,10035,10037,10039,10040,10454,10455,10456,10457,10458,10459,10460,10474,11102,11103,11105,11106,11206... |
2,561 | e8ba1ae98b247eaf90d83339e5fdc27287a70c73 | from dependency_injector import containers, providers
from src.repositories import MemcachedRepository
from src.services import FibonacciService
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
cache_repository = providers.Singleton(MemcachedRepository,
... |
2,562 | 99c60befed32a9aa80b6e66b682d9f475e05a8d1 | import gc
import network
import lib.gate as gate
import time
from micropython import const
from ubluetooth import BLE
import lib.webserver as webserver
bt = BLE()
bt.active(True)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
def byteToMac(addr):
m = memoryview(addr)
a = "{:0>2X}:{:0>2... |
2,563 | d932ab84848c9a8ca8bb23a57424b8f6190b6260 | from base_plugin import *
from plugin_utils import *
from datetime import datetime
import time
class LogPlugin(Plugin):
def initialize(self):
self.add_trigger(on_message)
self.add_command("!chatsearch", self.search)
self.add_command("!chatreplay", self.replay)
def run(self, message):
append_to_file(str(... |
2,564 | 40b3cacf55f6c5056c3541d70d8b2c0e2cc7d01b | from typing import List
class NURBS:
def __init__(self, degree: int) -> None:
self._degree = degree
self._points = [] # type: List[complex]
self._weights = [] # type: List[float]
self._knots = [] # type: List[float]
def addPoint(self, p: complex) -> None:
self._poin... |
2,565 | 426002bf900e23fd9b1d32c484350ac854228459 | # -*- coding: utf-8 -*-
"""Very basic codec tests.
:copyright: the translitcodec authors and developers, see AUTHORS.
:license: MIT, see LICENSE for more details.
"""
import codecs
import translitcodec
data = u'£ ☹ wøóf méåw'
def test_default():
assert codecs.encode(data, 'transliterate') == u'GBP :-( woof mea... |
2,566 | 6ff4aff5811d2bd7ad150d7e8f925308d120ef74 | # Imports
import os
from flask import Flask, redirect, render_template, url_for, request, flash
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
# Import - Database
from flask_sqlalchemy import SQLAlchemy
# Import - Models
from werkzeug.security import generate_password_hash... |
2,567 | b1fe7e318c361930c8ad00758bcb86597fd8f3bd | '''''''''''''''''''''''''''''
> Filename: lv6.py
> Author: Kadrick, BoGwon Kang
> Created at: 2021/10/11 16:07
> Description: zip
'''''''''''''''''''''''''''''
import zipfile
import re
# open zipfile
zfile = zipfile.ZipFile('./channel.zip')
# check list
'''
print(zfile.namelist())
print(zfile.read("readme.txt"))
prin... |
2,568 | 0e1ea8c7fba90c1b5d18eaa399b91f237d4defee | count = 0
maximum = -1
m = -1
while m != 0:
m = int(input())
if m > maximum:
maximum = m
count = 1
elif m == maximum:
count += 1
print(count)
|
2,569 | b3f376f4aec81cae853f996a74062e32bb4a8fa3 | import botocore
class s3Obj:
def __init__(self, name, bucket_name, size, last_modified, storage_class):
self.name = name
self.size = size
self.last_modified = last_modified
self.storage_class = storage_class
self.bucket_name = bucket_name
self.acl = []
... |
2,570 | 8c6b7032c85354740d59aa91108ad8b5279e1d45 | #! /usr/bin/env python
t = int(raw_input())
for i in xrange(1, t+1):
N = raw_input()
N1 = N
track = set()
if N == '0':
print "Case #%s: " % i + "INSOMNIA"
continue
count = 2
while len(track) !=10:
temp = set(x for x in N1)
track = temp | track
N1 = str(co... |
2,571 | f8b04f374e1c55d4985be793939f0ff9393c29e0 | '''
Given []int, most mostCompetitive subsequence is
a sublist of nums.
So we calculate a score, score is ∀ x ∈ nums, score += x_n - x_n-1
You can remove as many elements are you need to.
What is the mostCompetitive subsequence that you can come up with?
[1,3,5]
[1,3,4] ← More competitive
[1,2,5] ← More competiti... |
2,572 | 4411c81351ac76d72512faaa6b498cd577815691 | # 把函数视作对象
def factorial(n):
"""returns n!"""
return 1 if n < 2 else n * factorial(n - 1)
fact = factorial
print(list(map(fact, range(6)))) # 构建 0! 和 5! 的一个阶乘列表。
print([fact(n) for n in range(6)]) # 使用列表推导执行相同的操作。
# filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
# 该接收两个参数,第... |
2,573 | 3ab1de77147f6abfabeea10f2a4e85686edffd6f | # Generated by Django 3.1.7 on 2021-02-24 05:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('autotasks', '0017_auto_20210210_1512'),
]
operations = [
migrations.AddField(
model_name='automatedtask',
name='run_... |
2,574 | d1ee33ce6fb071aae800b0597a09e7039a209ec8 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 20:59:36 2021
@author: Abeg
"""
#factorial using recursion
"""def factorial(n):
if n==0 or n==1:
return 1
elif n==2:
return n
else:
return n*factorial(n-1)
n=int(input("enter the no"))
print(factorial(n))"""
#fibonancci using recursi... |
2,575 | 7277b045f85d58383f26ab0d3299feb166f45e36 | while True:
print("Light Levels:" + input.light_level())
if input.light_level() < 6:
light.set_all(light.rgb(255, 0, 255))
elif input.light_level() < 13:
light.set_all(light.rgb(255, 0, 0))
else:
light.clear()
|
2,576 | ee0f90b84df73ae5783ca0b8a52fe6fe9c979f15 | from flask import request, Flask
import lock, shelve
app = Flask(__name__)
@app.route("/unlock")
def web_unlock():
if not (request.args.get("token") and request.args.get("state")):
return "Error"
else:
with shelve.open("Settings.conf") as settings:
if "token" in settings:
... |
2,577 | 11dfb09286b8a5742550b5300c776ed82e69ead5 | from flask import request,Flask, render_template
from bs4 import BeautifulSoup as bs
from urllib.request import Request,urlopen
import re
app = Flask(__name__)
@app.route('/')
def addRegion():
return render_template('Website WordCount.html')
@app.route('/output_data', methods=['POST','GET'])
def output_data():
... |
2,578 | 74f3b4001a0520a25a314ff537719b679ba0fca4 | """ Soil and water decomposition rates """
import math
from water_balance import WaterBalance
from utilities import float_eq, float_lt, float_le, float_gt, float_ge, clip
__author__ = "Martin De Kauwe"
__version__ = "1.0 (25.02.2011)"
__email__ = "mdekauwe@gmail.com"
class DecompFactors(object):
""" Calcula... |
2,579 | 19ab44cec863560513aadd88b5fd4bb40f75e371 | import unittest
import brainfuck
import sys
from StringIO import StringIO
def run_program(program, input = None):
old_stdout = sys.stdout
old_stdin = sys.stdin
try:
out = StringIO()
sys.stdout = out
if input is not None:
input = StringIO(input)
sys.stdin = ... |
2,580 | a7e2b016131dfdb75e537e86875e1b2f19fb3d9d | import matplotlib.pyplot as plt
import numpy as np
import unittest
from ema_workbench.analysis import clusterer
from test import utilities
class ClusterTestCase(unittest.TestCase):
def test_cluster(self):
n = 10
experiments, outcomes = utilities.load_flu_data()
data = outcomes["infected f... |
2,581 | 538e582df7bfcf281973a5296adc14ca067be0a5 | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
from django.contrib import admin
from magmag_core.app import application
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from mag... |
2,582 | e3631a2a003f98fbf05c45a019250e76d3366949 | from model import WSD
from data_preprocessing import load_dataset, create_mapping_dictionary, reload_word_mapping,get_bn2wn,get_bn2wndomains, get_bn2lex
from typing import List, Dict, Tuple
from prova import convert_sentence_to_features_no_padding
import numpy as np
import os
from nltk.corpus import wordnet
mfs_count... |
2,583 | 7bb9455e6f0c15ab0be6963cff06ff41df73e6e0 | import json
import os
from six import iteritems
from ..exceptions import ColinConfigException
from ..constant import CONFIG_DIRECTORY, JSON
from ..loader import load_check_implementation
from ..target import is_compatible
class Config(object):
def __init__(self, name=None):
"""
Load config for ... |
2,584 | de003440be513d53b87f526ea95c0fbbc4a9f66f | import os
def savelesson(text):
os.path.expanduser("~/.buzzers/lessons")
def getlessonlist():
path = os.path.expanduser("~/.buzzers")
dirs = os.walk(os.path.expanduser("~/.buzzers/lessons"))
#"/home/loadquo/files/lhsgghc/Programs/PCSoftware/src/admin/lessons")
lessons = []
for root, d, fs in dirs:
... |
2,585 | 1a979933eb02e9d12dc034021448cbade59abc48 | '''
@name: ros_env_img.py
@brief: This (abstract) class is a simulation environment wrapper for
the X-Image Representation.
@author: Ronja Gueldenring
@version: 3.5
@date: 2019/04/05
'''
# python relevant
import numpy as np
# custom classes
from rl_agent.env_wra... |
2,586 | 74e70056ddfd8963a254f1a789a9058554c5489e | import torch.nn as nn
from transformers import BertModel
class BertBasedTODModel(nn.Module):
def __init__(self, bert_type, num_intent_labels, num_slot_labels):
super(BertBasedTODModel, self).__init__()
self.bert_model = BertModel.from_pretrained(bert_type)
self.num_intent_labels = num_inte... |
2,587 | 6050e83e73faaf40cbd5455efd3ad01e4e131188 | a=int(input())
s=0
t=0
while(a!=0):
t=a%10
s=s+t
a=a//10
print(s)
|
2,588 | 700d876dd45548b74b563ed86f8124fa666e1739 | a=10
b=20
c=400
d=100
e=500
f=30
z=a+b+c+d+e+f
print "The total sum is",z
print "variable d added"
print "Variable e added"
print "Variable f is equal to 30"
print "You are coming from test branch"
print "Your are very new in this branch"
|
2,589 | 9cb4e550a0d19b44ec8357882f353b04748b213b | # -*- coding: utf-8 -*-
class Config(object):
def __init__(self):
self.config_dict = {
"data_path": {
# "vocab_path": "../data/cnews/cnews.vocab.txt",
"vocab_path": "../data/rumor/cnews.vocab.txt",
# "trainingSet_path": "../data/cnews/cnews.trai... |
2,590 | 2aee4af2e5a5c3f59dde4d9dd46f8d124a32fb27 | """
Copyright (C) Adrian Herrera, 2017
You will need to install r2pipe and pydot:
```
pip install r2pipe pydot
```
"""
from __future__ import print_function
import glob
import json
import os
import pydot
import r2pipe
import s2e_web.S2E_settings as S2E_settings
def function_addrs(r2):
"""
Yield a list of... |
2,591 | 779ef8942bfb55bf017a8da9dfe34c03ac574a9a | import unittest
import math
from python.src.sort.insertion import Insertion
from python.src.sort.selection import Selection
from python.src.sort.shell import Shell
from python.test.util.utilities import Utilities
class ElementarySortTest(unittest.TestCase):
def setUp(self):
self.n = 1000
def test_i... |
2,592 | c8aa93a33a6513129b4980180c4eb8d5d5eb3b5b |
from django.contrib import admin
from django.urls import path
from . import views
from .views import index
from .views import Login , logout
from .views import CheckOut
urlpatterns = [
path("",views.index, name="index"),
path('login', Login.as_view(), name='login'),
path('logout',... |
2,593 | 0ae9ad7af26e3d19f2d3967c02611503c32aea70 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Brandon Bennett <bennetb@gmail.com>
#
# Send a notification via notifyserver (https://github.com/nemith/notifyserver)
# on highlight/private message or new DCC.
#
# History:
#
# 2015-02-07, Brandon Bennett <bennetb@gmail.com>:
# version 0.1: initial release
#
SCRIPT... |
2,594 | 9731f45b19d40a031216f8a430c09764fd34e984 | from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from .models import Blog, BlogType
from django.conf import settings
from read_statistics.utils import read_statistics_once_read
from user.forms import LoginForm
# Create your views here.
#分页函数
def get_blogs_common_data(r... |
2,595 | db684185c2b0a26cb101dc40090c84b64c554eeb | #! python3
import os
import shutil
import re
import argparse
def create_test_file(filename):
with open(filename, "w") as f:
f.write("foobar")
def create_test_files(test_dir, file_prefix):
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
os.mkdir(test_dir)
for i in range(1, 10):
... |
2,596 | a6ee2be7bed59b419fa66fd6cfe4b5fff3fac260 | import os
import sys
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
setup(
name='stripe-requests',
version='1.9.1-dev',
description='Stripe python bindings using requests',
author='Allan Lei',
author_email='allanlei@hel... |
2,597 | 8edca4c50e48734073e80de85088964837247696 | from django.shortcuts import render
from rest_framework.response import Response
from .serializers import *
from rest_framework import generics, status
class HistoryMyList(generics.ListCreateAPIView):
serializer_class = HistorySer
queryset = History.objects.all()
class HistoryListView(generics.GenericAPIView... |
2,598 | 19f17044d48c8cc0f9d366cde7edc846ff343462 | from multiprocessing import Pool
from pathlib import Path
import os
import re
import json
import string
import math
import GLOBALS
stopWords = {"a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren't",
"as", "at", "be", "because", "been", "before", "being", "bel... |
2,599 | 5f242ae801a239dde6a22e4fb68b4ef4b2459be6 | import Libcplx as lc
# 1.Adición de vectores complejos
def adVector(v, w):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxsum(v[k], w[k])]
return r
# 2.Inverso (aditivo) de un vector complejo
def invVector(v):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxproduct((... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.