text
string
size
int64
token_count
int64
# script to read-in CID list and write out cgi XML files # for molecule downloads from pubchem using PUG REST # usage: 1_write_cgi_PUG_v1.4.py pcba-aid411_activities.csv import pandas as pd import sys def dump_cgi_xml( outfile, cid_list, AID, AID_chunk ): '''write out a cgi xml file for fetching''' outfi...
2,280
948
# -*- coding: utf-8 -*- # This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2017 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from pymor.core.interfaces import ImmutableInterface class InstationaryP...
1,974
632
import importlib import sys import pituophis # check if the user is running the script with the correct number of arguments if len(sys.argv) < 2: # if not, print the usage print('usage: pituophis [command] cd [options]') print('Commands:') print(' serve [options]') print(' fetch [url] [options]')...
3,183
1,051
# Run as script using 'python -m test.synth' import cPickle import os import scipy.io from models.model_factory import * from inference.gibbs import gibbs_sample from utils.avg_dicts import average_list_of_dicts from synth_harness import initialize_test_harness from plotting.plot_results import plot_results from popul...
1,711
600
""" Every name reference is swapped for a call to ``__autoimport__``, which will check if it's part of the locals or globals, falling back to trying an import before giving up. """ from importlib import import_module from ast import NodeTransformer, copy_location, fix_missing_locations, \ AST, Call, Name, Load, St...
1,297
399
from PyQt5 import QtWidgets, QtCore, QtGui from pyqtgraph import SignalProxy class TaskWidget(QtWidgets.QWidget): def __init__(self, task, rate_limit=0.01, parent=None): super().__init__(parent=parent) self.task = task self.init_ui() proxy_config = { 'signal': self.task...
4,983
1,540
"""Test functions for pem.fluid.bw92 module """ import pytest from pytest import approx from _pytest.fixtures import SubRequest from hypothesis import given, settings, strategies as st import numpy as np import digirock.fluids.bw92 as bw92 from .strategies import n_varshp_arrays @pytest.fixture(scope="...
15,742
7,855
from localground.apps.lib.helpers import get_timestamp_no_milliseconds from localground.apps.site.api import filters from localground.apps.site import models from rest_framework import generics, status, exceptions from localground.apps.site.api.serializers.user_profile_serializer import \ UserProfileSerializer from...
3,103
816
import unittest from mymoney.apps.bankaccounts.factories import BankAccountFactory from mymoney.core.factories import UserFactory from ..factories import BankTransactionTagFactory from ..models import BankTransactionTag class ManagerTestCase(unittest.TestCase): def setUp(self): self.owner = UserFactory...
1,859
509
# Generated by Django 2.1.5 on 2019-08-28 07:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0016_friends'), ] operations = [ migrations.AlterModelOptions( name='friends', options={'verbose_name': 'Friend Lis...
690
219
""" A list of stopwords to filter out, in addition to those that are already being filtered by the built-in toolkit. """ CustomStopwords = ['alltid', 'fler', 'ta', 'tar', 'sker', 'redan', 'who', 'what', 'gilla', 'big', 'something','fler', 'cv', 'snart', 'minst', 'kunna', '000', 'hr-plus', 'enligt...
819
325
import tensorflow as tf from tensorflow.compat.v1 import logging logging.set_verbosity("INFO") logging.info("TF Version:{}".format(tf.__version__)) try: import horovod.tensorflow as hvd no_horovod = False except ModuleNotFoundError: logging.warning("No horvod module, cannot perform distributed training") ...
5,612
1,805
# import pytest def test_imports(): import vera from vera import RV def test_dace(): from vera.query_dace import get_observations _ = get_observations('HD10180', verbose=False) def test_read_rdb(): from vera import RV from os.path import dirname, join here = dirname(__file__) s = R...
871
344
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Project: Hangman File: hangman.py Author: Korvin F. Ezüst Created: 2017-11-24 IDE: PyCharm Community Edition Synopsis: hangman.py [ARGUMENT] Description: A simple hangman game that runs in the command li...
11,664
3,865
import json import os import typing import codecs import typing import os import json import dill from dataclasses import dataclass, field ENCODED_PICKLE = "encodedpickle" class TutorialJsonIOManager(typing.List[str]): """ TutorialJsonIOManager will read step results from a json file """ def __init_...
4,974
1,489
import sys sys.path.append('../') sys.path.append('../..') import cmbnncs.utils as utils import cmbnncs.spherical as spherical import cmbnncs.simulator as simulator import numpy as np import time start_time = time.time() def sim_Dust(dust_seed, frequ, amplitude_randn, spectralIndex_randn, temp_randn): ### ComDust ...
3,382
1,428
# -*- coding: utf-8 -*- # Copyright (c) 2012-2018, Anima Istanbul # # This module is part of anima-tools and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause import os import nuke from nukescripts import * from anima.env import empty_reference_resolution from anima.env.base import...
14,140
3,844
from .base import * # noqa INSTALLED_APPS += [ "api_test", ] ROOT_URLCONF = "api_test.urls"
99
45
# Generated by Django 3.2.4 on 2021-07-22 09:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0175_lotv2_lots_v2_year_87d135_idx'), ('certificates', '0010_auto_20210509_1038'), ] operations = [...
2,015
610
from .datafetcher import fetch_measure_levels from .stationdata import build_station_list, update_water_levels from .flood import stations_highest_rel_level import numpy as np import matplotlib import matplotlib.pyplot as plt from datetime import datetime, timedelta from floodsystem.station import inconsistent_typical_...
2,206
764
s = raw_input() find = 'bob' count = 0 index = 0 while index < len(s): index = s.find(find, index) if index == -1: break index += 2 count += 1 print "Number of times bob occurs is:", count
232
80
""" module to methods to main """ import sys from .migrate_isis import migrate_isis_parser from .migrate_articlemeta import migrate_articlemeta_parser from .tools import tools_parser def main_migrate_articlemeta(): """ method main to script setup.py """ sys.exit(migrate_articlemeta_parser(sys.argv[1:])) ...
533
195
# -*- coding: utf-8 -*- """ zang.domain.fraud_control_rule_whitelisted ~~~~~~~~~~~~~~~~~~~ `FraudControlRuleElement` model """ from zang.domain.base_resource import BaseResource from zang.domain.fraud_control_rule import FraudControlRule class FraudControlRuleElement(BaseResource): _map = { 'blocked': ...
721
228
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'installer.ui' ## ## Created by: Qt User Interface Compiler version 5.15.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################...
6,321
1,967
# Generated by Django 2.1.5 on 2019-02-06 23:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('paginas', '0013_auto_20190206_1739'), ] operations = [ migrations.AlterField( model_name='players_lobby', name='slot...
404
151
import singer from tap_kit import TapExecutor from tap_kit.utils import (transform_write_and_count) LOGGER = singer.get_logger() class GleanExecutor(TapExecutor): def __init__(self, streams, args, client): """ Args: streams (arr[Stream]) args (dict) client (B...
2,231
628
# import logging # logging.basicConfig(filename='example.log',level=logging.DEBUG) # logging.debug('This message should go to the log file') # logging.info('So should this') # logging.warning('And this, too ã') class ValidaSmart(): def __init__(self): self._carrega_modulos_externos() def _carrega_mod...
4,028
1,389
''' architecture for sftmd ''' import torch import torch.nn as nn import torch.nn.functional as F class Predictor(nn.Module): def __init__(self, input_channel=3, code_len=10, ndf=64, use_bias=True): super(Predictor, self).__init__() self.ConvNet = nn.Sequential(*[ nn.Conv2d(input_chan...
14,376
6,101
from django.conf.urls import include, url from django.contrib import admin from glue.views import * from glue.api import * urlpatterns = [ # Examples: # url(r'^$', 'server.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^api/user/data/', view=user_data), url(r'^api/user/si...
539
208
#!/usr/bin/env python """ LIVE STREAM TO YOUTUBE LIVE using FFMPEG -- from webcam https://www.scivision.co/youtube-live-ffmpeg-livestream/ https://support.google.com/youtube/answer/2853702 Windows: get DirectShow device list from: ffmpeg -list_devices true -f dshow -i dummy """ from youtubelive_ffmpeg import youtu...
1,040
368
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import json import logging from threathunter_common.util import millis_now from nebula_meta.model import Strategy from .base_dao import BaseDao, BaseDefaultDao from . import cache from ..models.default import StrategyDefaultModel as M...
17,943
5,754
# http://www.pythonchallenge.com/pc/bin/hex.html import bz2 import io import urllib.request import urllib.error import zipfile import zlib out_dir = "_out/idiot" prompt = "http://www.pythonchallenge.com/pc/hex/unreal.jpg" prompt_top = "http://www.pythonchallenge.com/pc/hex/" prompt_range = 1152983631 prompt_pass =...
2,205
713
from django.dispatch import Signal badge_awarded = Signal(providing_args=["badge"])
86
31
import unittest from unittest.mock import patch, Mock from werkzeug.datastructures import FileStorage import io import json from app import app from app.models.base import db from app.models.user import User from app.auth.views import UserPassportphotoView from app.auth import views class AuthUploadPassportPhotoTes...
2,596
799
import os import numpy as np import pytest from pennylane import qchem from openfermion.hamiltonians import MolecularData ref_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_ref_files") table_1 = np.array( [ [0.0, 0.0, 0.0, 0.0, 0.68238953], [0.0, 1.0, 1.0, 0.0, 0.68238953]...
6,380
4,291
# Generated by Django 2.0 on 2018-02-14 13:39 from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', ...
1,571
448
#! /usr/bin/env python """ Generic finite state machine class Initialise the class with a list of tuples - or by adding transitions Tony Flury - November 2012 Released under an MIT License - free to use so long as the author and other contributers are credited. """ class fsm(object): """ A simple to u...
6,159
1,645
from __future__ import division from optparse import OptionParser import numpy parser = OptionParser() parser.add_option("-i", "--input", dest="input", help="input file") (options, args) = parser.parse_args() def numpyImport(file): output = numpy.load("%s.npy" % file) output = output.item() return output...
873
299
from django.contrib import admin from django import forms from establishment.accounts.utils import get_user_search_fields from .models import SocialApp, SocialAccount, SocialToken, SocialProvider class SocialAppForm(forms.ModelForm): class Meta: model = SocialApp exclude = [] widgets = {...
1,631
508
"""GitHub tap class.""" from typing import List from singer_sdk import Tap, Stream from singer_sdk import typing as th # JSON schema typing helpers from tap_github.streams import ( CommitsStream, CommunityProfileStream, IssueCommentsStream, IssueEventsStream, IssuesStream, PullRequestsStream...
1,665
489
from typing import Hashable, Generator, Optional, Iterable import time import pandas as pd import sqlalchemy from sqlalchemy.pool import NullPool from sqlalchemy.sql import select from sqlalchemy import and_, or_, func from .backend import Backend _DEFAULT_SQL_URL = "sqlite:///" _DEFAULT_SQL_STR_LEN = 64 class SQL...
14,513
3,952
from django.db import models # Create your models here. from django.conf import settings from django.db import models from django.utils import timezone # Create your models here. class SearchQuery(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCAD...
475
166
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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 applicab...
2,875
977
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-01-10 08:34 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('org', '0001_initial'), ('event', '0002_auto_2018010...
585
219
import digitalio import pulseio from smbusslave import SMBusSlave IODIR = 0x00 IPOL = 0x01 GPINTEN = 0x02 DEFVAL = 0x03 INTCON = 0x04 IOCON = 0x05 GPPU = 0x06 INTF = 0x07 INTCAP = 0x08 GPIO = 0x09 OLAT = 0x0a IOCON_SEQOP = 1 << 5 IOCON_ODR = 1 << 2 IOCON_INTPOL = 1 << 1 # Pull up on interrupt pins are not supported...
9,806
3,222
import ConfigParser from datetime import datetime import os import sys import numpy as np import pandas as pd import utils.counts import utils.counts_deviation __author__ = 'Andrew A Campbell' # This script finds the days with the greatest deviation from some reference value (such as hourly means or medians) if __n...
2,084
698
from django.http import HttpResponse class HttpResponseNoContent(HttpResponse): status_code = 204
104
31
############################### # MODULE: Object settings # # AUTHOR: Yangildin Ivan # # LAST UPDATE: 08/04/2019 # ############################### import copy from enum import Enum, IntEnum from direct.gui.OnscreenText import TransparencyAttrib BLACK = (0.15, 0.15, 0.15, 1) #BLACK = (0.0, 0.0, 0.0, 1) WH...
5,457
1,954
from django.shortcuts import render from django.views import generic from django.shortcuts import redirect from django.utils import timezone from .models import Complaint from .forms import ComplaintForm class ComplaintList(generic.ListView): queryset = Complaint.objects.order_by('date') template_name = 'compl...
1,202
371
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep import time import csv import pyautogui #-------將網頁開啟的動作換為背景執行---------- options = webdriver.Chro...
4,679
2,091
# encoding: utf-8 ''' Match articles with annotated data ''' from collections import defaultdict import argparse from blamepipeline.preprocess.dataloader import Dataset case1, case2 = 0, 0 def match_data(source): dataset = Dataset(source) articles = dataset.get_articles() entries = dataset.get_entries...
2,052
588
import tensorflow as tf i = tf.compat.v1.constant(0, name="Hole") c = lambda i: tf.compat.v1.less(i, 10) b = lambda i: tf.compat.v1.add(i, 1) r = tf.compat.v1.while_loop(c, b, [i], name="While")
197
94
import unittest import decimal import prosperpy def get_prices(): prices = ['90.704', '92.900', '92.978', '91.802', '92.665', '92.684', '92.302', '92.773', '92.537', '92.949', '93.204', '91.067', '89.832', '89.744', '90.399', '90.739', '88.018', '88.087', '88.844', '90.778', '90.542',...
1,628
789
machine_number = 43 user_number = int( raw_input("enter a number: ") ) print( type(user_number) ) if user_number == machine_number: print("Bravo!!!")
156
59
import copy import numpy as np class FFDAlgorithm(object): def __init__(self, num_x, num_y, num_z, filename, object_points): #定义三坐标轴上控制点个数 self.cp_num_x = num_x self.cp_num_y = num_y self.cp_num_z = num_z self.object_points_initial = object_points def cover_obj(self, initial=T...
15,377
5,008
# from AlphaZero-AI import game
31
10
from django.test import TestCase from ..twitterAPI import search class TwitterTestCase(TestCase): """Unit test to ensure that search string is found in 100 new reddit posts returned from API""" def setUp(self): self.queryString = "Police" self.submissions = search(self.queryString) def test_submissions_contai...
721
208
from conans import ConanFile, tools import os required_conan_version = ">=1.33.0" class MioConan(ConanFile): name = "mio" description = "Cross-platform C++11 header-only library for memory mapped file IO." license = "MIT" topics = ("mio", "mmap", "memory-mapping", "fileviewer") homepage = "https:...
2,130
739
import os import math from scapy.all import * from pytest_main import eth_config from pytest_main import dump_eth_config def getstatusoutput(cmd): pipe = os.popen(cmd + " 2>&1", 'r') text = pipe.read() sts = pipe.close() if sts is None: sts=0 if text[-1:] == "\n": text = text[:-1] return sts,...
3,330
1,331
// Test calls to statebus server var bus = require('statebus/server')(); bus.ws_client("/*", "ws://aws.local-box.org:45678"); x = bus.fetch("/paul/code"); console.log(JSON.stringify(x)); if (!x.written) { console.log("No member .written found, setting it now"); x.written = "here it is"; } save(x);
304
113
# # Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRAN...
1,205
398
# Generated by Django 2.2.13 on 2020-12-07 13:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reo', '0075_auto_20201125_1947'), ('reo', '0082_chpmodel_chp_unavailability_hourly'), ] operations = [ ]
282
127
import os import sys import time import torch import torch.nn as nn import random import numpy as np import torchvision.transforms as transforms FILE_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_ROOT = os.path.join(FILE_DIR, '../../../data') sys.path.append(os.path.join(FILE_DIR, '../')) sys.path.append(os.pa...
4,020
1,199
# HANGMAN GAME from collections import namedtuple import main game_board = namedtuple('game_board', ['board', 'mistakes', 'letters', 'status']) def welcome(): """Starts the game.""" print("Welcome") word = main._choose_word() _print_start_game() _print_start_spaces(word) game_board.letters = []...
4,462
1,563
#!/bin/python3 import Canopto import pygame from pygame.locals import * import time import random import colorsys c = Canopto(2, 8, previewEnabled = True)
159
54
# ------------------------------------------------------------------------------ # Joyous events models # ------------------------------------------------------------------------------ import datetime as dt from django.db import models from django.db.models.query import ModelIterable from django.utils import timezone f...
8,246
2,281
import os import pandas as pd import random import string import numpy as np import substratools as tools class TitanicOpener(tools.Opener): def get_X(self, folders): data = self._get_data(folders) return self._get_X(data) def get_y(self, folders): data = self._get_data(folders) ...
2,534
903
# coding: utf-8 from unittest import TestCase import os import ibm_watson import pytest import json import time from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions @pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') is None, reason=...
1,064
341
from django.views.generic import ListView from rest_framework import authentication, permissions from ..models import Message,Listing,User from django.db.models import Q class ListConversationsView(ListView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.I...
1,337
372
import cv2 as cv def nothing(x): pass cv.namedWindow('Binary') cv.createTrackbar('threshold', 'Binary', 0, 255, nothing) cv.setTrackbarPos('threshold', 'Binary', 167) img_color = cv.imread('wallpaper-2994965.jpg', cv.IMREAD_COLOR) cv.imshow('Color', img_color) cv.waitKey(0) img_gray = cv.cvtC...
778
339
import asyncio import discord from discord import channel from discord.ext import commands import random from main import bot class member_joining(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_member_join(self, member): channel = ...
1,210
443
from . import common as cmmn import logging import uuid from typing import Optional from instauto.api.structs import Surface logger = logging.getLogger(__name__) class _Base(cmmn.Base): _csrftoken: str = None radio_type: str = 'wifi-none' device_id: str = None _uid: str = None _uuid: str = None ...
4,020
1,282
from IPython.display import display from ipywidgets import widgets button = widgets.Button(description="Click for answer") output = widgets.Output() display(button, output) already_clicked = False def on_button_clicked(b): global already_clicked, button if not already_clicked: already_clicked = True...
955
250
# Generated by Django 3.2 on 2021-07-02 21:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('respostas', '0015_alter_resposta_banca'), ] operations = [ migrations.AddField( model_name='resposta', name='materia',...
426
147
from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.toolbar import MDToolbar class Menus(): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __call__(self): box_central = MDBoxLayout(orientation='vertical') # criar componentes toolbar = MDToo...
523
163
# -*- coding: utf-8 -*- """ Created on Thu Jan 13 23:29:22 2022 @author: Tommaso """ from setuptools import setup VERSION = '0.2.8' DESCRIPTION = 'A python package for bspline curve approximation using deep learning' # Setting up setup( name='deep-b-spline-approximation', packages=['deep_b_spline_approximati...
1,342
461
from datetime import date from typing import Iterable from sqlalchemy.orm import Session from db_api import models, schemas def get_document(db: Session, document_id: str) -> models.Document: return db.query(models.Document).filter(models.Document.id == document_id).first() def get_documents_by_publication_da...
1,697
539
from argparse import ArgumentParser import os from displ.pwscf.parseScf import fermi_from_scf from displ.wannier.wannier_util import global_config from displ.wannier.build import Update_Disentanglement def _main(): parser = ArgumentParser(description="Update disentanglement window in W90 input") parser.add_arg...
1,571
516
"""Setup file for souliss package.""" import os from setuptools import setup, find_packages if os.path.exists('README.rst'): README = open('README.rst').read() else: README = '' setup( name='pysouliss', version='0.0.5', description='Python API for talking to a Souliss gateway gateway', long_de...
942
311
''' ScriptFile File Manager for the scriptlib package Developed by Orbtial ''' #Custom Imports from . import scriptui #Standard Imports import os def initPTPDIR(filePathAttr): """ Returns a string representation of the path to the file's parent directory. Should be initialised and stored before using any other fu...
3,485
1,000
import sys sys.path.append("/mnt/storage/apps/software/dias_config") from dias_dynamic_files import ( genes2transcripts, bioinformatic_manifest, genepanels_file, ) assay_name = "CEN" # Core Endo Neuro assay_version = "v1.1.4" ref_project_id = "project-Fkb6Gkj433GVVvj73J7x8KbV" # Single workflow ss_wor...
6,823
3,131
""" Axiom Python Client """ __version__ = "0.1.0-beta.2" from .client import * from .datasets import *
105
43
import unittest from credentialData import CredentialData class TestCredentials(unittest.TestCase): def setUp(self): """ setUp method """ self.new_credential = CredentialData("Instagram", "mimi", "mireille") def test_init(self): """ testing initialization ...
1,070
308
import numbers import random import math import torch from scripts.study_case.ID_13.torch_geometric.transforms import LinearTransformation class RandomRotate(object): def __init__(self, degrees, axis=0): if isinstance(degrees, numbers.Number): degrees = (-abs(degrees), abs(degrees)) a...
1,130
389
from datetime import datetime from typing import Any, Callable, Dict, Optional, Union from pydantic import BaseModel class BaseMetadata(BaseModel): def dict( self, *, include: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None, exclude: Union['AbstractSetIntStr', 'MappingIntStr...
4,606
1,171
from flask import Flask, render_template, Response from .OverlayCamera import OverlayCamera from .settings import ROUTE app = Flask(__name__) def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type...
594
186
"""Implements the :py:class:`SearchClient` class.""" from typing import Any, List from datetime import datetime, timezone from pymongo.collation import Collation import pymongo __all__ = ['SearchClient'] class SearchClient: """This class executes search queries.""" def __init__(self, *, db: pymongo.databa...
8,098
2,189
import unittest from cardutil import pinblock class PinblockTestCase(unittest.TestCase): def test_pin_block_Iso0(self): self.assertEqual( b'\x04\x12\x26\xcb\xa9\x87\x6f\xed', pinblock.Iso0PinBlock(pin='1234', card_number='4441234567890123').to_bytes()) def test_visa_pvv(self)...
4,110
1,935
# GPIO Zero: a library for controlling the Raspberry Pi's GPIO pins # Copyright (c) 2019 Jeevan M R <14.jeevan@gmail.com> # Copyright (c) 2019 Dave Jones <dave@waveform.org.uk> # Copyright (c) 2019 Ben Nuttall <ben@bennuttall.com> # Copyright (c) 2018 SteveAmor <steveamor@noreply.users.github.com> # # Redistribution an...
12,300
4,436
def pedir_entero (mensaje,min,max): numero = input(mensaje.format(min,max)) if type(numero)==int: while numero <= min or numero>=max: numero = input("el numero debe estar entre {:d} y {:d} ".format(min,max)) return numero else: return "debes introducir un entero" valido...
506
176
# from collections.abc import MutableMapping, MutableSequence, MutableSet from collections.abc import Sequence, Container # , Mapping, Set from collections import OrderedDict import contextlib from ruamel.yaml.constructor import ConstructorError from ruamel.yaml.nodes import MappingNode, SequenceNode def _is_contai...
2,806
801
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
2,482
770
# -*- coding: utf-8 -*- """ Created on Sun Jan 26 16:01:59 2014 @author: pi """ import time def delay(i): k=0 for j in range(i): k+=1 n=5000 j=0 a=time.time() i=1 c=time.time() d=c-a print d a=time.time() for i in range(n): j+=1 c=time.time() d=c-a print d a=time.time() delay(n) c=time.tim...
338
187
############################################################ import pytesseract import os from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont ############################################################# R_...
1,716
568
""" pdict.py -- Implement a (remote) persistent dictionary that is accessed over a socket. The backend dictionary could be dbshelve, BSDDB, or even a relational table of (key, blob). *** The purpose is to have a bullet-proof, separate-process, persistent dictionary that is very fast, globa...
12,921
3,678
from selenium import webdriver import unittest class FirefoxTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_page(self): #test method names must start with 'test' self.browser.get('http://localhost...
633
185
import timeit # bro, probably could just use %timeit if # you are on ipython. :-P starttime = timeit.default_timer() """ your code here """ endtime = timeit.default_timer() print(endtime - starttime)
204
72
import os import re from subprocess import call from time import sleep supervisor_dir = "/etc/supervisor/conf.d/" _, _, files = next(os.walk(supervisor_dir)) for f in files: m = re.match("(hortiradar-worker\d)\.conf", f) if m: worker = m.group(1) call(["supervisorctl", "restart", worker]) ...
336
121
#!/usr/bin/env python """ Main runner for the service """ from flask import Flask from flask_restful import Api from resources.rtls import Rtls def create_app(): app = Flask(__name__) api = Api(app) api.add_resource(Rtls, '/rtls/', '/rtls/<string:package>/<string:change_id>', ...
687
238
#!/usr/bin/env python # -*- coding: utf-8 -*- from ykdl.util.html import default_proxy_handler, get_content from ykdl.util.match import match1, matchall from ykdl.extractor import VideoExtractor from ykdl.videoinfo import VideoInfo from ykdl.compact import install_opener, build_opener, HTTPCookieProcessor import json...
3,205
1,142