index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
991,700 | 9242c079a1cf1402c284caa3d78409c25ba7c3ed | def singleNonDuplicate(self, nums: List[int]) -> int:
left = 0
right = len(nums)-1
while(left<right):
mid = (left + right)//2
check_if_halves_are_even = (right-mid) % 2 == 0
if nums[mid+1] == nums[mid]: #if pair is on the right sid... |
991,701 | 1c63b9ae647c875d74e932532d5bd78a0d92cb8c | #from urllib2 import Request, urlopen, URLError
import requests
#import gdax
# get buy volume increase in percent
# get sell volume increase in percent
# get price of Sell/buy order
class PublicClient(object):
def __init__(self, api_url = 'https://api.gdax.com/'):
self.url = api_url.rstrip('/')
def get_product... |
991,702 | a625d27c899a7734384693a5247154bf631136af | import sys
input = lambda:sys.stdin.readline().strip()
def func(cur, bit):
if cur==11:
return 0
ret = 0
for i in range(11):
if arr[cur][i] and bit ^ 1<<i:
ret = max(ret, func(cur+1, bit ^ 1<<i)+arr[cur][i])
return ret
for c in range(int(input())):
arr = [[] for i in ran... |
991,703 | 3909df336678900024a6dbdfccff6d9f58e17249 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import os
import contextlib
import shutil
import tempfile
import time
@contextlib.contextmanager
def file_locker(path_in, path_repl, locker_path = None):
in_path = os.path.split(path_repl)
#~ mask_file = os.path.join(path_repl, in_path[-1])
mask_file = path_... |
991,704 | d5fc023a2121816e75f71fe4cd9c0cc1bd6a3f13 | class CisneiNegro:
def __len__(self):
return 42
Livro = CisneiNegro()
print(len(Livro))
Nome = 'Dikson'
listas = [12,34,40,55]
DICT = {"Dikson": 34, "Luciene": 43, "Vó": 83}
print("Nome",len(Nome))
print("List",len(listas))
print("Dicio",len(DICT))
|
991,705 | 177679098f61f5dcc04416d50e371565dd2511a6 | class Solution:
def lengthLongestPath(self, input: str) -> int:
path = []
ans = 0
for name in input.split("\n"):
l = 0
for c in name:
if c == "\t":
l += 1
else:
break
if len(path) > l:... |
991,706 | 72b20fd98b26a86aaaacf719a10fb5698f60952e | from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
mobile = db.Column(db.String(), unique=True)
email_address = db.Column(db.String(), unique=True)
password = db.Column(db.TEXT())
is_active = db.Column(db.Boolean(), default=True)... |
991,707 | 4ad47bda7b603fe768d6f3730b0d130cda13a4f9 | FILENAME_BUILDNO = 'VERSION'
FILENAME_VERSION_H = 'src/version.h'
version = '0.1.'
import datetime
from pathlib import Path
def get_active_branch_name():
head_dir = Path(".") / ".git" / "HEAD"
with head_dir.open("r") as f: content = f.read().splitlines()
for line in content:
if line[0:4] == "ref:":
re... |
991,708 | b9dcc23814c7000a55e67eaf5ce395de64fd3ef5 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SSOSession'
db.create_table('sso_session', (
... |
991,709 | e6b550a0a469ff8ccca8a9e517fe730f2cb8552a | # -*- coding: utf-8 -*-
# @Time : 2019/4/10 22:21
# @Author : tuihou
# @File : serializers.py
from rest_framework import serializers
from .models import Project, Step, Case, Variables, API, Category, Config, Classify, TestSuite, Report, \
ReportCase, ReportDetail
from drf_writable_nested imp... |
991,710 | 7f6c6a2471f5874fc472430cef77cd5eb99fe11f | from rc4 import rc4
chave = input("Chave: ")
texto = input("Texto: ")
texto_enc = rc4(texto, chave)
print("Resultado da encriptação: ", texto_enc)
print("-------------")
print("Resultado da decriptação: ", rc4(texto_enc, chave))
|
991,711 | bd6a341a4eae0d0309ca1ef73954b2e74463c8f4 | from unittest import TestCase
class TestRecursion(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_reverse_a_list(self):
from kata.katas import reverse_a_list
self.assertEqual(reverse_a_list([1,2,3,4,5]), [5,4,3,2,1])
self.assertEqual(reverse_a_... |
991,712 | cf01aa52f04a01df4a3de439ea58a95b773abfd9 | """
Name: problem1.py
Purpose: This problem requires a celsius to fahrenheit converter to help the user
understand the amount of degrees celsius to fahrenheit
Author: Tuczynski.S
Date: 07/12/2020
"""
#inputs user data for the amount of degrees celsius
print("--- Welcome to the online celsius to fahrenheit conv... |
991,713 | d669c7beb2016954085249c9844123c54d5c7886 | # ! /usr/bin/env python
from random import randint
SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
ACTION_ONE_WORD = 1
ACTION_MAX = 2
ACTION_WORD_FROM_FILE = 3
class Scrabble:
def __init__(self, scrabbles_scores)... |
991,714 | 49ee0c44d5ee3fc381cbf745fe67678f29bbe53c | # Generated by Django 3.0.6 on 2020-12-22 15:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mi_CandyMuebles', '0006_pedido_tipoevento_idtipodeevento'),
]
operations = [
migrations.AlterModelOptions(
name='ti... |
991,715 | 9e3ef0f92a36edb4751ea41a5ddf95aa0e25d64a | #coding:utf8
#只是切割掉 图片的底端空白
#切割掉 左右两端 对称的空白
#吸血鬼行走文件夹名字不对
#泰坦图片左侧存在1像素的白线 需要先切割掉 再crop
import os
import Image
import sys
import ImageOps
import json
#读取士兵图片的边沿 根据士兵 图片 切割 特征色图片的边沿
fi = open('../mb.txt', 'r')
fi = json.loads(fi.read())
#mId aId
print sys.argv
b = int(sys.argv[1])
e = int(sys.argv[2])
n = int(sys.argv... |
991,716 | eabc1496ee9c1ca75b20758ebbfaf8fb64b73480 | from output.models.nist_data.list_pkg.short.schema_instance.nistschema_sv_iv_list_short_length_2_xsd.nistschema_sv_iv_list_short_length_2 import NistschemaSvIvListShortLength2
obj = NistschemaSvIvListShortLength2(
value=[
31514,
31646,
31122,
31422,
31331,
31643,
... |
991,717 | 51361ae6ab76a15e2db7fbc27f3e1ca7bca99f6b | import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# from pylab import rcParams
import scipy.stats as stats
from scipy.stats import chi2
import time,tqdm
from imblearn.over_sampling import SMOTE
import lightgbm as lgb
from sklearn.model_selection import StratifiedKFold
from s... |
991,718 | aa9e38ad3e2964924a8d1beabdd9a18fe28586a7 | import sys
import re
from package import func_wiki
args = sys.argv
args.append('ch03/ch03/jawiki-country.json.gz')
def main():
pattern = r'\[\[ファイル:(.+?)\|'
result = '\n'.join(re.findall(pattern, func_wiki.read_wiki(args[1], 'イギリス')))
print(result)
if __name__ == '__main__':
main()
|
991,719 | 5e97637819494ac1924c84f29066997dad5b1876 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import glob
import os.path
if __name__ == '__main__':
suite = unittest.TestSuite()
for i in glob.glob('test_*.py'):
module = __import__(os.path.splitext(i)[0])
if hasattr(module, 'get_suite'):
suite.addTest(module.get_su... |
991,720 | 75cae99c8a6aac965247d961b182c3b6114bd171 | import numpy as np
import scipy.signal as signal
def gauss_kern(sigma,h):
""" Returns a normalized 2D gauss kernel array for convolutions """
h1 = h
h2 = h
x, y = np.mgrid[0:h2, 0:h1]
x = x-h2/2
y = y-h1/2
# sigma = 10.0
g = np.exp( -( x**2 + y**2 ) / (2*sigma**2) )
return g / g.su... |
991,721 | 8852cc2a2261fe854ef4b7784f63b77f598a0526 | # Main program.
from . import task_generator
from . import dispatcher
from . import scheduler
from . import net_graph
# Create a network graph.
ntg = net_graph.NetGraph()
# Create a scheduler.
# Create a task generator.
# Create a dispatcher.
# Main loop
|
991,722 | 958ca864f28f9e8f9c91a0ddf34891cf27b99530 | import collections
S=str(input())
cc=collections.Counter(S)
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','m','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(26):
if cc[alphabet[i]]==0:
print(alphabet[i])
exit()
if i==25:
print('None')
exit()
|
991,723 | 08f0f11a1d4aea0fda0ac25b3e54677dcfb6594a | # Generate an ANN structure for a given data set.
import os
import cProfile
import argparse
import logging
import sys
import config
import annfab.storage
import annfab.hasher
import annfab.utils
try:
import annfab.batch_hasher
disable_batch = False
except ImportError as e:
logging.error("Cannot import an... |
991,724 | 5fbe6ea85039a217739ed36b01c738d8dfa03b62 | # Perform substitutions
while NOUN_PLACEHOLDER in story:
new_word = random.choice(NOUNS)
story = story.replace(NOUN_PLACEHOLDER, new_word, 1)
while ADJECTIVE_PLACEHOLDER in story:
new_word = random.choice(ADJECTIVES)
story = story.replace(ADJECTIVE_PLACEHOLDER, new_word, 1)
while VERB_PLACEHOLDER in sto... |
991,725 | c4f2103cb606f539e57ae2912f9714e881711ce9 | #!/usr/bin/env python3
"""
Example of how to use function_exec_manager.py
"""
import time
from pybullet_ros.function_exec_manager import FuncExecManager
class Plugin1:
def __init__(self, pybullet, robot, **kargs):
print('executing plugin 1 constructor')
def execute(self):
print('calling plug... |
991,726 | 0762438871c64e340c7db50f054785f58c1fdd25 |
# interfile - Interfile read and write
# Stefano Pedemonte
# Aalto University, School of Science, Helsinki
# Oct 2013, Helsinki
from __future__ import absolute_import, print_function
import unittest
from .. import Interfile
class TestInterfile(unittest.TestCase):
"""Sequence of tests for module interfile. ""... |
991,727 | ec7843a8a78eaac9b8955bc7fbe80266d7f0d06e | from django.utils.translation import ugettext_lazy as _
from feincms.content.richtext.models import RichTextContent
from feincms.module.page.models import Page
Page.register_extensions(
'pagepermissions.extension'
)
Page.register_templates({
'title': _('Standard template'),
'path': 'base.html',
'reg... |
991,728 | 067823bf7ec5e25121d8b237a5f51f0313c44f79 |
# coding: utf-8
# # Q3_P1
#
# 1.Use ‘cricket_matches’ data set.
#
# 2.Calculate the average score for each team which host the game and win the game.
#
# 3.Remember that if a team hosts a game and wins the game, their score can be innings_1 runs or innings_2 runs. You have to check if the host team won the game,... |
991,729 | a8718ebd62900eb342c7c46b80ac7619ee450e50 |
# William Kavanagh, August 2019
# Extended CSG - strategy generator for 5c-3at RPGLite
full_name = {"K":"Knight","A":"Archer","W":"Wizard","R":"Rogue","H":"Healer"}
chars = ["K","A","W","R","H"]
def choice_available(state_desc):
# if there is more than one viable action: return True, else return False.
if s... |
991,730 | 9bd50c2e8e95addbd3009fcc3a9a0093065be924 | '''
Created on Dec 2, 2012
@author: adewinter
App meant to create a generic multiplier of two numbers. Using home brewed Genetic Algorithm creator thing.
'''
from gene import *
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def evaluate_candidate(gene):
"""
Returns the score of ... |
991,731 | 70b6b562b02999643f0f248aea5a91ca474c6000 | import requests
from bs4 import BeautifulSoup
import smtplib
import time
import sys
#URL = 'https://www.amazon.de/720%C2%B0DGREE-Trinkflasche-uberBottle-Wasserflasche-Auslaufsicher/dp/B07H7VGFSR?pf_rd_p=93ca5e1f-c180-59f3-a38f-564b8302b2de&pf_rd_r=TFG7VS6T3HD1SBN6EXMP&pd_rd_wg=mgYUE&ref_=pd_gw_ri&pd_rd_w=SNr3w&pd_rd_... |
991,732 | d0f66f7130346b9e333e4a82b7c69b873fedc5d4 | from flask import Flask, render_template
app=Flask(__name__)
@app.route('/')
def home():
return render_template('site.html')
@app.route('/mysite2.html')
def about():
return render_template('mysite2.html')
|
991,733 | ba371e6b60127ba78b3f32727263cfe4bdeea04b | # Enter your code here. Read input from STDIN. Print output to STDOUT
import numpy
n = map(int, raw_input().split())
print numpy.zeros(n, int), "\n", numpy.ones(n, int)
|
991,734 | 3329e11822ed577e6c83d676bc4ecc64c92d230e | """
Django settings for django_channels2 project.
"""
SECRET_KEY = "0%1c709jhmggqhk&=tci06iy+%jedfxpcoai69jd8wjzm+k2f0"
DEBUG = True
INSTALLED_APPS = ["channels", "graphql_ws.django", "graphene_django"]
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
... |
991,735 | 2e0078398ae72a5cfa92c60b9b4e10b03688c58a | __author__ = 'Kami'
|
991,736 | 27610b01613335975586de1b2e041a2b91434f39 | import re
data = [line.strip() for line in open("./input.txt").readlines()]
data.sort()
slept = {}
for line in data :
if '#' in line :
id = int(re.findall(r"\#(\d+)", line)[0])
if id not in slept :
slept[id] = [0] * 60
elif "falls asleep" in line :
start = int(re.findall(r"\d:(\d+)", line)[0])
... |
991,737 | 13f9c5a83986714b1b646258fb0d9a1117eb8f1c | from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.utils.translation import ugettext, ugettext_lazy as _
from apps.user.models import CustomUser
from apps.opt.models import BusinessTypes
class LoginForm(AuthenticationForm):
pass
class Use... |
991,738 | 5c421813a057f70141b0cd0898490fd158dd8b82 | #!/usr/bin/env python
import json
import os
import csv
import random
import string
currentdirpath = os.getcwd()
filename = 'choices.csv'
file_path = os.path.join(os.getcwd(), filename)
def get_file_path(filename):
currentdirpath = os.getcwd
file_path = os.path.join(os.getcwd(),filename)
print file_path
return fi... |
991,739 | ba8653a1e4a996dbec36ccf0388f9e69c5385859 | #!/usr/bin/env python3
# Power digit sum
# =================
# Problem 16
# :math:`2^{15} = 32768` and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number :math:`2^{1000}`?
# .. rubric:: Solution
# .. py:module:: euler16
# :synopsis: Power digit sum
# .. py:funct... |
991,740 | b86043bb70db47fbe6478fdaf63e45b71e244893 | from flask import Blueprint
from sys_app.api import AppAPI, AccessAPI
app_app = Blueprint('app_app', __name__)
app_view = AppAPI.as_view('app_api')
app_app.add_url_rule('/apps/',view_func=app_view, methods=['POST',])
access_view = AccessAPI.as_view('access_api')
app_app.add_url_rule('/apps/access_token/', view_func... |
991,741 | 60131206a8647c93f88a0ee2aec3585103a93a52 | import heapq
def solution(scoville, K):
answer = 0
heap = []
for s in scoville:
heapq.heappush(heap, s)
while heap:
if heap[0]>=K: return answer
a = heapq.heappop(heap)
if heap!=[]:
heapq.heappush(heap,a+(heapq.heappop(heap)*2))
answer += ... |
991,742 | 934cd2523fca35c070a1c753dec84163b74a373e | from typing import TypedDict
class PullRequest(TypedDict):
pass
|
991,743 | 22be56a727deae2433d56b38bd8ad77585876c77 | caso1 = {'25u8sBP': {'estado': 'Fuera de Servicio',
'modeloCajero': 101,
'transacciones': [{'fechaMovimiento': '17-05-2021',
'monto': 50000,
'tipoCuenta': 'cuentaVirtual',
'tipoMovimiento': 'consign... |
991,744 | 64a6f0b1ee14d0d5b5b4baa58c2aa25f3552aafe | import requests
siteList = [
"https://google.com",
"http://store.nike.com/us/en_us/",
"http://www.adidas.com/us/yeezy",
"http://www.adidas.com/us",
"http://www.supremenewyork.com/shop/all"
]
proxies = [
"123.123.123.123:1234"
]
userAgent = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/5... |
991,745 | c8a37647ef5924b61c022e5beff51a78aa6cc1d4 | # This program support the convertion of object location from camera by rotating it in 3D environment
# It needs the coorporation of robot hand so control robot function will be applied
# Robot position will be changed in config file
from cv2 import sqrt
import kuka_communicate as robot
import configparser
from ast im... |
991,746 | f4e7902ca2dffd81714c0d57c261d76223c6db2a | #!/bin/python3
import math
import os
import random
import re
import sys
squares = []
seed = (
(8, 1, 6),
(3, 5, 7),
(4, 9, 2)
)
def reflect(s):
'''
Returns a new square that is the reflected version of s.
Reflects across the identity diagonal. Any sort of reflect works since we
also rota... |
991,747 | 1a82b98af2dd3c9dc08ea2fff9cb710b93807407 | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from model_conv import Net
def train(model, device, train_loader, optimizer, epoch):
model.train()
... |
991,748 | fb56a2a3d48c20fb6c890997ca01d1088acbfa26 | class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
pile = []
a, b = "", ""
i, size = 0, len(s)
# recover first number
while i < size and (s[i] == ' ' or s[i].isdigit()):
a += s[i]
... |
991,749 | 4f35855e0af79363297580f6f169029bc673a924 | #!/usr/bin/env python3
import datetime
from datetime import date
class S1_Utils():
def __init__(self):
tracks = [37, 52, 169, 65, 7, 50, 64, 49]
self.numberOfFrames = {}
self.numberOfFrames[37] = 5
self.numberOfFrames[52] = 5
self.numberOfFrames[169] = 4
self.numb... |
991,750 | 9a53466a6b0c79693ff202865119bb3992c2ee70 | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout
import matplotlib.pyplot as plt
import numpy as np
mnist = keras.datasets.mnist
(img_train, lab_train), (img_test, lab_test) = mnist.load... |
991,751 | bd07ec32a003fdd32798fedee0029a4fc67a82ec | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from datetime import datetime
class Question(models.Model):
question=models.CharField(max_length=500)
ans... |
991,752 | c51318117177f7d64fda876d7a0fe64cfc7aa98b |
class GroupChat:
def __init__(self, users, messages):
"""
Class representing the group chat in a format way.
:param users: Set of users in the chat
:param messages: List of messages sorted by time, newest first and oldest last
"""
self.users = users
self.me... |
991,753 | 5023fe4721e42aecaa36835a96fd6c784129daad | def match(s1,s2):
length = len(s2)
result = ""
resultMisaamatchCount = length
seqdict={}
for index, s in enumerate(s1[:-length]):
missmatch = 0
for j,k in zip(s1[index:index+length],s2):
if j!=k:
missmatch +=1
if missmatch <= resultMissma... |
991,754 | bd4c8d2362c6fc2652831ecb410ca3f50454bd64 | # Python module file
"""Definitions of camera models used by the Curiosity Mars rover."""
|
991,755 | f3f7affcd0a9d7cb2c40911e86292285c3dcbead | from __future__ import print_function
import random
import textwrap
import sys
if sys.version_info < (3, 0):
print("此代码需要 Python 3.x 并使用 3.5.x版测试 ")
print("正在使用的Python版本是"
": %d.%d " % (sys.version_info[0], sys.version_info[1]))
print("退出")
sys.exit(1)
def show_theme_message(width=76):
... |
991,756 | 0608fed03d27ed0c3a74dc0fc88ca831726eb1eb |
class Set(object):
def __init__(self):
self.screen_width = 800
self.screen_height = 600
self.bg_color = (0, 0, 0)
self.air_speed = 1.5
self.bullet_set_speed = 1
self.bullet_w = 15
self.bullet_h = 3
self.bullet_set_color = 255, 255, 255
|
991,757 | 0602eb51ede3d8b50f94e254d9f8f3440e414870 |
import pandas as pd
import geopandas as gpd
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import adjacency_graph
from random import randint
from autographs.faces import HalfEdge
"""
Imports a seeded plan and makes a pretty map of it.
"""
# Load the district assignment into pandas.
df... |
991,758 | 0480089f416e4e132030aee50a92014ee5df4b10 | #Mark Griffiths
#Date: 11/10/2019
#CSC121
#File Python Dictionaries and file writing
import mbox
def writeMboxReport(mydict):
str1 = "";
for day,count in mydict.items():
str1 = str1 + day + " " + str(count) + "\n";
emailinfo = str1;
fhand = open('report.txt', 'w');
fhand.write(emailinfo)
fhan... |
991,759 | df9487f92f620731d74443a4255060d3fcc767a5 | # -*- coding: utf-8 -*-
import unittest, socket, logging, os
from ..util import TestClient, Msg
class TestChannel(TestClient, unittest.TestCase):
user = 'foo'
host = socket.gethostname()
def openCircuit(self, auth=True):
'Open TCP connection and sent auth info'
self.connectTCP()
s... |
991,760 | 16c79d75cbecc43956a3a57519b3a12e549a0f5f | from .util import *
def get_connection(db_name):
conn = sqlite3.connect('data/{}.db'.format(db_name))
conn.text_factory = str
return conn
def query(firm, cmd):
with get_connection(firm) as conn:
cur = conn.cursor()
cur = cur.execute(cmd)
field_names = [i[... |
991,761 | d62f6fed42223514d3f0707e98d1b90da4082b92 | #!/usr/bin/env python
"""
.. module:: convert
:synopsis: used to create info.txt and the <txname>.txt files.
"""
import sys
import os
import argparse
import types
argparser = argparse.ArgumentParser(description =
'create info.txt, txname.txt, twiki.txt and sms.py')
argparser.add_argument ('-utilsPath', '--utils... |
991,762 | 5bc5a057bfc97833f54e29dca67b785b8ed4fa93 | def reverse(text):
return text[::-1]
def is_polidrom(text):
return text == reverse(text)
def filter(text):
forbidden = ('.', '?', '!', ':', ';', '-', '—', '(', ')', '[', ']', '...', '’', '“', '”', '/', ',')
newtext = [x for x in text if not x in forbidden]
newtext = ''.join(newtext)
return ne... |
991,763 | 366b0c6c2f07942ca1c5efade5881e443dbcd71a | import Image, re, os, subprocess
from vdfparser import VDF
from subprocess import PIPE, Popen
import wikitools
from uploadFile import *
if os.path.isfile('pngcrush.exe'):
pngcrush = True
else:
pngcrush = False
def get_file_list(folder):
""" Returns list of .png files in folder. """
filelist = []
for file in os.... |
991,764 | 1b96a71fc924744fe72c61dfba74b2643d9cc090 | import sqlite3
from Bio import SeqIO
import random
import re
from jsonschema import validate
class CodonDatabase:
def __init__(self,database=None,default_organism=None,rare_cutoff=None):
if database != None:
self.conn = sqlite3.connect(database)
else:
self.conn = sqlite3.co... |
991,765 | 6f908df70e20039599e28971e4dc9d268ac3126d | # Вариант №3
# 3. Дан файл. Определите сколько в нем букв (латинского алфавита),
# слов, строк. Выведите три найденных числа в формате, приведенном в примере.
# Пример входного файла:
# Beautiful is better than ugly.
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicat... |
991,766 | f1640625af5d38f7f6eaed57e81865546da1e253 | #!/usr/bin/env python
# -*-coding: utf-8 -*-
# out_file = 'data/logs/auth_mix.log'
# in_file_list = ['data/logs/auth_normal.log', 'data/logs/auth_hydra.log']
out_file = 'data/logs/jslab_logs/jslab_access_mix.log'
in_file_list = ['data/logs/jslab_logs/jslab_access.log.1', 'data/logs/jslab_logs/jslab_access.log.2',
... |
991,767 | 240f5ea5159d6e8323073844f2fca785a59387d4 | import logging
import scrapy
import proxy
from ..items import BeautyItem
# print('start generate proxy ip')
# proxy.get_proxy()
logger = logging.getLogger(__name__)
class BeautySpider(scrapy.Spider):
print('start generate proxy ip')
proxy.get_proxy()
name = 'siwa'
allowed_domains = ['www.27270.com... |
991,768 | 15384ba35b489540d5968a4493ecd20aa33d4ff5 | # encoding: UTF-8
import json
import tushare as ts
import numpy as np
import pandas as pd
from enum import Enum
from collections import deque
import traceback
import os
from datetime import datetime
from datetime import timedelta
from time import time, sleep
from pymongo import MongoClient, ASCENDING, DESCENDING
fro... |
991,769 | e1e1d5b08fd4ea038f33134b969133b4120e1de7 | import numpy as np
from typing import Optional, List
class Galaxy:
def __init__(
self,
redshift: float,
light_profiles: Optional[List] = None,
mass_profiles: Optional[List] = None,
):
"""
A galaxy, which contains light and mass profiles at a specifie... |
991,770 | 268308182d08ecba3757b8a26a7f6ac14009062e | # from Model import Model
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import numpy as np
from copy import deepcopy
# import aerosonde_parameters as MAV
# import vaporlite_parameters as MAV
from tools import normalize
from tools import Quaternion2Euler
import pdb
import warnings
def R(q):
... |
991,771 | da58fd3dd6dcf065ad37ec18b8e6cd341314547a | AlfaItemList=[]
#AlfaItemList.ItemList+= ["ALFA_HitCollection#*"]
#AlfaItemList.ItemList+= ["ALFA_ODHitCollection#*"]
#AlfaItemList.ItemList+= ["ALFA_DigitCollection#*"]
#AlfaItemList.ItemList+= ["ALFA_ODDigitCollection#*"]
#AlfaItemList.ItemList+= ["ALFA_RawDataContainer#*"]
AlfaItemList.append("ALFA_DigitCollecti... |
991,772 | 5be825c3f0f3e7d2bfae25394832e247cc262818 | import pandas as pd
import geopandas as gpd
import osmnx as ox
import networkx as nx
import json
import ast
from fiona.crs import from_epsg
from shapely.geometry import Point, LineString, MultiLineString, box
import utils.exposures as exps
import utils.geometry as geom_utils
import utils.utils as utils
def get_walkabl... |
991,773 | e7e06f5b3f145bccb4452650174660b8fb85ce45 | # Generated by Django 2.2.5 on 2021-02-21 17:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0008_tech_support'),
]
operations = [
migrations.AlterField(
model_name='tech_support',
name='user',
... |
991,774 | e38008f8a51fa74d56e4bd7d7825692bd57fac14 | #
# Copyright (C) 2019 Databricks, Inc.
#
# 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 i... |
991,775 | c81ddc73aca4123e4667141a822194c54f3b9006 | # -*- coding: utf-8 -*-
import time
from wechat.client import WeChat
w = WeChat()
w.login()
print(w.client.login_info)
while True:
time.sleep(100)
|
991,776 | f40d971a99cd46e8993ca606d6716a5eac615165 | import collections
reductions = [
# Simplifications
[ 'n', 'se', 'ne'],
[ 'n', 'sw', 'nw'],
[ 's', 'ne', 'se'],
[ 's', 'nw', 'sw'],
['sw', 'se', 's'],
['nw', 'ne', 'n'],
# Opposites
[ 'n', 's', '--'],
['sw', 'ne', '--'],
['nw', 'se', '--'],
]
def distance(steps):
co... |
991,777 | 13b3b84e6d55890d70eedf527ebc83ace9984896 |
import sys, os
from glbase3 import *
sys.path.append("../sam_annotations/")
import sam_map
config.draw_mode = "pdf"
expn = glload("../te_counts/genes_ntc_expression.glb")
sam_map.remap_expn_sample_names(expn)
expn.log(2, 0.1)
expn.tree(filename="tree.png", color_threshold=0.0, label_size=4, size=(5,14))
expn.corre... |
991,778 | 6495711650a7ae4f032920cfa6f3ac079ec39ffa | from SmartDjango import models, E, Hc
@E.register(id_processor=E.idp_cls_prefix())
class ConfigError:
CREATE = E("更新配置错误", hc=Hc.InternalServerError)
NOT_FOUND = E("不存在的配置", hc=Hc.NotFound)
class Config(models.Model):
key = models.CharField(
max_length=100,
unique=True,
)
value ... |
991,779 | a0d7d3b95dfefe7b19ffccbed089b1a26d769b92 | def sum_of_divisors(number):
x = 0
for a in range(int(0.5+(number**0.5))):
if (a+1)**2 == number or (a+1) ==1:
x += (a+1)
elif number%(a+1) == 0:
x += (a+1)
x += number/(a+1)
return x
abundants = []
for a in range(1,49):
b = sum_of_divisors(a)
if b>a:
abundants.append(a)
print(b,a)
print abundan... |
991,780 | be25c4831533e712a29ac4e39ca13c814e1c32c7 | from flask import Flask
from flask_testing import TestCase
# from flask.ext.testing import TestCase
import unittest
try:
from flask_discoverer import Discoverer, advertise
except ImportError:
import sys
sys.path.append('..')
from flask_discoverer import Discoverer, advertise
class TestConfigOptio... |
991,781 | 939aa4c17d16edcc202dac10323ec6245693aabd | from django.shortcuts import render, get_object_or_404
from .models import Product, CartDetail
from django.http import HttpResponse
import json, uuid
def index(request):
latest_product_list = Product.objects.all()
context = {
'latest_product_list': latest_product_list,
}
return render(request,... |
991,782 | d6f0ec860f7267cdc19cc7320da6677f4224cee1 | #!/usr/bin/env python
import base64
import hashlib
import hmac
import json
import sys
import time
def base64_url_decode(input):
input = input.encode(u'ascii')
input += '=' * (4 - (len(input) % 4))
return base64.urlsafe_b64decode(input)
def parse_signed_request(input, secret, max_age=3600):
encoded_s... |
991,783 | 3c065f540a50844a1bf0238c2990dffa6d7ab9e3 | def computepay(h, r):
if h > 40 :
th = h-40
rh = 40
rr = r*1.5
p = rh*r+th*rr
else :
p = h*r
return p
hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter Rate:")
r = float(rate)
p = computepay(h, r)
print("Pay", p)
|
991,784 | fe2690dab9b419a223ffa0edea51118dd9060df9 | from collections import Counter
from typing import List
def mostCommonWord( paragraph: str, banned: List[str]) -> str:
paragraph = paragraph.lower()
stri=""
for c in paragraph:
if c.isalnum():
stri+=c
else:
stri=stri+(" ")
words=stri.split()
c=Cou... |
991,785 | b0a58e69ff8e70a0ee4c912de9dc9f236c9267bf | M,N = map(int,raw_input().split())
nums = [43, 88, 250, 290, 319, 312, 501, 177, 358, 24, 221, 30, 98, 591, 4, 66, 76, 37, 131, 6, 450, 188, 384, 241, 85, 291, 12, 505, 523, 480, 33, 183, 504, 419, 454, 44, 272, 104, 374, 133, 172, 427, 81, 190, 225, 458, 349, 418, 337, 266, 592, 444, 170, 306, 175, 296, 571, 542, 204... |
991,786 | 87efec1debb62562acc9c7bcb57ece143e054e6f | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pyexplog.configuration import ParameterSpace, Configuration, ConfCollection
from pyexplog.manager import ExpManager, DummyExperiment, repeated_experiment
from pyexplog.log import ExpLog
import pandas as pd
from tables.nodes import filenode
import io
# Path to the re... |
991,787 | 98c865ee956880823ad312a2a920e68e597b1488 | import sys
from hangman import hangman
class MyInput:
def __init__(self, input_values):
self.__input_values = input_values
def readline(self):
return self.__input_values.pop(0)
def test_hangman(capsys):
sys.stdin = MyInput(list("abeolhxyznmo"))
def test_hangman_hello_won_p():
... |
991,788 | a0da6c04a6b401f34fa144c290b755f0b22d2a47 | f = open('sum_of_digits')
N = int(f.readline())
result_arr = []
for i in range(N):
sum_digits = 0
arr = f.readline().split()
sum_number = int(arr[0]) * int(arr[1]) + int(arr[2])
for ch in str(sum_number):
sum_digits += int(ch)
result_arr.append(sum_digits)
for ch in result_arr:
... |
991,789 | df8006efbb2153b98ec5bb26415aa68d330c8bae | from abc import ABC, abstractmethod
import datetime as dt
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
import pandas as pd
import simpleaudio as sa
import numpy as np
import court
class AbstractBall(ABC):
def __init__(self, xy, angle, speed):
self._xy = xy # (x... |
991,790 | 670404546b047f4ef06f7abad8b3e6f6a1ccbb9b | from pymongo import MongoClient
from flask import Flask, jsonify, request
import json
import requests
import json
import bson
from datetime import datetime
from flask import send_file
import qrcodegen
import pymongo
import re
from flask_restplus import Api, Resource
from flask_swagger import swagger
from flask_cors im... |
991,791 | 2301733dd739c486b6f19d54037920fa77df30c0 | from distutils.core import setup
setup(
name='sleepylyze',
version='0.1dev',
author= 'J. Gottshall',
author_email='jackie.gottshall@gmail.com',
packages=['sleepylyze',],
url='https://github.com/jag2037/sleepylyze',
license='',
description= 'Python analysis of EEG sleep architecture'
long_description=open('REA... |
991,792 | ed38321193f4a2593ce81d9e72b027924ab0127f | from hashlib import md5
secret = "bgvyzdsv"
hash_out = "xxxxxx"
# part 1
i = 0
while hash_out[:5] != '00000':
i += 1
hash_out = md5(str(secret + str(i)).encode()).hexdigest()
print("part 1:\ti: {}, hash: {}".format(i, hash_out))
# part 2
while hash_out[:6] != '000000':
i += 1
hash_out = md5(str(secre... |
991,793 | 8f2f7037219045cb7d825333034150b130bf4c19 | r"""Models of galaxy luminosities.
Models
======
.. autosummary::
:nosignatures:
:toctree: ../api/
herbel_luminosities
"""
import numpy as np
import skypy.utils.astronomy as astro
from skypy.utils.random import schechter
def herbel_luminosities(redshift, alpha, a_m, b_m, size=None,
... |
991,794 | 14735a60820f780205cf6b142f0f6921bacdd63b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
DESCRIPTION = "STJ_PV: SubTropical Jet Finding via PV Gradient Method"
LONG_DESCRIPTION = """STJ_PV Provides a framework for testing metrics of the subtopical
jet against one another."""
AUTHOR = 'Penelope Maher, Michael Kelleher'
setup(
... |
991,795 | aec4c9f99cc6d4ba90c008c4ce9544e7108c7169 | #!/usr/bin/env python
"""Unittests for testing.py"""
import sys
import testing
class TestCase(testing.TestCase):
def testBasic(self):
"""The most basic test."""
self.assertEqual(True, True)
def test_assert_iterator(self):
"""Test the test_iterator() method"""
iterator = iter... |
991,796 | 153a7be9e6eb14d3e6952eac2dc3c794304f9872 | from django.contrib import admin
from productdetails.models import product
admin.site.register(product)
|
991,797 | 87cce7135900ebf0e819977e1654b4451a2facf6 | from unittest import TestCase
from time import sleep
from datetime import datetime
from ctparse.ctparse import _timeout, ctparse, _seq_match, _match_rule
from ctparse.types import Time
class TestCTParse(TestCase):
def test_timeout(self):
t_fun = _timeout(0.5)
with self.assertRaises(Exception):
... |
991,798 | 6b00861b847ba9b6ac9315b6b77737e9c3375bd1 | #!/usr/bin/env python3
# import boto3
import Inventory_Modules
from Inventory_Modules import display_results
from ArgumentsClass import CommonArguments
from account_class import aws_acct_access
from colorama import init, Fore
from time import time
from botocore.exceptions import ClientError
import logging
init()
__v... |
991,799 | 6e8ad7acd7843cf856552137fac09946d22ddf39 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def InitListNode(self,matrix):
self.head=ListNode(matrix[0])
p=self.head
for num in matrix[1:]:
p.next=ListNode(num)
p=p.nex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.