text
string
size
int64
token_count
int64
# -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This file is part of BridgeDB, a Tor bridge distribution system. # # :authors: Nick Mathewson <nickm@torproject.org> # Isis Lovecruft <isis@torproject.o...
6,995
1,913
""" Module docstring """ def _impl(_ctx): """ Function docstring """ pass some_rule = rule( attrs = { "attr1": attr.int( default = 2, mandatory = False, ), "attr2": 5, }, implementation = _impl, )
267
87
from __future__ import print_function from connection import * from jinja2 import Environment, FileSystemLoader import webbrowser def print_report(id): env = Environment(loader=FileSystemLoader('.')) template = env.get_template("src/template.html") cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = "SELECT e.*...
2,469
942
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2021 all rights reserved # # superclass from .Schema import Schema # declaration class Container(Schema): """ The base class for type declarators that are sequences of other types """ # constants typename = 'container' # ...
2,250
617
# # Copyright The NOMAD Authors. # # This file is part of NOMAD. # See https://nomad-lab.eu for further info. # # 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/lic...
98,110
31,953
# coding: utf-8 """ simcore-service-storage API API definition for simcore-service-storage service # noqa: E501 OpenAPI spec version: 0.1.0 Contact: support@simcore.io Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 a...
41,012
12,122
# Generated by Django 3.2.7 on 2021-10-22 14:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reservation_management', '0020_greenpass'), ] operations = [ migrations.DeleteModel( name='GreenPass', ), ]
304
106
#!/usr/bin/env python """ Demos of encoding and decoding algorithms using populations of IAF neurons. """ # Copyright (c) 2009-2015, Lev Givon # All rights reserved. # Distributed under the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license import sys import numpy as np # Set matplotlib back...
3,878
1,519
"""func expr""" F = function( x,y ): return x+y def main(): TestError( F(1,2) == 3 )
90
45
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, ListAdminView SORTBY_VAR = '_sort_by' class SortablePlugin(BaseAdminPlugin): sortable_fields = ['sort'] # Media def get_media(self, media): if self.sortable_fields and self.request.GET.get(SORTBY_VAR): ...
1,266
383
import logging from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE from datetime import datetime, timedelta from pytz import timezone import celery import redis from charges import amount_to_charge, charge, ChargeException from npsp import Opportunity from util import send_email zone = timez...
2,644
841
import operator import os from unittest.mock import patch import pytest import requests from rotkehlchen.chain.ethereum.manager import NodeName from rotkehlchen.constants.assets import A_BTC from rotkehlchen.tests.utils.blockchain import mock_etherscan_query from rotkehlchen.typing import SupportedBlockchain @pytes...
3,311
1,173
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: I am # # Created: 02/11/2017 # Copyright: (c) I am 2017 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): ...
366
107
from flask import Flask from config import Config from sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_moment import Moment from flask_misaka import Misaka from flask_bootstrap import Bootstrap import os import logging ...
2,405
829
import numpy as np import random from time import time, sleep import h5py import torch import torch.nn as nn import torch.optim as optimizer import glob import os #from scipy.stats import rankdata from lstm import Model, initialize from Optim import ScheduledOptim # import _pickle as cPickle # np.set_printoptions(t...
7,252
2,430
from c_int import Int from casting import cast from globals_consts import NAMESPACE from temps import used_temps, get_temp, get_temp_func def binary_expression(copy_strings, expression, target, variables_name, vtypes): from expression import generate_expression c1, t1, tt1 = generate_expression(None, expressi...
2,031
692
#!/usr/bin/python from struct import * from getopt import * import sys import os import re def usage(): global progname print >> sys.stderr, "" print >> sys.stderr, " Usage:", progname, "[options] fname" print >> sys.stderr, "" print >> sys.stderr, "Options" print >> sys.stderr, " -h, --help show...
3,080
1,547
import os from pytest_mock import MockerFixture from robot.api import logger from Mainframe3270.x3270 import x3270 def test_set_screenshot_folder(under_test: x3270): path = os.getcwd() under_test.set_screenshot_folder(path) assert under_test.imgfolder == os.getcwd() def test_set_screenshot_folder_no...
1,186
459
# -*- coding: utf-8 -*- from __future__ import print_function, division """ .. note:: These are the spectrophotometry functions for SPLAT """ # imports - internal import copy import os # imports - external import numpy from astropy import units as u # standard units from astropy import constants...
35,752
12,333
import datetime ONE_MINUTE = 60 ONE_HOUR = 3600 ONE_DAY = 24 * ONE_HOUR ONE_YEAR = 1 * 365 * ONE_DAY def days(days): return int(days * 86400.0) def hours(hours): return int(hours * 3600.0) def minutes(minutes): return int(minutes * 60.0) def to_utc_date(timestamp): return datetime.datetime.utcfro...
629
256
""" Plot up surface or bottom (or any fixed level) errors from a profile object with no z_dim (vertical dimension). Provide an array of netcdf files and mess with the options to get a figure you like. You can define how many rows and columns the plot will have. This script will plot the provided list of netcdf datase...
4,766
1,750
from sklearn.feature_extraction.text import TfidfVectorizer def compute_tf_idf(corpus): """Computing term frequency (tf) - inverse document frequency (idf). :param corpus: List of documents. :returns: tf-idf of corpus. """ return TfidfVectorizer().fit_transform(corpus) if __name__ == '__main__': ...
500
161
#!/usr/bin/env python3 from __future__ import print_function import socket import threading try: import socketserver except ImportError: import SocketServer as socketserver import time import os import signal import sys import struct import errno from fprime.constants import DATA_ENCODING from optparse import...
18,197
5,130
import logging import sched import time ( MENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB, PANIC_BUTTON, CUSTOM_SCRIPT, ) = range(8) BOUGHT, BUYING, SOLD, SELLING = range(4) logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"...
453
188
import modutil mod, __getattr__ = modutil.lazy_import(__name__, ['tests.test_data.A', '.B', '.C as still_C']) def trigger_A(): return mod.A def trigger_B(): return mod.B def trigger_C(): return mod.still_C def trigger_failure(): return mod.does_not_exist
316
109
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import tqdm import torch import pickle import resource import numpy as np import matplotlib.pyplot as plt from args import parse_args from modelSummary import model_dict from pytorchtools import load_from_file from torch.utils.data import DataLoader ...
10,390
3,187
#!/usr/bin/env python """ <Program Name> test_util.py <Author> Konstantin Andrianov. <Started> February 1, 2013. <Copyright> See LICENSE for licensing information. <Purpose> Unit test for 'util.py' """ # Help with Python 3 compatibility, where the print statement is a function, an # implicit relative im...
21,072
7,637
from django import forms class FlightrForm(forms.Form): flight_number = forms.CharField(max_length=30, label="航班号", widget=forms.TextInput(attrs={'class': 'form-control'})) plane_type_choices = [ ('波音', ( ('1', '747'), ('2', '777'), ('3', '787'), ) ...
2,769
1,022
from functools import lru_cache from math import cos, sin import scipy from scipy.ndimage import affine_transform import numpy as np @lru_cache(maxsize=10) def get_matrix(angles=(90, 90, 90), inverse=False): """ Axis of rotation Get matrix by angle. (shear+compress) Examples: z = 120 ######...
8,282
2,846
#!/usr/bin/env python import sys #lolafile = open("ex-small.graph", "r") source = 0 target = 0 lowlink = 0 trans = "bla" print("digraph {") with open(sys.argv[1]) as lolafile: for line in lolafile: if len(line) == 1: continue linelist = line.split(" ") if "STATE" in linelist: ...
596
229
import re import urllib.parse from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from .models import Definition RE_HANGUL = re.compile(r'[(]*[\uAC00-\uD7AF]+[\uAC00-\uD7AF (),;]*', re.IGNOR...
3,098
950
import globals class ToggleSwitch(globals.Hass): async def initialize(self): config = self.args["config"] self._input = config["input"] self._toggle_service = config["toggle_service"] self._toggle_payload = config["toggle_payload"] self._power = config["power"] self...
1,867
528
#!/usr/bin/env python from __future__ import print_function ''' 1\taaaa~^~bbbb~^~cccc 2\tdddd~^~EEEE~^~ffff ''' import sys ARR_DELIM = '~^~' for row in sys.stdin: row = row.strip() sent_id, lemmas = row.split('\t') lemmas = lemmas.split(ARR_DELIM) for lemma in lemmas: print('{}\t{}'.format(s...
336
152
from django.urls import path from . import views urlpatterns = [ path('', views.SupplierList.as_view(), name='supplier_list'), path('view/<int:pk>', views.SupplierView.as_view(), name='supplier_view'), path('new', views.SupplierCreate.as_view(), name='supplier_new'), path('view/<int:pk>', views.Suppli...
528
183
import yaml __config=None def config(): global __config if not __config: with open('config.yaml', mode='r') as f: __config=yaml.safe_load(f) return __config
205
65
APP_PROFILE_DIRECTORY_NAME = 'lazies-cmd' DOSKEY_FILE_NAME = 'doskey.bat' AUTO_RUN_REGISTRY_NAME = 'AutoRun'
109
53
#!/usr/bin/env python import os, sys from Bio import SeqIO def get_seqs_from_list(fastafile, listfile): seqs = [line.strip() for line in open(listfile)] for r in SeqIO.parse(open(fastafile), 'fasta'): if r.id in seqs or r.id.split('|')[0] in seqs or any(r.id.startswith(x) for x in seqs): pr...
777
252
import time import json import base64 import msgpack from schema import Schema, And, Optional from datetime import datetime from algosdk import mnemonic from algosdk.account import address_from_private_key from algosdk.error import * from algosdk.future.transaction import PaymentTxn from inequality_indexes import * fr...
7,482
2,471
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by Andrew D. King # import logging import unittest from programmingtheiot.cda.system.SystemMem...
1,530
522
""" Django settings for api project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os from url...
9,538
3,630
# -*- coding: utf-8 -*- """Unit test package for gblackboard."""
66
27
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import fibcapi_pb2 as fibcapi__pb2 import fibcapis_pb2 as fibcapis__pb2 class FIBCApApiStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: ...
25,225
8,298
from cymbology.identifiers.sedol import Sedol from cymbology.identifiers.cusip import Cusip, cusip_from_isin from cymbology.identifiers.isin import Isin __all__ = ('Sedol', 'Cusip', 'cusip_from_isin', 'Isin')
210
85
from marshmallow import Schema, fields from marshmallow.validate import Range, Length from sqlalchemy import Column, Integer, Boolean, DateTime from ..db import Base from ..shared.models import StringTypes # ---- Error-report class ErrorReport(Base): __tablename__ = 'error_report' id = Column(Integer, prim...
948
286
#!/bin/python3 import math import os import random import re import sys # # Complete the 'findSubstring' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # def isVowel(x): if(x=="a" or x=='e' or x=='i' or x=='o' or x=='...
1,067
404
COLLECTION = 'productos'
24
9
"""Evaluation metrics.""" import numpy as np from sklearn.metrics import matthews_corrcoef # noqa from sklearn.metrics import recall_score # noqa from sklearn.metrics import cohen_kappa_score from sklearn.metrics import r2_score # noqa from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_...
4,501
1,584
from __future__ import absolute_import import operator from collections import deque import functools from abc import ( ABCMeta, abstractmethod ) import rlp_cython as rlp import time import math from uuid import UUID from typing import ( # noqa: F401 Any, Optional, Callable, cast, Dict, ...
117,896
33,084
""" This module includes functions related to the regions API endpoint. """ from django.http import JsonResponse from ...cms.models import Region from ...cms.constants import region_status from ..decorators import json_response def transform_region(region): """ Function to create a JSON from a single region ...
3,113
880
import copy import os from cli.src.Config import Config from cli.src.helpers.build_io import (get_ansible_path, get_ansible_path_for_build, get_ansible_vault_path) from cli.src.helpers.data_loader import (load_all_schema_objs_from_directory, ...
10,964
3,113
from unittest import TestCase from snail import snail class TestSnail(TestCase): def test_snail_001(self): self.assertEqual(snail([[]]), []) def test_snail_002(self): self.assertEqual(snail([[1]]), [1]) def test_snail_003(self): self.assertEqual(snail([[1, 2, 3], [4...
247,996
155,620
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
7,385
2,395
import pytest from plenum.server.view_change.view_changer import ViewChanger from stp_core.common.log import getlogger from plenum.test.pool_transactions.helper import start_not_added_node, add_started_node logger = getlogger() @pytest.fixture(scope="module", autouse=True) def tconf(tconf): old_vc_timeout = tc...
2,501
817
from abc import ABC, abstractclassmethod from model.response import ResponseModel class CacheInterface(ABC): @abstractclassmethod async def get(cls, url: str) -> ResponseModel: pass @abstractclassmethod async def set(cls, url: str, value: ResponseModel, ttl=0): pass
288
82
""" Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
16,904
5,500
import math from typing import List def jump_search(array: List[int], value: int) -> int: """ Performs a jump search on a list of integers. :param array: is the array to search. :param value: is the value to search. :return: the index of the value, or -1 if it doesn't exist.' """ if len(ar...
1,688
524
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from __future__ import annotations from dataclasses import dataclass from enum import IntEnum from typing import List, Optional, TYPE_CHECKING from ...utils.api_object import APIObject from ...utils.types import MISSING...
3,484
1,122
from django.views.generic import \ UpdateView as BaseUpdateView class UpdateView(BaseUpdateView): template_name_suffix = '_form_update'
147
45
import torch import lib.modeling.resnet as resnet import lib.modeling.semseg_heads as snet import torch.nn as nn import torch.optim as optim import utils.resnet_weights_helper as resnet_utils from torch.autograd import Variable from roi_data.loader import RoiDataLoader, MinibatchSampler, collate_minibatch, collate_mini...
3,219
1,260
import json from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions from pprint import pprint def generate_dimensions(): dimensions = [] for dimension in get_all_dimensions(): pprint (dimension) if dimension.get('measure_type').startswith('W-'): continue ...
2,511
760
"""Test Evil Genius Labs light.""" from unittest.mock import patch import pytest from homeassistant.components.light import ( ATTR_COLOR_MODE, ATTR_SUPPORTED_COLOR_MODES, ColorMode, LightEntityFeature, ) from homeassistant.const import ATTR_SUPPORTED_FEATURES @pytest.mark.parametrize("platforms", [(...
2,909
1,075
import platform import shutil import tempfile import warnings from pathlib import Path import requests from tqdm import tqdm DOCKER_VERSION = "20.10.5" BUILDX_VERSION = "0.5.1" CACHE_DIR = Path.home() / ".cache" / "python-on-whales" TEMPLATE_CLI = ( "https://download.docker.com/{os}/static/stable/{arch}/docker-...
4,410
1,431
import boto3 import json import os import logging from contextlib import closing from boto3.dynamodb.conditions import Key, Attr from botocore.exceptions import ClientError from random import shuffle import time import pyqrcode import png __BUCKET_NAME__ = "project-cerebro" dynamo = boto3.client('dynamodb') logg...
4,415
1,380
#!/usr/bin/env python #coding:utf-8 # Author: mozman --<mozman@gmx.at> # Purpose: test drawing module # Created: 11.09.2010 # Copyright (C) 2010, Manfred Moitzi # License: GPLv3 from __future__ import unicode_literals import os import unittest from io import StringIO from svgwrite.drawing import Drawing...
4,241
1,619
from django.shortcuts import render from django.utils.translation import ugettext as _ # pylint: disable=unused-argument def handler400(request, exception): ctx = {'code': 400, 'title': _('Bad request'), 'message': _('There was an error in your request.')} response = render(request, 'error_handler/...
1,480
469
from typing import NamedTuple from django.contrib.auth.models import AbstractUser from django.db import models from msg.models import Msg class User(AbstractUser): phone_number: 'str' = models.CharField(max_length=255, null=True, blank=True) class HelloSMSMessage(...
738
206
matrix = [list(map(int, input().split())) for _ in range(6)] max_sum = None for i in range(4): for j in range(4): s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3]) if max_sum is None or s > max_sum: max_sum = s print(max_sum)
280
117
class Bunch(dict): """Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, `bunch["value_key"]`, or by an attribute, `bunch.value_key`. Examples -------- >>>...
1,391
430
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
6,558
2,085
from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Q_ARG, QAbstractItemModel, QFileInfo, qFuzzyCompare, QMetaObject, QModelIndex, QObject, Qt, QThread, QTime, QUrl) from PyQt5.QtGui import QColor, qGray, QImage, QPainter, QPalette from PyQt5.QtMultimedia import (QAbstractVideoBuffer, QMediaContent, ...
23,156
6,844
#!/usr/bin/env python """Test checkpoint-like periodic snapshots. We test that there are that many folders and that the currentStep changes. """ import mirheo as mir u = mir.Mirheo(nranks=(1, 1, 1), domain=(4, 6, 8), debug_level=3, log_filename='log', no_splash=True, checkpoint_every=1...
1,234
490
#!/usr/bin/python # # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Loads a set of web pages several times on a device, and extracts the predictor database. """ import argparse import logging import os...
3,632
1,129
from abc import ABC, abstractmethod from typing import Optional from xml import dom import numpy as np import pandas as pd from .utils import get_factors_rev def calc_plot_size(domain_x, domain_y, plot_goal, house_goal): f1 = sorted(get_factors_rev(domain_x)) f2 = sorted(get_factors_rev(domain_y)) plot_...
9,947
3,623
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * from random import random def on_click(): x = random() y = random() bt1.place(relx=x, rely=y) root = Tk() root['bg'] = 'white' root.title('crown') img = PhotoImage(file='crown.png') bt1 = Button(image=img, command=on_click) bt1.place...
373
160
from openpyxl import Workbook def create_test_workbook(*worksheet_titles, include_default_sheet=False): workbook = Workbook() for title in worksheet_titles: workbook.create_sheet(title) if not include_default_sheet: default_sheet = workbook['Sheet'] workbook.remove(default_sheet) ...
341
103
import subprocess import sys import unittest import pathlib from torch.testing._internal.common_utils import TestCase, run_tests, IS_LINUX, IS_IN_CI REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent try: # Just in case PyTorch was not built in 'develop' mode sys.path.append(str(REPO_ROOT)) from...
2,114
656
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_str def validate_email_with_name(value): """ Validate email address. Both "Recipient...
1,365
384
# Input DOI / URL import re import sys # Pyperclip is not built-in, check and download if needed try: import pyperclip except (ImportError, ModuleNotFoundError): print('Pyperclip module not found. Please download it.') sys.exit(0) # Regex for links link_regex = re.compile(r'''( http[s]?:// (?:[a-...
1,144
387
import argparse import csv import os import torch import tqdm from torch import distributed from torch.utils import data from torchvision import datasets from torchvision import transforms from nets import nn from utils import util data_dir = os.path.join('..', 'Dataset', 'IMAGENET') def batch(images, target, mode...
6,338
2,142
import numpy as np from time import time from cgbind.atoms import get_atomic_number from cgbind.log import logger from cgbind.constants import Constants from cgbind.exceptions import CgbindCritical def get_esp_cube_lines(charges, atoms): """ From a list of charges and a set of xyzs create the electrostatic po...
2,897
1,131
import os import sys import logging import time import argparse import numpy as np from collections import OrderedDict import scripts.options as option import utils.util as util from data.util import bgr2ycbcr from data import create_dataset, create_dataloader from models import create_model # options parser = argpar...
6,051
2,254
# coding:utf-8 import time import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model import matplotlib matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) np.random.seed(0) X, y = sklearn.datasets.make_moons(200, noise=0.20) plt.scatter(X[:,0], X[:,1], s=40...
5,403
2,086
#!/usr/bin/env python # coding=utf-8 from manage import db import app.domain.model db.create_all()
101
37
import asyncio import json from aiodocker import Docker, DockerError from jupyterhub.tests.utils import api_request async def add_environment( app, *, repo, ref="master", name="", memory="", cpu="" ): """Use the POST endpoint to add a new environment""" r = await api_request( app, "enviro...
1,188
349
from api import db from uuid import uuid4 from ariadne import MutationType from api.models import Post from api.store import queues mutation = MutationType() @mutation.field("createPost") async def create_post_resolver(obj, info, input): try: post = Post(postId=uuid4(), caption=input["caption"]) ...
657
194
from async_sched.client import quit_server as module_quit from async_sched.client import request_schedules as module_request from async_sched.client import run_command as module_run from async_sched.client import schedule_command as module_schedule from async_sched.client import stop_schedule as module_stop from async_...
1,200
368
import abc from typing import TypeVar, Generic, List, Dict T = TypeVar('T') class CRUDInterface(Generic[T], metaclass=abc.ABCMeta): @abc.abstractmethod def all(self) -> List[T]: pass @abc.abstractmethod def one_by_id(self, entity_id: int) -> T: pass @abc.abstractmethod def ...
545
187
from pathlib import Path import pytest import git import json from conftest import TEST_DIR def test_init_with_project(tmpdir): output_path = Path(tmpdir.strpath) # Set arguments args = f"init -o {output_path} {TEST_DIR}/example_templates/python_project" from masonry import main # Run from en...
2,730
900
# Copyright 2015 Huawei Technologies Co., Ltd. # # 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...
2,657
724
from setuptools import setup setup( name="greek-utils", version="0.2", description="various utilities for processing Ancient Greek", license="MIT", url="http://github.com/jtauber/greek-utils", author="James Tauber", author_email="jtauber@jtauber.com", packages=["greekutils"], classi...
742
229
""" tweet stuff in intervals """ import time import datetime import twitter from markov_chains import german_text from config import config_no, config_yes MAX_TWEET_LENGTH = 280 greeting = ' Sehr geehrte/r Anstragssteller/in.' ending = ' MfG' num_tweets = 3 class FoiaBot: def __init__(self, config): s...
6,275
1,918
from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options import getpass import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from utils import * def login_user(browser, email='', password=''): print('Redir...
2,880
879
pessoas = {'nomes': "Rafael","sexo":"macho alfa","idade":19} print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for c in pessoas.keys(): print(c) for c in pessoas.values(): print(c) for c, j in pe...
1,104
462
# RSA Key Generator 2. # http://inventwithpython.com/hacking (BSD Licensed) 3. 4. import random, sys, os, rabinMiller, cryptomath The program imports the rabinMiller and cryptomath modules that we created in the last chapter, along with a few others. Chapter 24 – Public Key Cryptography and the RSA Cipher 387...
526
182
config = { "Luminosity": 1000, "InputDirectory": "results", "Histograms" : { "WtMass" : {}, "etmiss" : {}, "lep_n" : {}, "lep_pt" : {}, "lep_eta" : {}, "lep_E" : {}, "lep_phi" : {"y_margin" : 0.6}, "lep_...
2,537
953
# coding=utf-8 from ..logger import log_debug from ..utils import parent_map, replace_node, is_prefixed_var, get_used_vars def opt_unused_variable(ast): parents = parent_map(ast) used_vars = get_used_vars(ast) for node in ast.iter(): if node.tag in ["AssignmentStatementAst"]: subnodes...
1,943
528
""" Determine the number of bits required to convert integer A to integer B Example Given n = 31, m = 14,return 2 (31)10=(11111)2 (14)10=(01110)2 """ __author__ = 'Danyang' class Solution: def bitSwapRequired(self, a, b): """ :param a: :param b: :return: int """ ...
1,433
517
from pyLMS7002M import * print("Searching for QSpark...") try: QSpark = QSpark() except: print("QSpark not found") exit(1) print("\QSpark info:") QSpark.printInfo() # print the QSpark board info # QSpark.LMS7002_Reset() # reset the LMS7002M lms700...
605
218
from django.conf import settings from netaddr import mac_unix, mac_eui48 import importlib import warnings class mac_linux(mac_unix): """MAC format with zero-padded all upper-case hex and colon separated""" word_fmt = '%.2X' def default_dialect(eui_obj=None): # Check to see if a default dialect class has...
2,549
703
import time from textmagic.test import ONE_TEST_NUMBER from textmagic.test import THREE_TEST_NUMBERS from textmagic.test import TextMagicTestsBase from textmagic.test import LiveUnsafeTests class MessageStatusTestsBase(TextMagicTestsBase): def sendAndCheckStatusTo(self, numbers): message = 'sdfqwersdfg...
2,422
688