text
string
size
int64
token_count
int64
#!/usr/bin/env python """ This module provides Migration.Update data access object. """ from WMCore.Database.DBFormatter import DBFormatter from dbs.utils.dbsExceptionHandler import dbsExceptionHandler from dbs.utils.DBSDaoTools import create_token_generator class Update(DBFormatter): """ Migration Update DAO ...
3,401
1,034
import re import pathlib from clldutils.text import strip_chars from cldfbench import Dataset as BaseDataset from cldfbench import CLDFSpec QUOTES = '“”' class Dataset(BaseDataset): dir = pathlib.Path(__file__).parent id = "lapollaqiang" def cldf_specs(self): # A dataset must declare all CLDF sets it ...
3,636
1,163
import sys import os def convert_word_to_zero_length_list(word): ls = [] # Convert each character into a zero-width sequence and save them into ls. for char in word: # Convert char to binary. binary_char = bin(ord(char)) binary_char_strip = binary_char[2:] # A zero-width se...
1,752
570
from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name='HOTT', version='0.1', url='https://github.com/lambdaofgod/HOTT', packages=find_packages(), install_requires=requirements )
280
95
#!/usr/bin/env python3 from setuptools import setup def getRequirements(): requirements = [] with open("requirements.txt", "r") as reqfile: for line in reqfile.readlines(): requirements.append(line.strip()) return requirements def getVersion(): return "0.0.2" setup( python...
736
247
from django.forms import Form, ModelForm, CharField, Textarea from django.db import transaction from django.utils.translation import gettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import ForumPost, ForumThread, ForumBoard, ForumPostEdit class NewThrea...
4,340
1,269
#!/usr/bin/env python import math,os,sys try: from optparse import OptionParser except: from optik import OptionParser def main(): (star,mline,line_name,output) = parse_command_line() aa=open(star,"r") instar_line=aa.readlines() out=open(output,"w") for i in range(0,mline): if (instar_line[i].split()): ...
1,467
704
########################################################################## # # Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
2,639
906
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
18,444
6,117
# -*- coding: utf-8 -*- """ Created on Wed Mar 23 12:50:34 2016 @author: alex """ from AlexRobotics.dynamic import Manipulator as M from AlexRobotics.dynamic import Hybrid_Manipulator as HM from AlexRobotics.control import DPO_features as DPO import numpy as np # Define dynamic system R = HM.Hy...
1,149
581
import os.path from depthaware.data.base_dataset import * from PIL import Image import time def make_dataset_fromlst(dataroot, listfilename): """ NYUlist format: imagepath seglabelpath depthpath HHApath """ images = [] segs = [] depths = [] HHAs = [] with open(listfilename) as f: ...
5,294
1,868
""" Flask-gTTS ------------- A Flask extension to add gTTS Google text to speech, into the template, it makes adding and configuring multiple text to speech audio files at a time much easier and less time consuming """ from setuptools import setup setup( name='Flask-gTTS', version='0.11', url='https://g...
1,382
453
from Arquivo1 import Produto #READ #Consultar o Banco de dados #1.Retorna todas as informações do Banco de dados produtos = Produto.objects() print(produtos) for produto in produtos: print(produto.Nome, produto.Valor)
232
90
""" ----------------------------------ABOUT----------------------------------- Author: Arun Baskaran -------------------------------------------------------------------------- """ import model_params def smooth(img): return 0.5*img + 0.5*( np.roll(img, +1, axis=0) + np.roll(img, -1, axis=0) + np.r...
9,280
3,539
from flask_script import Manager from src import app manager = Manager(app) if __name__ == "__main__": manager.run()
125
41
#CIFAR from tensorflow import keras import numpy as np import matplotlib.pyplot as plt data = keras.datasets.cifar10 activations=[keras.activations.sigmoid, keras.activations.relu, keras.layers.LeakyReLU(), keras.activations.tanh] results=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] class_names=[0,1,2,3,4,5,6,7,8,9] ...
1,355
475
# ENME 489Y: Remote Sensing # Edge detection import numpy as np import matplotlib import matplotlib.pyplot as plt # Define slice of an arbitrary original image f = np.empty((0)) index = np.empty((0)) # Create intensity data, including noise for i in range(2000): index = np.append(index, i) if i <= 950: ...
3,127
1,318
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayCommerceReceiptBatchqueryModel(object): def __init__(self): self._level = None self._out_biz_no_list = None @property def level(self): return self._level ...
1,850
641
import unittest from datetime import datetime, timezone from pyfuppes import timeconversion class TestTimeconv(unittest.TestCase): @classmethod def setUpClass(cls): # to run before all tests print("testing pyfuppes.timeconversion...") @classmethod def tearDownClass(cls...
2,632
1,187
"""This module contains the meta information of LstorageClone ExternalMethod.""" from ..ucscentralcoremeta import MethodMeta, MethodPropertyMeta method_meta = MethodMeta("LstorageClone", "lstorageClone", "Version142b") prop_meta = { "cookie": MethodPropertyMeta("Cookie", "cookie", "Xs:string", "Version142b", "In...
1,111
379
import sys import glob import serial import ttk import tkFileDialog from Tkinter import * #for plotting we need these: import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt from drawnow import * class MainView: #CLASS VARIABLES: closing_status = False powerW = [] def __init__(se...
7,468
2,245
from django.test import TestCase, Client from django.urls import reverse from shop.products.models import Product from tests.base.mixins import ProductTestUtils class ProductDetailsTest(ProductTestUtils, TestCase): def setUp(self): self.client = Client() self.product = self.create_product( ...
900
260
import socket import threading import os import sys from pathlib import Path #--------------------------------------------------- def ReadLine(conn): line = '' while True: try: byte = conn.recv(1) except: print('O cliente encerrou') return 0 ...
4,558
1,501
# -*- coding: utf-8 -*- import random sentences = [ "Going into the #dogpark is not allowed, @%s.", "That's my favourite #dogpark @%s - no one is allowed to go into it!", "That #dogpark you mention is forbidden! Please don't, @%s", "The #dogpark should be secured with electrified barbwire. " "Don...
2,424
773
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from scipy import spatial import unittest from caffe2.proto import caffe2_pb2 from caffe2.python import core from caffe2.python import workspace from...
3,595
1,305
from numbers import Integral import torch from torch.autograd import Function from torch._thnn import type2backend from . import _all_functions from ...modules.utils import _pair from ...functional import _check_bilinear_2d_scale_factor class _UpsamplingBase(Function): def __init__(self, size=None, scale_factor...
4,497
1,312
# --- Day 17: Trick Shot --- import math import time def get_puzzle_input(filepath): with open(filepath) as f: for line in f: # target area: x=269..292, y =-68..-44 parts = line.rstrip().replace(',', '').split() [x1, x2] = parts[2][2:].split("..") [y1, y2] =...
7,869
2,817
import zipfile zip_file = zipfile.ZipFile("zip_archive.zip", "w") zip_file.write("textfile_for_zip_01") zip_file.write("textfile_for_zip_02") zip_file.write("textfile_for_zip_03") # print(zipfile.is_zipfile("zip_archive.zip")) # zip_file = zipfile.ZipFile("zip_archive.zip") # print(zip_file.namelist()) ...
568
250
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # # Copyright © 2018 Dell Inc. or its subsidiaries. All rights reserved. # Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries. # Other trademarks may be trademarks of their respective owners. # # Licensed under the Apache License, Ver...
21,024
6,202
import argparse import os import sqlite3 from django.core.management.base import BaseCommand from playthrough.models import Alias, Channel, Game, GameConfig, Guild, RoleTemplate, User class Command(BaseCommand): help = 'Migrates a DB from \'Shogun\' bot (SciADV-Community/playthrough-bot).' @staticmethod ...
3,196
1,008
import logging from datetime import datetime import numpy as np from logging.config import dictConfig from kafkawrapper.producer import Producer from utils.mongo_utils import BenchMarkingProcessRepo from configs.configs import ulca_notifier_input_topic, ulca_notifier_benchmark_completed_event, ulca_notifier_benchmark_f...
5,233
1,449
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-20 16:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Cre...
1,780
528
class Rektangel: def __init__(self, start_x, start_y, bredde, hoyde): self.start_x = start_x self.start_y = start_y self.hoyde = hoyde self.bredde = bredde def areal(self): return self.bredde*self.hoyde # Endrer høyde og bredde på en slik måte at areal forblir det s...
1,603
648
from datetime import datetime import discord import itertools from .utils import formatString, getUsageEmbed, getOopsEmbed # IDEAS # 1. Paying out points (without bets) class DiscordPoints: """ Class that parses Discord Points info and interactions Attributes __________ fire (Fire obj): The fire...
16,024
4,494
from django.contrib import admin from .models import MenuFacebook, MenuEmail, UserProfile, Occupation, FacebookRestaurant, EmailRestaurant class MenuBaseAdmin(admin.ModelAdmin): list_display = ('id', 'format_date', 'is_lunch', 'message') list_filter = ('created_date', 'is_lunch') list_editable = ('is_lun...
1,579
511
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
19,082
5,301
Script to read temperature data from the DHT11: # Importeer Adafruit DHT bibliotheek. import Adafruit_DHT import time als = True while als: humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4) #on gpio pin 4 or pin 7 if humidity is not None and temperature is not None: humidity ...
2,740
997
""" Module containing helper routines for routes """ from typing import Dict, Any, Set, List, Tuple import numpy as np from route_distances.utils.type_utils import StrDict def calc_depth(tree_dict: StrDict, depth: int = 0) -> int: """ Calculate the depth of a route, recursively :param tree_dict: the ro...
4,168
1,298
from __future__ import print_function from node.tests import NodeTestCase from yafowil.base import factory from yafowil.compat import IS_PY2 import lxml.etree as etree import sys import unittest import yafowil.common import yafowil.compound import yafowil.persistence import yafowil.table if not IS_PY2: from impor...
1,920
657
from foolbox.attacks import LinfinityBasicIterativeAttack from foolbox.criteria import Misclassification from foolbox.distances import MSE from tools.foolbox.adversarial_attack import AdversarialAttack class BIMAttack(AdversarialAttack): def __init__(self, model, step_size_iter=0.05, max_perturbation=0.3, n_iter...
1,350
403
# Tabuada em Python def tabuada(x): for i in range(10): print('{} x {} = {}'.format(x, (i + 1), x * (i + 1))) print() if __name__ == '__main__': print(9 ) nro = int(input('Entre com um número: ')) print(f'\n\033[1;32mTabuada do {nro}'+'\n') tabuada(nro)
292
134
# -*- coding: utf-8 -*- ''' Created on Dec 01, 2012 @author: Mourad Mourafiq About: This is an attempt to implement the radix tree algo. Features : -> insert -> remove -> search ''' NOK = "{'':[]}" class Prefixer(): def __init__(self): self.__data = {} def __repr__(self): retu...
3,235
898
class Animal(object): def __init__(self,name,health): self.name = name self.health = 50 def walk(self): self.health = self.health - 1 return self def run(self): self.health = self.health - 5 return self def display_health(self): print "Healt...
1,264
439
from typing import Union, List, Dict import numpy as np import pandas as pd from ai4water.utils.utils import jsonize, deepcopy_dict_without_clone from ai4water.preprocessing.transformations import Transformation class Transformations(object): """ While the [Transformation][ai4water.preprocessing.transforma...
17,915
4,617
import os import dgl import time import argparse import numpy as np import torch as th import distutils.util import torch.nn.functional as F import utils import models import data_loader os.environ["CUDA_VISIBLE_DEVICES"] = '0' dev = th.device('cuda' if th.cuda.is_available() else 'cpu') if __name__ == '__main__': ...
3,684
1,350
#!/usr/bin/env python """ BSD 3-Clause License Copyright (c) 2017, SafeBreach Labs All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notic...
27,127
7,377
from __future__ import print_function from configurations import configuration from pymongo import MongoClient MONGO_HOST= configuration.MONGO_HOST client = MongoClient(MONGO_HOST) class DBConnection(): def getConnection(self): return client.analyticsDB
269
72
from typing import Any, List from dataclasses import dataclass, replace from .consts import OK class Data: def replace(self, **kwargs): return replace(self, **kwargs) @dataclass(frozen=True) class RpcCall(Data): route: str service: str method: str args: List[Any] @dataclass(frozen=Tr...
448
150
#!/usr/bin/python import timeit setup = ''' import os def FileTest(path): file = open(path, "r") lines = file.readlines() data = [None for i in range(len(lines))] i = 0 for line in lines: data[i] = line.split(',') j = 0 for field in data[i]: data[i][j] = field.strip('\\'\\n') j += 1 i += 1 re...
598
266
# -*- coding: utf-8 -*- ''' Created on 25.9.2011 @author: xaralis ''' from model_utils import Choices SEXES = Choices( (1, 'FEMALE', u'žena'), (2, 'MALE', u'muž') ) NATIONALITIES = Choices( (1, 'CZ', u'Česká republika'), (2, 'EU', u'Jiné - EU'), (3, 'NON_EU', u'Jiné - non-EU'), (4, 'UNKNOWN', ...
5,475
2,837
import os import sys import json import pickle import h5py from tqdm import tqdm import numpy as np import torch import cv2 import scipy.spatial import hydra from face_expression import utils from face_expression.third_party.face_mesh_mediapipe import FaceMeshMediaPipe # class VoxCeleb2FaceDataset(torch.utils.data...
23,569
7,950
###################################################################### # OLED_Clock.py # # This program display date and time on OLED module ###################################################################### import Adafruit_SSD1306 from datetime import datetime import time from PIL import Image from PIL impo...
1,316
448
''' Contains the extended FastAPI router, for simplified CRUD from a model ''' from typing import Any, List, Optional, Sequence, Set, Type, Union import fastapi from fastapi import Depends, params from pydantic import BaseModel, create_model from odim import Odim, OkResponse, SearchResponse from odim.dependencies imp...
9,601
2,646
# Princess No Damage Skin (30-Days) success = sm.addDamageSkin(2432803) if success: sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.")
194
70
import asyncio import aiohttp import pytest from .client import HttpClient from .constant import Url from .product import Product @pytest.mark.asyncio async def test_show_portfolio(tracing_client): return await tracing_client.equities.list() @pytest.mark.asyncio async def test_find_products_by_name(tracing_cl...
1,184
357
import numpy as np from PIL import Image, ImageOps class BaseImage(object): """ 変換元画像 """ def __init__(self, path): """ 元画像を読み込む :param path: :param array: np.ndarray :param line_height: int :return: """ image = Image.open(path) a...
1,346
494
from collections import namedtuple RGB = namedtuple("RGB", "red, green, blue") COLORS = { "red": RGB(255, 0, 0), "orange-deep": RGB(255, 40, 0), "orange": RGB(255, 120, 0), "yellow": RGB(255, 200, 0), "yellow-acid": RGB(160, 255, 0), "green": RGB(0, 255, 0), "green-forest": RGB(34, 139, 34...
2,839
1,352
from nspawn.support.header import * def test_header(): print() head_dict = { 'etag':'some-hash', 'last-modified':'some-time', 'content-length':'some-size', 'nspawn-digest':'some-text', } assert head_dict[Header.etag] == 'some-hash' assert head_dict[Header.last_modi...
1,247
420
#!/usr/bin/env python from helpers import sjoin, cjoin from random import shuffle card_types = [ ("tax",1,1), # tax everyone 2 coins => bank ("soldier",2,1), ("sergeant",3,1), ("captain",4,2), ("emperor",1,5), ("prince",1,1), #...
2,042
685
#! /usr/bin/env python # # Usage: # python # import sys import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style="darkgrid") data = np.loadtxt(sys.argv[1]) kappa_LB, kappa_CNN = data.T kappa_LB = 10.0 ** kappa_LB kappa_CNN = 10.0 ** kappa_CNN fig, ax = plt.subplots(1, 1, sharey=True, ...
683
307
import bson import json import swifty # # GET /tasks -- list tasks # POST /tasks $BODY -- add new task # GET /tasks/ID -- get info about task # PUT /tasks/ID -- update task (except status) # DELETE /tasks/ID -- remove task # POST /tasks/ID/done -- mark task as done # def toTask(o...
1,664
575
# https://dmoj.ca/problem/tss17a # https://dmoj.ca/submission/2226280 import sys n = int(sys.stdin.readline()[:-1]) for i in range(n): instruction = sys.stdin.readline()[:-1].split() printed = False for j in range(3): if instruction.count(instruction[j]) >= 2: print(instruction[j]) ...
401
141
from todo.templatetags.todo_tags import is_management from django.contrib.auth.decorators import login_required, user_passes_test from django.http import HttpResponse from django.shortcuts import render from todo.models import Designer, Management, Writer, Editor @login_required @user_passes_test(is_management) def u...
1,159
348
# Copyright (c) 2019, The Personal Robotics Lab, The MuSHR Team, The Contributors of MuSHR # License: BSD 3-Clause. See LICENSE.md file in root directory. from .waypoints import Waypoints __all__ = ["Waypoints"]
214
79
from typing import List import heapq # Definition for an Interval. class Interval: def __init__(self, start: int = None, end: int = None): self.start = start self.end = end class Solution: def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]': allinterval = [] he...
1,401
457
from bluepy import btle import concurrent from concurrent import futures import threading import multiprocessing import time from time_sync import * import eval_client import dashBoardClient from joblib import dump, load import numpy # to count labels and store in dict import operator # to get most predicted label im...
41,312
12,639
import unittest from treeno.base import PrintMode, PrintOptions from treeno.expression import Array, Field, wrap_literal from treeno.orderby import OrderTerm, OrderType from treeno.relation import ( AliasedRelation, Lateral, SampleType, Table, TableQuery, TableSample, Unnest, ValuesQuer...
3,100
1,003
import random from blaze.chrome.har import har_from_json, Har, HarLog, HarEntry, Request, Response from blaze.config.environment import ResourceType from blaze.preprocess.har import get_har_entry_type, har_entries_to_resources from blaze.util.seq import ordered_uniq from tests.mocks.config import get_config from test...
4,257
1,216
from Budget import Budget, Item FILENAME = 'Budget.txt' def scrape_off_char(s, c): out = '' for ch in s: if ch != c: out += ch return out def load_budget(): try: fr = open(FILENAME, 'r') lines = fr.readlines() fr.close() b = Budget()...
1,245
423
# -*- coding: utf-8 -*- import unittest import pytest from .solution import calc_minimum_travels class CalcMininumTravelsTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_calc_minimum_travels(self): assert calc_minimum_travels([4, 5, 2, 3, 1])...
448
193
#!/usr/bin/env python import sys from serial.tools import list_ports import serial import tweepy # locate ESP32-C3 USB device port = None for device in list_ports.comports(): if device.vid == 0x303a and device.pid == 0x1001: break if not device: sys.exit(-1) ser = serial.Serial(device.device, baudrat...
2,573
927
from menpofit.result import (ParametricIterativeResult, MultiScaleParametricIterativeResult) class LucasKanadeAlgorithmResult(ParametricIterativeResult): r""" Class for storing the iterative result of a Lucas-Kanade Image Alignment optimization algorithm. Parameters -...
4,664
1,236
import os import keras import skimage.io import keras_contrib.applications from metrics import * from mrcnn import utils from mrcnn import config from imgaug import augmenters as iaa from dataset import Dataset, PoseEstimationDataset import numpy as np import keras.backend as K import mrcnn.model as modellib class Con...
6,533
2,760
from django.conf.urls import include, url from donations.views import DonateAPI, VerifyAPI app_name = 'donations' api_urls = ([ url(r'^donate/$', DonateAPI.as_view(), name="donate"), url(r'^verify/(?P<pk>[0-9]+)$', VerifyAPI.as_view(), name="verify"), ], "donations") donations = ([ url(r'^api/', include...
442
166
""" Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. """ import os.path from fabric.api import local from fabric.api import env def __ensure_in_vagrant_dir(): """ ...
3,004
905
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 19 23:38:25 2022 @author: goran """ from ..general_cp import GeneralCP from ..cp_utils import to_degrees, dihedral_angle, normal from math import sqrt, pi, tan, atan2 box_packing_cell_nodes = {'A': (2, 0), 'B': (4, 0), ...
1,988
800
from __future__ import absolute_import, print_function, unicode_literals import functools import logging import time import uuid import dill import kafka from kafka.errors import KafkaError from kq.job import Job class Queue(object): """KQ queue. A queue serializes incoming function calls and places them ...
11,001
3,073
""" accel_adxl345.py This modules defines the AccelADXL345 class for streaming data from the ADXL345 accelerometers. """ import time import serial import sys import numpy import struct BUF_EMPTY_NUM = 5 BUF_EMPTY_DT = 0.05 class AccelADXL345(serial.Serial): def __init__(self, **kwarg): # Command ids ...
8,683
2,699
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "E09000030" addresses_name = "local.2018-05-03/Version 2/Democracy_Club__03May2018.tsv" stations_name = "local.2018-05-03/Version 2/Democracy_Club__03May2018.t...
831
325
import struct from collections import OrderedDict from configparser import RawConfigParser from pynaja.common.async_base import Utils from pynaja.common.error import ConstError class Result(dict): """返回结果类 """ def __init__(self, code=0, data=None, msg=None, details=None): super().__init__(code=...
8,490
3,000
# coding:utf-8 import numpy as np import tensorflow as tf from layers import * from MobilenetV2 import MobilenetV2,MobilenetV2_dynamic class YOLOV3(object): def __init__(self, training,numcls=20): self.__training = training self.__num_classes = numcls self.__strides=[8,16,32] def build...
15,178
4,728
# -*- coding: utf-8 -*- # Copyright (c) 2020 Warpnet B.V. import re from saltlint.linter.rule import DeprecationRule from saltlint.utils import LANGUAGE_SLS class CmdWaitRecommendRule(DeprecationRule): id = '213' shortdesc = 'SaltStack recommends using cmd.run together with onchanges, rather than cmd.wait' ...
654
230
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
7,818
2,593
import pygame import sys import time import random from pygame.locals import * # Pygame Init pygame.init() # Play Surface size = width, height = 800, 800 screen = pygame.display.set_mode(size) pygame.display.set_caption("Snake Change") # Colors red = (255, 0, 0) green = (0, 255, 0) black = (0, 0, 0) white = (255, 25...
6,636
2,544
from .modules.common import * import numpy as np import os from .modules.rs_structs import getRSformat class RockstarFile(object): def __init__(self,binfile,data,galaxies,debug): self.galaxies = galaxies self.binfile = binfile self.debug = debug self.header() self....
4,203
1,633
import boto3 from datetime import datetime, date import re import string import pandas as pd from spellchecker import SpellChecker import uuid import psycopg2 from psycopg2 import sql import sys sys.path.append('.') from rule_processing import postgresql def queryTable(conn, table): cmd = """ SELECT * FROM ...
7,019
2,197
import datetime from bgmi.script import ScriptBase from bgmi.utils import parse_episode class Script(ScriptBase): class Model(ScriptBase.Model): bangumi_name = "TEST_BANGUMI" cover = "" update_time = "Mon" due_date = datetime.datetime(2017, 9, 30) def get_download_url(self): ...
1,182
461
from collections import deque def fill_the_box(*args): box_size = args[0] * args[1] * args[2] args = deque(args[3:]) while args: curr_arg = args.popleft() if curr_arg == "Finish": break box_size -= curr_arg if box_size < 0: args.remove("Finish") ...
677
290
import smart_imports smart_imports.all() # for external code ViewError = utils_exceptions.ViewError class Context(object): def __setattr__(self, name, value): if hasattr(self, name): raise ViewError(code='internal.try_to_reassign_context_value', message=conf.set...
19,617
5,717
__version__ = '0.10.0' from NeoAnalysis.spikedetection import SpikeDetection from NeoAnalysis.spikesorting import SpikeSorting from NeoAnalysis.analogfilter import AnalogFilter from NeoAnalysis.graphics import Graphics from NeoAnalysis.popuanalysis import PopuAnalysis
269
89
class HiddenPeople(): """Class for holding information on people""" def __init__(self): self.people = { 'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False, 'glasses': True, 'moustache': False}, ...
5,021
1,595
import click from typing import Any, Optional from paperplane.backends.click import _prompt def run(prompt: str, choices: list, default: Optional[Any] = None): return _prompt(text=prompt, default=default, type=click.Choice(choices=choices))
247
76
"""Implementation of allocation API. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from treadmill import discovery from treadmill import context _LOGGER = logging.getLogger(__name__) class AP...
1,012
280
from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. def index(request): return HttpResponse('Hello World</en>')
167
47
""" Clusters Bob Ross paintings by features. By Walter Hickey <walter.hickey@fivethirtyeight.com> See http://fivethirtyeight.com/features/a-statistical-analysis-of-the-work-of-bob-ross/ """ import numpy as np from scipy.cluster.vq import vq, kmeans, whiten import math import csv def main(): # load data into ve...
1,834
605
import os import sys import json from corvette.autoindex import autoindex def main(): if len(sys.argv) == 2: conf_path = sys.argv[1] else: print("Usage: python -m corvette path/to/corvetteconf.json") return dirname = os.path.dirname(__file__) # First load default conf de...
880
287
#!/usr/bin/python import sensor import lcd import csv import time import os import datetime import sys import re import circular_buffer lcd.init() last_time = datetime.datetime.now() last_minute = last_time.minute probe_minute_01 = circular_buffer.CircularBuffer(size=30) probe_minute_15 = circular_buffer.CircularBu...
1,965
705
#!/usr/bin/python3 # I don't believe in license. # You can do whatever you want with this program. import os import sys import re import time import requests import random import argparse from urllib.parse import urlparse from functools import partial from colored import fg, bg, attr from multiprocessing.dummy import...
9,988
3,492
from flask import abort from flask import current_app from flask import g from flask import request from flask import session from info import constants from info import db from info.models import Category, News, User from info.utils.response_code import RET from . import profile_blue from flask import render_template...
7,952
3,115
""" Solves a 3x3 square programmatically. It is not meant to be a full blown solution for magic squares, but rather a writeup of my thoughts on how it can be solved. """ import statistics def make_pairs(I, mid): """ We take pairs as [ [9, 1], [8, 2], [7, 3], [6, 4]] :param I: :param mid: :return:...
962
384