index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
600 | 1a0d4e77f09b4ce752631ae36a83ff57f96b89b1 | from rlbot.agents.base_agent import BaseAgent, GameTickPacket, SimpleControllerState
#from rlbot.utils.structures.game_data_struct import GameTickPacket
from Decisions.challengeGame import ChallengeGame
from Decisions.info import MyInfo, Car
from Decisions.strat import Strategy
from Drawing.Drawing import DrawingTool
f... |
601 | 4a0eca90de3ce7fb0ab6decb0ec6aadb32c1a9fa | # Given two binary trees, write a function to check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# Example :
#
# Input :
#
# 1 1
# / \ / \
# 2 3 ... |
602 | 0c1de2c1eb5a4de7aeb14ad6b27aa61e07bc4c51 | from django.urls import path
from .views import (
TreeCreateView,
TreeListView,
TreeUpdateView,
)
app_name = 'trees'
urlpatterns = [
path('list/', TreeListView.as_view(),
name='list'),
path('create/', TreeCreateView.as_view(),
name='create'),
path('<int:pk>/update/', TreeCreat... |
603 | 42d03aabef7d75c813f30bb6d8a835d76fd1fc83 | start=0
last=100
middle=50
counter=1
print(" Guess a number between 0 and 100")
condition = int(input("Is your guess " + str(middle) + "? (0 means it's too low, 1 means it's your guess and 2 means it's too high) "))
while condition != 1:
counter += 1
if condition == 0:
last = middle
elif conditio... |
604 | 97d4387c7bfd141b5a7019b221adb550105d4351 | import datetime
import logging
import os
from functools import lru_cache
from authlib.jose import JsonWebKey, jwt
from flask import g, request, jsonify
from lorem_ipsum.model import User, AppContext
import lorem_ipsum
from lorem_ipsum.model import Permission, BlacklistToken
LOGGER = logging.getLogger('lorem-ipsum')
... |
605 | eb90912d09fca52a43b28ec4c988e3658ddfc219 | # Question link: https://www.hackerrank.com/challenges/30-scope/problem
# Code section:
def computeDifference(self):
# Add your code here
self.maximumDifference = -111111
for i in range(0,len(self.__elements)-1):
for j in range(i+1, len(self.__elements)):
diff = abs(self._... |
606 | be1ef0aa3868985bf198781ee827bd447588df15 | """
This module provides functions to make WCSAxes work in SunPy.
"""
import matplotlib.pyplot as plt
from packaging.version import Version
import astropy.units as u
from astropy import __version__ as astropy_version
from astropy.visualization import wcsaxes
from sunpy.coordinates import HeliographicCarrington, Helio... |
607 | af9b83b6e213359f5e193918b6c09c22220e5457 | #crfで英文に固有表現認識(タグ付け)をする
#usr/bin/python3
#coding:utf-8
from itertools import chain
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import LabelBinarizer
import sklearn
import pycrfsuite
from sklearn import cross_validation
import sys
import os
import math
import random
d... |
608 | 932bb7c9dbf3e97c966d2d7d537e747756831e30 | version https://git-lfs.github.com/spec/v1
oid sha256:a2959c4cccf29b3797cc2e2dcef87ddb5a0779d9fb992bb38e190b791ae37eb0
size 88352
|
609 | 2536b22c2d154e87bdecb72cc967d8c56ddb73fb | import os
from pathlib import Path
import Algorithmia
API_KEY = os.environ.get('ALGO_API_KEY')
DATA_DIR_BASE = os.environ.get('DATA_DIR')
ORIGINAL_DATA_DIR = DATA_DIR_BASE + 'original/'
TRANSFERD_DATA_DIR = DATA_DIR_BASE + 'transferd/'
def upload(client, fnames):
for im in fnames:
im = Path(im)
... |
610 | 8a631adc8d919fb1dded27177818c4cb30148e94 | # 효율적인 해킹
# https://www.acmicpc.net/problem/1325
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = map(int, input().split())
graph[b].append(a) # B를 해킹하면 A도 해킹할 수 있다
def bfs(start):
visited =... |
611 | 833923c1928862e13c24904f5614927a683b168f | import os
class Config(object):
"""Base Config Object"""
DEBUG = False
SECRET_KEY = os.environ.get('SECRET_KEY') or 'Som3$ec5etK*y'
UPLOAD_FOLDER = './uploads'
dbconfig = {
'host': os.environ.get('MYSQL_HOST') or 'localhost',
'user' : os.environ.get('MYSQL_USER') or 'root',
'password' : o... |
612 | 1748c8dfcc3974b577d7bfacb5cabe4404b696bc | import math
import numpy as np
from statistics import median
from src.filter.median import quickselect_median
def bilateral_median_filter(flow, log_occlusen, auxiliary_field, image, weigth_auxiliary, weigth_filter,
sigma_distance = 7, sigma_color =7 / 200, filter_size=5):
"""
:par... |
613 | 55f76ae1ffe0fb2d2ca2c7a20aab45ffb00cf178 | # collectd-vcenter - vcenter.py
#
# Author : Loic Lambiel @ exoscale
# Contributor : Josh VanderLinden
# Description : This is a collectd python module to gather stats from Vmware
# vcenter
import logging
import ssl
import time
from pysphere import VIServer
try:
import collectd
COLLECTD_ENABLED... |
614 | 7e50fc5eb794d7f2e4805924dcc7a99296e0d732 | /usr/share/pyshared/Bio/Phylo/_io.py |
615 | a571abd88184c8d8bb05245e9c3ce2e4dabb4c09 | import sys
from collections import deque
t = int(sys.stdin.readline().rstrip())
for _ in range(t):
n, m = map(int, sys.stdin.readline().split())
q = deque(map(int, sys.stdin.readline().split()))
count = 0
while q:
highest = max(q)
doc = q.popleft()
m -= 1
if doc != high... |
616 | 2257494dec9fccc4e8bd4acf0aff31a73c252a61 | h = 160
xorg = 0
yoff = 400
xcount = 0
xvel = 2
def setup():
size(800, 800)
colorMode(HSB, 360, 1, 1, 1)
background(140, 0.49, 0.75)
frameRate(30)
noStroke()
def draw():
global h, xorg, yoff, xcount, xvel
if frameCount % 10 == 0:
fill(140, 0.49, 0.75, 0.2)
square(0,0,width)... |
617 | 6f99b4e4204e85c78f9c02a5cd53cd76f52c022c | import ujson as json
import platform
import socket
import os
from pathlib import Path
def test_json(text):
jobj = json.loads(text)
l = len(jobj['coordinates'])
x = 0
y = 0
z = 0
for coord in jobj['coordinates']:
x += coord['x']
y += coord['y']
z += coord['z']
print(x / l... |
618 | 94be205e516c1f1248b6028419c04c927236596e | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmagic.registry import MODELS
def test_colorization_net():
model_cfg = dict(
type='ColorizationNet', input_nc=4, output_nc=2, norm_type='batch')
# build model
model = MODELS.build(model_cfg)
# test attributes
assert mode... |
619 | cb3c1adb9d91aecee5b21774d61dfe9400a330fa | from point import Point
from velocity import Velocity
import arcade
import config
PADDLE_WIDTH = 15
PADDLE_HEIGHT = 30
class Paddle:
def __init__(self):
self.center = Point(390, 50)
self.velocity = Velocity(0, 5)
def draw(self):
self.drawing = arcade.draw_rectangle_filled(self.center... |
620 | 44224985dbfa6234eff406149ce25e1d00b512e9 | class Anagram(object):
def __init__(self, word):
self.word = word
self.canonical = self._canonicalize(word)
def _canonicalize(self, word):
return sorted(word.lower())
def _is_anagram(self, word):
return word != self.word and self._canonicalize(word) == self.canonical
d... |
621 | c2839046592469dfae7526f72be947126960ba19 | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
from projects.models import Project
from django.db import connection
from .utils import namedtuplefetchall
from django.http import JsonResponse
fro... |
622 | 1431a0049c05a99e0b68052f56bf8e2e3c48e1aa | from flask import request
from flask_restful import abort
from sqlalchemy.exc import SQLAlchemyError
from gm.main.models.model import db, Metric, QuantModelMetricSchema, \
MlModelMetricSchema, Frequency, QuantModelMetric, MlModelMetric, \
ThresholdType
from gm.main.resources import success, get_metric_b... |
623 | 4a136a6284add3bcbd7f9546e18e79151cea685f | import nevergrad as ng
import numpy as np
import torch
from pix2latent.utils.image import binarize
class _BaseNevergradOptimizer():
"""
Base template for NeverGrad optimization. Should be used jointly with
BaseOptimizer.
For full list of available optimizers
> https://github.com... |
624 | 1bf79319613ca1454f3a9ed21068bd899616395c | #-*- coding: utf-8 -*-
s = "123"
try:
print(int(s) + 1)
print(int(s) / 1)
except ValueError as ve:
print("ValueError occurs!!!", ve)
except ZeroDivisionError as e:
print("ValueError occurs!!!", e)
except :
print("Error occurs!!!")
else:
print("elseeeeeeeeeeeeeee")
finally:
print("ABCDE... |
625 | 40bc8122d98d407341a56251f9abfab019e0acd8 | from collections import Counter
from enum import auto, Enum
class Category(Enum):
ONES = 1
TWOS = 2
THREES = 3
FOURS = 4
FIVES = 5
SIXES = 6
YACHT = auto()
FULL_HOUSE = auto()
FOUR_OF_A_KIND = auto()
LITTLE_STRAIGHT = auto()
BIG_STRAIGHT = auto()
CHOICE = auto()
def s... |
626 | 3e07a2a2d0a810c016720fa41d71d0771cbccfef | from tqdm import tqdm
import os
import pandas as pd
import pickle
import numpy as np
def inv_list(l, start=0):
d = {}
for i in range(len(l)):
d[l[i]] = i+start
return d
raw_data_path = '/home/reddy/sindhu/datasets/physionet_2012/'
def read_dataset(d):
ts = []
pbar = tqdm(os.listdir(raw_dat... |
627 | 3668e8009dca4ea261bdfbd325331c338fdac5a9 | import torch
import re
import sys
import os
import shutil
import filecmp
import numpy as np
from collections import defaultdict
from shutil import copyfile
sys.path.append('../')
class BoardParser:
def __init__(self):
self.file = open('../board_output', 'rb')
self.data = None
def update(se... |
628 | 32b3e65add5fb44320898b682e8f94f1460a32e7 |
def create_meme(word):
return f'this is your meme NEW VERSION {word}'
|
629 | a714ac227d5185d7b4a932695ba6698e18d96341 | # -*- coding: utf-8 -*-
import sys
from os import listdir, makedirs, unlink
from os.path import isdir, join, isfile, exists
from shutil import copy
import random
def clearDirectory( path ):#将dataset里面的文件都删除
for the_file in listdir(path):
file_path = join(path, the_file)
try:
if isfile(file_path):
... |
630 | 6af5faaaa9d894dd2b882cfe1bb8b8225780743c | '''
# VariableScope.py
#
# Written by leezhm on 13th March, 2012.
#
# Copyright (C) leezhm(c)126.com. All Right Reserved.
#
# For Chapter 6 Dragon Realm
#
# <<Invent Your Own Computer Games with Python>>
'''
print('Why not ?')
print(True and not False)
# A global variable named "spam"
spam = 1208
# This b... |
631 | 98bd4eb25a76fb9184f9abfcb920a6fbe46b9394 | import json
subjects = []
with open("sub.json", 'r') as subject_file:
subjects = json.load(subject_file)
print(json.dumps(subjects, separators=(',',':')))
|
632 | 168a12e6653a0526f29c163913def50147481154 | """This program displays a customizable list of items by priority value,
with priority 1 being the highest. Allows the user to add, edit,
mark complete, show completed (hidden), and remove items. Stores the list of
items in a .txt file located where this program's main.py file is. All
changes are automatically save... |
633 | b7ccb41c43a0db6f1bf9e6ba5cef1b9b1417e297 | "Unit tests for reverse URL lookup"
from django.core.urlresolvers import reverse_helper, NoReverseMatch
import re, unittest
test_data = (
('^places/(\d+)/$', 'places/3/', [3], {}),
('^places/(\d+)/$', 'places/3/', ['3'], {}),
('^places/(\d+)/$', NoReverseMatch, ['a'], {}),
('^places/(\d+)/$', NoRevers... |
634 | 778cf8064fa45e3e25a66f2165dcf6885c72fb8a | # This script allows you to copy all files with a certain extention to a new folder without integrating the sub folders
# Created by Maurice de Kleijn Vrije Universiteit Amsterdam Spatial Information laboratory for the datamanagement of the the archaological project Barin Hoyuk
# 22062016 Python 2.7
import shutil
impo... |
635 | 56d3e59e3e077b1febb834668aba44ce8dba13ae | clear ;
clc;
%-----------------------读入图像-------------------------------------%
markbefore=imread('p203.bmp');
markbefore2=rgb2gray(markbefore);
mark=im2bw(markbefore2);
figure(1);
subplot(2,3,1);
imshow(mark),title('水印图像');
[rm,cm]=size(mark);
cover=imread('pic.bmp');
cover1=imresize(cover,[512... |
636 | 5eb4c71869b077dac0d61072c99d801030395fc2 | from pwn import *
p = process("./weeb_hunting")
elf = ELF("/lib/x86_64-linux-gnu/libc-2.23.so")
pwnlib.gdb.attach(p)
r = p.recv()
while "You found a" not in r:
r = p.recvuntil(">")
p.send("AAAA\n")
p.send("AAAA\n")
r = p.recv()
while "You found a" not in r:
r = p.recvuntil(">")
p.send("AAAA\n")
p.send("AAAA\n")... |
637 | 383d3b35fbfb7921111b28c3160173ce1c200387 | from copy import deepcopy
from datetime import date, timedelta
from hashlib import sha256
import starkbank
from starkbank import BoletoPayment
from .boleto import generateExampleBoletosJson
example_payment = BoletoPayment(
line="34191.09008 61713.957308 71444.640008 2 83430000984732",
scheduled="2020-02-29",
... |
638 | b05a5fcbba74bf4108bc953c6f868eb1f5ca298f | from pymarketo.client import MarketoClientFactory
import os
import sys #@UnusedImport
import time #@UnusedImport
import datetime #@UnusedImport
from pprint import pprint #@UnresolvedImport
TESTDIR = os.path.split(__file__)[0]
PACKAGEDIR = os.path.join(TESTDIR,"..")
INIFILE = os.path.join(PACKAGEDIR,"marketo.ini")
DATA... |
639 | e2c69191d81724cac44bebba3111a773e408b7c8 | #Print table using while loop
tablenumber = int(input("Enter a number: "))
upperlimit = int(input("Enter a upper limit: "))
lowerlimit = int(input("Enter a lower limit: "))
i = upperlimit
while (i <= lowerlimit):
print (i,"*",tablenumber,"=",i*tablenumber)
i=i+1
print("========================================... |
640 | a513dfd84b5d9267b7e96fedc88e5b6dabeea19e | """ Tests for `yatsm.utils`
"""
import numpy as np
import pytest
from yatsm import utils
@pytest.mark.parametrize('nrow,njob', [(793, 13), (700, 1), (700, 700)])
def test_distribute_jobs_interlaced(nrow, njob):
assigned = []
for i in range(njob):
assigned.extend(utils.distribute_jobs(i, njob, nrow, i... |
641 | 6a5a6bdb0740d51426aa8b36dd3cc317103412b1 | from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from django.contrib.auth import logout
from rest_framework import status
from rest_framework.authtoken.models import Token
from .serilizer import UserSerializer
class RegistrationView(AP... |
642 | 04aacf9461ade2e229076ffdf85aca913037edad | import json
from jsonargparse import ArgumentParser, ActionConfigFile
import yaml
from typing import List, Dict
import glob
import os
import pathlib
import pdb
import subprocess
import copy
from io import StringIO
from collections import defaultdict
import torch
from spacy.tokenizer import Tokenizer
from spacy.... |
643 | 104c49941a79948749b27217a0c728f19435f77a | import random
x = int(raw_input('Please supply a number: '))
y = int(raw_input('Please supply a second number: '))
z = random.randint(x,y)
print (z)
|
644 | 3605f46da25eb98767ca8d7248beaa07572d3171 | processed_lines = []
for line in open('9.in'):
if line:
processing_pattern = False
new_line = ''
for idx, char in enumerate(line):
pattern_found = False
if line[idx] == '(' and line[idx+1].isnumeric() and line[idx+2] == 'x' and line[idx+3].isnumeric() and line[idx + 4] == ')':
patter... |
645 | e7db3390d30f86e19eee930c48e5f848f41cc579 | # take any non-negative and non-zero integer number and name it c0;if it's even, evaluate a new c0 as c0 ÷ 2;
# otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1;
# if c0 ≠ 1, skip to point 2.
# The hypothesis says that regardless of the initial value of c0,it will always go to 1.
# Write a program which reads on... |
646 | c455de70a79f70f5f0e21391511f5035f1b4feb9 | "Base class for tests."
import argparse
import http.client
import json
import os
import re
import sys
import unittest
import jsonschema
import requests
SCHEMA_LINK_RX = re.compile(r'<([^>])+>; rel="([^"]+)')
JSON_MIMETYPE = 'application/json'
DEFAULT_SETTINGS = {
'ROOT_URL': 'http://127.0.0.1:5002/api',
'U... |
647 | 630480e9458491a26ea9060bd36541a0d5805a11 | import urllib.request
import json
def kind():
data={}
with open("dataset.json", "r") as read_file:
data = json.load(read_file)
return data["kind"]
def items():
data={}
with open("dataset.json", "r") as read_file:
data = json.load(read_file)
return data["items"]
#Can add a bunc... |
648 | 016b64a2eb4af3034d54272c878fb917506d330c | from import_export.admin import ImportExportMixin
from django.contrib import admin
from import_export import resources, widgets, fields
from .models import Addgroup,Addsystemname,Zhuanzhebushi,Yewuzerenbumen,czyylx,Zhuanze,Data
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidg... |
649 | cddb16a305f74eb1a3f2854208f8508c4a7a8953 | import datetime
from flask import request
from flask_babel import _
from markupsafe import escape
from app import app
from app.data_access.audit_log_controller import create_audit_log_confirmation_entry
from app.data_access.user_controller import user_exists, create_user
from app.data_access.user_controller_errors im... |
650 | 219b22b6ad685fc316b1df02cc924a1cfec89f5b | from lmfit import Parameters
import numpy as np
from cls.cls import *
from reading.ellipseOutput import readEllipseOutput
def readInputModel(txt, equivalentAxisFit, Settings):
psfwing_02pxscale_datatab = None
psfwing_logscale_datatab = None
componentslist = []
params = Parameters()
data = open(txt)
for lin... |
651 | 4cf2829282cb0a1673e741f78f17ce27a2817ff2 | '''Module for generating and plotting networks.'''
from trafpy.generator.src import tools
import copy
import networkx as nx
import matplotlib.pyplot as plt
import json
def gen_arbitrary_network(num_eps,
ep_label=None,
ep_capacity=12500,
... |
652 | da66b254afb3a8fcd3783a38d8624caa917e58c3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
ACHAEA_ENDPOINT = 'https://api.achaea.com'
def _requires_auth(func):
def wrapper(self, *args, **kwargs):
if self.auth is not True:
raise APIError()
return func(self, *args, **kwargs)
return wrapper
class API:
au... |
653 | 83c7bb2e109f8affd9e2a12e8c5370b0f5a34048 | def fibonacci(quantidade):
resultado = [1, 2]
# while True:
# substituir o while pelo for, em um range do 2° valor da lista, correr até
# o valor definido na função "Quantidade"
for _ in range(2, quantidade):
# desta forma ele irá realizar a função do 2° da lista até atingir
# o valor ... |
654 | 0082f75332321dba498f06d4c4a99c9248829b59 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 13:19:51 2020
@author: Warren
Script to check sdf file format for Fragalysis upload
"""
from rdkit import Chem
import validators
import numpy as np
import os
from viewer.models import Protein, CompoundSet
import datetime
# Set .sdf format versio... |
655 | 48bc5d4b191fa631650b60240560dbece6396312 | from random import randint
cantidad = int(input("Numero de preguntas: "))
contador_bien = 0
contador_mal = 0
while cantidad <= 0:
print ("El numero de preguntas debe ser al menos 1")
cantidad = int(input("Numero de preguntas: "))
for i in range(cantidad):
numero = randint(2,10)
numero2 = randint(2,10)
aleatorio ... |
656 | 18435f43e2f52e3d2e9ff6411f8dd0510d2da54d | a=eval(input('enter a list: '))
n=len(a)
if (n%2==0):
for i in range(0,n//2):
a[i],a[n//2+i]=a[n//2+i],a[i]
print('after swap:',a)
else:
for i in range(0,n//2):
a[i],a[n//2+i+1]=a[n//2+i+1],a[i]
print('after swap:',a)
|
657 | b1ab28a99fdcce66f0a1e4e25821073673f531cf | """
module rational number
"""
def _gcd(num_a, num_b):
"""
gratest common divisor
"""
if num_a == 0 or num_b == 0:
raise ArithmeticError('gcd of zero')
var_p = num_a
var_q = num_b
if var_p < var_q:
var_p = num_b
var_q = num_a
var_r = var_p % var_q
while var_r... |
658 | 5e0cba6952cdc677c640a0df325426ffc89189cd | # -*- coding: utf-8 -*-
from django.test import TestCase
from ..printer import Printer
class TestSunlumoProjectPrinter(TestCase):
def test_printer(self):
sl_prj = Printer('./sunlumo_mapserver/test_data/test_sunlumo.qgs')
tmpFile = '/tmp/printtmp'
sl_prj.printToPdf({
'tmpFile... |
659 | 49df9db508637ce5914aa6591178a03c609b6bc7 | import numpy as np
import math
import random
from numpy.linalg import inv
from scipy.optimize import minimize
from Util import to_vector
class TS_RLR:
def __init__(self, alpha):
self.d = 6
self.k = 6
self.alpha = alpha
self.batch_size = 1000
self.training_size = 1000
self.impressions = 0
self.batch_... |
660 | e08159a51b611ce6d0ca354a4fe6759d00af2cb7 | import matplotlib.pyplot as plt
file_list = ["Quantification_comet_fdr.csv",
"Quantification_crux_fdr.csv",
"Quantification_msfg_fdr.csv",
"Quantification_msfg_percolator.csv"]
file_titles = ["Comet",
"Crux",
"MSGFPlus",
"MSGFPlus + Pe... |
661 | 887a39f1eeb81e6472938c2451e57866d3ac4a45 | import math
from historia.utils import unique_id, position_in_range
from historia.pops.models.inventory import Inventory
from historia.economy.enums.resource import Good, NaturalResource
from historia.economy.enums.order_type import OrderType
from historia.economy.models.price_range import PriceRange
from historia.econ... |
662 | 3b3f423cfb08413a4135646ea4d3d6dcb5d0cc10 | # Based on https://dev.to/jemaloqiu/design-pattern-in-python-2-observer-j4
class AbstractObservable():
"""
Abstract Observable
"""
def __init__(self):
self.__observers = []
def add_observer(self, observer):
self.__observers.append(observer)
def remove_observer(self, obse... |
663 | 9d3439a2be1f22c8ec59923b88ac22877a4f13e8 | n, x = input().split()
n = int(n)
x = int(x)
m = [int(i) for i in input().split()]
m.sort(reverse=True)
i = 0
res = 0
while x > 0:
res += max(0, m[i])
m[i] -= 1
x -= 1
if m[i % n] < m[(i+1) % n]:
i = (i+1) % n
print(res) |
664 | 6b2fc94d9a53b8f669cab5e1fb625dd01e20ba98 | """Splits the google speech commands into train, validation and test sets.
"""
import os
import shutil
import argparse
def move_files(src_folder, to_folder, list_file):
with open(list_file) as f:
for line in f.readlines():
line = line.rstrip()
dirname = os.path.dirname(line)
... |
665 | 3e1540a06c478d471f6e6a190cadc44d5c4c2467 | import time as t
class Record:
def __init__(self, value = 10, name = 'name'):
self.id = name
self.value = value
def __get__(self, instance, owner):
with open('record.txt', 'a') as f:
msg = '读取变量%s ' % self.id
tmp = t.localtime()[:6]
form = ['年','月','... |
666 | ba216642935d19b85e379b66fb514854ebcdedd9 | #!/usr/bin/env python3
import subprocess
import sys
import pickle
if len(sys.argv) != 3:
print('Usage: std_dev_eval.py <std_dir> <ans>')
quit()
std_dir=sys.argv[1]
std_ans=sys.argv[2]
subprocess.call('rm -f {}/result'.format(std_dir), shell=True)
op_f = open('{}/jobs'.format(std_dir), 'w')
command = 'utils... |
667 | cd104eec21be8a59e8fb3bd8ab061dd357fc126a | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com 技术支持qq群:6089740
# CreateDate: 2018-3-27
# pillow_rotate.py
import glob
import os
from PIL import Image
def rotate(files, dst, value=90):
for file_ in files:
img = Image.open(file_)
img = img.rotate(value)
name = "{... |
668 | b1c06e9c5516a378c0bbce2ce9e17afaeae01928 | import re
# Class with static regex compilations
class RegexCompiles:
# regex for finding product-id in an EMAG link
re_compile_product_id = re.compile('Product-Id=[0-9]*')
# regex for finding the first number
re_compile_id = re.compile('[0-9]+')
# Verifies if a word exists in a text
def find_whole_... |
669 | 4a88ce640b6680df925288b44232cf43d585c11c | from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from datasets import concatenate_datasets
from datasets.arrow_dataset import Dataset
from transfer_classifier.dataset_preprocessor.classification_dataset_preprocessor import (
ClassificationDatasetPreprocessor,
)
from transf... |
670 | 58d069f6700149793c3446bdd4677f08eaf301ee | """A utility for outputting graphs as pickle files.
To test, run ``openbiolink generate --no-download --no-input --output-format pickle --qual hq``.
"""
import os
import pickle
from typing import Mapping
from openbiolink.edge import Edge
from openbiolink.graph_creation.graph_writer.base import GraphWriter
__all__ =... |
671 | 123d3906ce040a4daa5309eae555bad5509f805e | # coding=utf-8
# http://rate.tmall.com/list_detail_rate.htm?itemId=41464129793&sellerId=1652490016¤tPage=1
import requests, re
from Tkinter import *
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import random
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] ... |
672 | a4ecc578a163ee4657a2c9302f79f15c2e4e39de | class Leg():
__smelly = True
def bend_knee(self):
print("knee bent")
@property
def smelly(self):
return self.__smelly
@smelly.setter
def smelly(self,smell):
self.__smelly = smell
def is_smelly(self):
return self.__smelly |
673 | a85a7ad6ffb2b9aa5f5326d11c75ddbee680fac4 | import sys
import sucessor
import expande
from collections import deque
def busca_caminho(nodo_final, nodo_inicial):
pilha_acoes = deque() # iremos empilhar as acoes já que a estaremos com a ordem reversa a priori
v = nodo_final
while v != nodo_inicial:
pilha_acoes.append(v.acao)
v = v.pai
return pilha_acoes
... |
674 | 42d2d8717ec2c25a99302e8de3090d600f8e80ff | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.scala.goals.tailor import classify_source_files
from pants.backend.scala.target_types import (
ScalaJunitTestsGeneratorTarget,
ScalaSourcesGeneratorTarget,
... |
675 | b2fa6104f03dc76522a51f352101cef199ddc665 | # Generated by Django 2.2.7 on 2019-11-15 23:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('quizzapp', '0005_auto_20191115_2339'),
]
operations = [
migrations.RemoveField(
model_name='question',
name='titre',
... |
676 | 07bd3c7cacbf8d0e39d06b21456258ad92cb2294 |
# module: order functionality
# HW2: complete this func
def process_option(food, option):
# print(food.keys())
food_name = list(food.keys())[option-1]
food_price = food[food_name]
print(food_price)
print("You have chosen: ", option, food_name, "!", " For unit price: ", food_price)
... |
677 | 37f610457e51599a29168accd95eaa6699c6f777 | # Generated by Django 2.2 on 2020-11-05 16:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0011_auto_20201104_0936'),
]
operations = [
migrations.AddField(
model_name='users',
name='isadmin',
... |
678 | d786e89b9d478dcff3c541c89731247075d078c3 | '''
@author: Ken Venner
@contact: ken@venerllc.com
@version: 1.13
Read in a file of wine names and create consistent wine descriptions
from these names.
'''
import kvutil
import kvcsv
import re
import sys
import shutil
# may comment out in the future
import pprint
pp = pprint.PrettyPrinte... |
679 | c6cce2edafd7683af766b932d90ca170359e648a | """Usage:
sharedprint.py INPUT [--output=out.mrc]
sharedprint.py INPUT [--csv=greenglass.csv]
Process Koha MARC export for SCELC Shared Print.
The two uses above either 1) create a subset of the MARC input that's limited to
circulating items only or 2) performs a comparison between what's in the catalog
and w... |
680 | 3d45fd7dcb3b382efaefe2797ebeb33216a840fa | from django import forms
from .models import Picture
class PictureUploadForm(forms.ModelForm):
class Meta:
model = Picture
exclude = ()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widge... |
681 | d84641ce2854d4af26cd46abbe9557d6006cfc2e | import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
import os
# caps = {'browserName': os.getenv('BROWSER', 'firefox')}
# browser = webdriver.Remo... |
682 | bad719d968b4e358f863b7ef13bc12127f726806 | # -*- coding: utf-8 -*-
"""Testing constants for Bio2BEL FlyBase."""
import logging
import os
log = logging.getLogger(__name__)
dir_path = os.path.dirname(os.path.realpath(__file__))
TEST_FILE = os.path.join(dir_path, 'test_gene_map_table.tsv.gz')
|
683 | 0ff6e22f8704a0c6c0ffff3c53761b9d3a531b6d | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from PyQt5 import QtWidgets, uic
import sys
import pymysql
import mysql.connector
class Ui_Login(QtWidgets.QDi... |
684 | 5ff7a3843314dfd3914c5e96164385d61fbe7fa5 | import sys
import time
import math
from neopixel import *
count = int(sys.argv[1])
percent = int(sys.argv[2])
# LED strip configuration:
LED_COUNT = count # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000 # LED signal frequency in he... |
685 | 07d574060ded0d98734b4f184dcba7377b3a5480 | from datetime import datetime
import whois
def age_domain(url):
try:
w = whois.whois(url)
if(w):
for l in w.expiration_date:
d1 = datetime.date(l)
print(d1)
for l1 in w.creation_date:
d2 = datetime.date(l1)
print(d2)
diff = (d1 - ... |
686 | a4db12fee72989f983c1069839dc0a5ede4561a3 | from django.contrib.postgres.fields import JSONField
from django.db import models
from service.models import TimeStampedModel
class Praise(TimeStampedModel):
class Meta:
verbose_name = '칭찬'
verbose_name_plural = verbose_name
content = models.CharField(verbose_name='내용', unique=True, max_leng... |
687 | c70aa1a373530ac73553753e62d3989f5bc79287 | #!/usr/bin/env python
import urllib
class LicenseChecker( object ):
def __init__( self ):
self.url = 'http://logon.guidoaccardo.com.ar/'
self.count_offline = 15
def __countTimes( self ):
ff = open( 'times.ehead', 'r' )
bb = ff.read()
ff.close()
return int( bb )
... |
688 | 8680c033662a89ed6fc73e65ec544b93558c4208 | from .feature import slide_show
def main(args=None):
if args:
slide_show(args[0])
|
689 | 56892e125934d5de937b92a08bd7707c12c70928 | # 4, [[1,0],[2,0],[3,1],[3,2]]
# 3->1->0
# \ ^
# \ |
# \> 2
# 1,0,2,3
# stack 3
#
# 0 1 2 3
# 1,0
# stack 1
# 0
#
# def findOrder(numCourses, prerequisites):
# if len(prerequisites) == 0:
# order = []
# for i in range(0, numCourses):
# order.append(i)
# return or... |
690 | efca954e1977a6f6ac9a966b3c84ba80f5b7a663 | import sys
sys.stdin = open('10989.txt', 'r')
counting_list = [0 for _ in range(10001)]
N = int(sys.stdin.readline())
for n in range(N):
counting_list[int(sys.stdin.readline())] += 1
for i, v in enumerate(counting_list):
if v:
sys.stdout.write((str(i) + '\n') * v)
|
691 | 0709d413ddbe41a0c97f94b7819fdfded241d3fc | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 16:22:21 2018
@author: SDis
"""
#import Code.Members_module
class Resources:
""" Parent class for Books and eResources containg the main data fields and related setters and getters"""
def __init__(self, title, author, publisher, year):
self.title = tit... |
692 | 9156ee034ceb8a39fc1eb3a18c1597c737814c72 | # from django.test import TestCase ,LiveServerTestCase,Client
# from MeetUps.models import*
# from django.shortcuts import reverse
# from .forms import RegistrationForm
# class MeetUpViewTest(TestCase):
# @classmethod
# def setupTestDat(cls):
# #create or get all meetups
# d... |
693 | afcadc11d23fb921eb6f8038a908de02ee763ca4 | from __future__ import absolute_import
import sys
from apscheduler.executors.base import BaseExecutor, run_job
try:
import gevent
except ImportError: # pragma: nocover
raise ImportError('GeventExecutor requires gevent installed')
class GeventExecutor(BaseExecutor):
"""
Runs jobs as greenlets.
... |
694 | bf51da12632013c62aa543ae7f02415057138c7a | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
695 | 3887516e4222504defe439e62bd24b12db3cdd84 | from django import forms
from .models import HhRequest
class WorkRequestForm(forms.ModelForm):
"""Форма заявки на премию"""
class Meta:
model = HhRequest
fields = ('profile', 'sphere', 'experience', 'work_request', 'resume')
widgets = {
'profile': forms.Select(
... |
696 | c19c3f580d7555379bd7e077b0264a3784179e93 | import sqlite3
import pandas as pd
#%matplotlib inline
import matplotlib.pyplot as plt
db_filename = 'readonly/dinofunworld.db'
conn = sqlite3.connect(db_filename)
c = conn.cursor()
c.execute("SELECT a.Name, count(c.visitorID) \
FROM attraction as a, checkin c \
WHERE \
a.AttractionID = c.attraction \
AND a.Category l... |
697 | 978f3979aee1c4361483fd61b54352e7fff8d3b3 | """Functions for parsing various strings to RGB tuples."""
import json
import re
from pathlib import Path
import importlib.resources as resources
from pilutils.basic import hex_to_rgb
__all__ = [
"parse_hex6",
"parse_hex3",
"parse_rgbfunc_int",
"parse_rgbfunc_float",
"parse_rgbfunc_percent",
"... |
698 | 8a773448383a26610f4798e12fb514248e71dc4b | import importlib
if __name__ == '__main__':
module = importlib.import_module('UserFile')
print(module.if_new_message)
print(module.ID)
|
699 | 8ce2db0a28de8ddd504b744f3c9210d1a0ed7d45 | import json
from .errors import TorrentNotValid, TorrentHashNotFound, FailedLogin, HttpException
class QBittorrentClient:
"""
QBittorent client
"""
def __init__(self, *, connector):
self.connector = connector
def login(self, username : str, password : str):
return self.connector.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.