text
string
size
int64
token_count
int64
# Copyright © 2019 Province of British Columbia # # 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 agr...
4,565
1,657
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Path of the file data=pd.read_csv(path) data=data.rename(columns={"Total":"Total_Medals"}) data.head(10) ...
4,292
1,612
import time class Tester: def __init__(self, url, api: str = "", name: str = "", params: str = "", filepath: str = "") -> None: self.url = url self.api = api self.name = name self.params = params ...
704
192
#!/usr/bin/env python import requests import sys domains = set() for line in sys.stdin: domain = line.strip() certs = requests.get("https://certspotter.com/api/v0/certs?domain=%s" % domain).json() try: for cert in certs: for domain in cert["dns_names"]: domain = domain....
430
136
from omnibot import logging from omnibot.services import stats from omnibot.services import slack from omnibot.services.slack import parser logger = logging.getLogger(__name__) class Message(object): """ Class for representing a parsed slack message. """ def __init__(self, bot, event, event_trace): ...
9,731
2,567
import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger("WebTerminal")
96
30
# coding=utf-8 # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. # # 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 re...
18,980
6,020
""" typing module """ from . import pipeline from . import parsers
68
22
# AUTHOR = PAUL KEARNEY # DATE = 2018-02-05 # STUDENT ID = G00364787 # EXERCISE 03 # # filename= gmit--exercise03--collatz--20180205d.py # # the Collatz conjecture print("The COLLATZ CONJECTURE") # define the variables num = "" x = 0 # obtain user input num = input("A start nummber: ") x = int(...
871
463
""" concon (CONstrained CONtainers) provides usefully constrained container subtypes as well as utilities for defining new constrained subtypes and append-only dict modification. There are two flavors of constraints: frozen and appendonly. The former prevents any modification and the latter prevents any modification ...
8,064
2,527
from graphs.reference_implementation import DirectedGraph, UndirectedGraph from algorithms.search.student_implementation import breadth_first_search def test_start_is_stop(): g = DirectedGraph() g.add_edge('a', 'b') g.add_edge('b', 'c') g.add_edge('b', 'd') g.add_edge('e', 'f') assert breadth_...
4,186
1,820
import math import dnaplotlib as dpl import matplotlib.pyplot as plt from matplotlib import gridspec from matplotlib.patches import Polygon, Ellipse, Wedge, Circle, PathPatch from matplotlib.path import Path from matplotlib.lines import Line2D from matplotlib.patheffects import Stroke import matplotlib.patches as patch...
13,205
6,027
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : convertUI.py @Time : 2022/02/28 00:08:31 @Author : felix @Version : 1.0 @Contact : laijia2008@126.com @License : (C)Copyright 2021-2025, felix&lai @Desc : None ''' # here put the import lib import os import sys def ConvertUI(): ...
1,624
696
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: src/ray/protobuf/common.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor f...
71,145
27,477
import flot import math import datetime from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): xy10 = flot.Series(x=flot.XVariable(points=range(1, 10)), y=flot.YVariable(points=range(1, 10...
2,506
748
import color_sensor_ISL29125 from time import time cs = color_sensor_ISL29125.color_senser(1) if cs.valid_init: print "Valid color sensor" else : print "Color Sensor invalid" t0 = time() red_list = [] green_list = [] blue_list = [] for x in range(100): stat = cs.readStatus() if "" in stat: #"FLA...
1,097
454
print("yaaaay") input()
24
11
import vaex import os # Open the main data taxi_path = 's3://vaex/taxi/yellow_taxi_2012_zones.hdf5?anon=true' # override the path, e.g. $ export TAXI_PATH=/data/taxi/yellow_taxi_2012_zones.hdf5 taxi_path = os.environ.get('TAXI_PATH', taxi_path) df_original = vaex.open(taxi_path) # Make sure the data is cached locally ...
879
296
from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * def unique(iterable, key=id): """ List unique elements, preserving order. Remember all elements ever seen. """ return unique_values((key(element), element) for element in...
493
142
import nltk from nltk.tokenize import word_tokenize #nltk.download('punkt') #nltk.download('averaged_perceptron_tagger') from collections import Counter def extract_noun_counts(doc_list): nouns_pdoc = [] for i in range(len(doc_list)): pos = nltk.pos_tag(nltk.word_tokenize(doc_list[i])) ...
1,540
552
# Copyright (c) 2020, Xilinx # 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 notice, this # list of conditions and the follow...
14,315
4,032
""" <html><body> <p> You'll probably want to supply a stylesheet. Perhaps some javascript library. Maybe even some images. One way or another, it's handy to be able to point at a directory full of static content and let the framework do its job. </p> <p> This example exercises that facility by presenting the examples ...
822
273
#= ------------------------------------------------------------------------- # @file hello_world2.py # # @date 02/14/16 13:29:22 # @author Martin Noblia # @email martin.noblia@openmailbox.org # # @brief # # @detail # # Licence: # This program is free software: you can redistribute it and/or modify # it under the terms...
1,266
397
import re from .utils import validator regex = ( r'^[A-Z]{2}[0-9]{2}[A-Z0-9]{13,30}$' ) pattern = re.compile(regex) def char_value(char): """A=10, B=11, ..., Z=35 """ if char.isdigit(): return int(char) else: return 10 + ord(char) - ord('A') def modcheck(value): """Check if...
1,167
414
import sys t = int(input().strip()) for a0 in range(t): n = int(input().strip()) def preSum(q): return (q*(1+q) //2 ) result = 3*preSum(int((n-1)//3)) + 5*preSum(int((n-1)//5)) - 15*preSum(int((n-1)//15)) print(int(result))
249
115
from statistics import mode from django.db import models from cloudinary.models import CloudinaryField # Create your models here. class Image(models.Model): # image = models.ImageField( # upload_to='uploads/', default='default.jpg') image = CloudinaryField('image') title = models.CharField(max_l...
1,303
386
from django.contrib.auth.models import Group, User from django.utils import timezone import factory from factory import fuzzy from mozillians.geo.models import City, Country, Region from mozillians.users.models import Language class UserFactory(factory.DjangoModelFactory): username = factory.Sequence(lambda n: ...
2,396
771
import os import shutil from contextlib import ( contextmanager, ) from pathlib import Path import pytest @pytest.fixture(scope='function', autouse=True) def cleanup(): test_generate_dir = (Path('.') / 'tests' / 'biisan_data') if test_generate_dir.exists(): shutil.rmtree(test_generate_dir) yi...
1,248
471
from django.test import TestCase from django.shortcuts import reverse from .models import MovieList from christmasflix import omdbmovies class MovieListIndexViewTests(TestCase): def test_no_lists(self): response = self.client.get(reverse('christmasflix:index')) self.assertEqual(response.status_co...
1,866
596
from asyncio import CancelledError, TimeoutError from requests.exceptions import Timeout, ConnectionError from aiohttp.client_exceptions import ClientHttpProxyError, ClientProxyConnectionError, ClientOSError class CaptchaError(Exception): pass ProxyErrors = (CaptchaError, ClientOSError, ClientProxyConn...
430
117
import json import logging import re from itertools import chain from json import JSONDecodeError from typing import Iterable, Optional, Mapping import requests import untangle from bs4 import BeautifulSoup, PageElement, Tag from holdingsparser.file import Holding, VotingAuthority, ShrsOrPrnAmt logger = logging.getL...
4,493
1,411
# DEFAULT SETTINGS FILE import json import requests mturk_type = "sandbox" data_type = "temporal" data_path = "../data/" input_path = "../input/" template_path = "../templates/" result_path = "../results/" max_results = 10 approve_all = False # you must have a YouTube API v3 key # your key must be in a json file titl...
4,757
1,646
# coding=utf-8 # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import json import os import signal import time import traceback import requests import access_token import config import metrics import model import spark_pools def write_string_to_path(path, filename, content): _path = o...
10,790
3,128
""" File: stanCodoshop.py Name: James Shih ---------------------------------------------- SC101_Assignment3 Adapted from Nick Parlante's Ghost assignment by Jerry Liao. ----------------------------------------------- Remove people or abnormal objects in a certain photo. """ import os import sys import time from simpl...
5,465
1,688
from rest_framework import viewsets from elasticsearch_dsl import Search from elasticsearch_dsl.connections import connections from search.filters import ElasticsearchFuzzyFilter from search.documents import AuthorDocument from search.serializers import AuthorDocumentSerializer from utils.permissions import ReadOnly ...
1,254
335
import torch import torch.utils.data as data import os import pickle import numpy as np import nltk from PIL import Image import os.path import random from torch.autograd import Variable import torch.nn as nn import math # Environment Encoder class Encoder(nn.Module): def __init__(self): super(Encoder, self).__ini...
4,329
2,143
# coding: utf-8 # # This code is part of qclib. # # Copyright (c) 2021, Dylan Jones import numpy as np from ..math import apply_statevec, apply_density, density_matrix from .measure import measure_qubit, measure_qubit_rho class DensityMatrix: def __init__(self, mat): self._data = np.asarray(mat) de...
1,584
530
#!/usr/bin/env python # coding: utf-8 # #### Modeling the elemental stoichiometry of phytoplankton and surrounding surface waters in and upwelling or estuarine system # >Steps to complete project: # >1. Translate matlab physical model into python # >2. Substitute Dynamic CFM into model for eco component # >3. Analyze ...
3,981
1,748
import requests sess = requests.session() import gzip import json import time import os def downloadyear(year): print("fetching year", year) url = "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-{year}.json.gz".format(year=year) req = sess.get(url, stream=True) return gzip.open(req.raw)....
2,534
1,055
#!/usr/bin/env python3 ''' Perimeterator Enumerator. This wrapper is intended to allow for simplified AWS based deployment of the Perimeterator enumerator. This allows for a cost effective method of execution, as the Perimeterator poller component only needs to execute on a defined schedule in order to detect changes....
2,974
812
# Copyright or Copr. Centre National de la Recherche Scientifique (CNRS) (2017/11/27) # Contributors: # - Vincent Lanore <vincent.lanore@gmail.com> # This software is a computer program whose purpose is to provide small tools and scripts related to phylogeny and bayesian # inference. # This software is governed by th...
3,991
1,309
import pytest import numpy as np import numpy.testing as npt from lenstronomy.PointSource.point_source import PointSource from lenstronomy.LensModel.lens_model import LensModel from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver import lenstronomy.Util.param_util as param_util class Test...
6,871
2,542
# -*- coding: utf-8 -*- # # Copyright (C) 2021 Technische Universität Graz # # invenio-rdm-pure is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Utility methods.""" import smtplib from datetime import datetime from os.path import di...
3,493
1,066
from subproject import d print("c")
37
13
# Copyright 2020 Ford Motor Company # 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 ag...
1,992
577
# # Copyright 2013 Radware 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 applicable law or agr...
37,790
10,615
import boto3 from botocore.exceptions import NoCredentialsError ACCESS_KEY = '' SECRET_KEY = '' def upload_to_aws(local_file, bucket, s3_file): s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) try: s3.upload_file(local_file, bucket, s3_fil...
1,219
410
from psycopg2 import connect, DatabaseError, OperationalError, ProgrammingError import logging import sys logging.getLogger().setLevel(logging.INFO) def query_exec(query: str, conn) -> list: query_ok = False with conn.cursor() as cursor: logging.info(f'Executing query: {query}') try: ...
2,176
642
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Description --------- Class of sampler by Metropolis algorithm. Documentation --------- C.f. `../doc/metropolis_sampler.tm`. """ import random from math import log from copy import deepcopy as copy class MetropolisSampler: """ An implementation of sampler ...
2,365
678
#Faça um programa que calcule a soma entre todos os números ímpares que são múltiplos de 3 e que se encontram # no intervalo de 1 até 500. soma = 0 cont = 0 for c in range(1,501,2): if c % 3 == 0: cont = cont + 1 soma = soma + c print('A soma dos números solicitados {} são {}'.format(cont, soma))
319
128
import os import argparse import tqdm import os import argparse import numpy as np import tqdm from itertools import chain from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import transforms from torch.autograd import Vari...
10,532
3,767
import pickle from random import shuffle sums = [(5, 105) , (205, 305), (405, 1005), (1105, 1205), (1305, 1405)] shuffle(sums) a = {'sums': sums, 'current_sum': 0} with open('child_data/child1.pkl', 'wb') as f: pickle.dump(obj=a, file=f) print(a) shuffle(sums) b = {'sums': sums, 'current_sum': 0} with open('child...
529
266
"""Test weighted path counting methods.""" # pylint: disable=redefined-outer-name,too-few-public-methods # pylint: disable=too-many-branches import pytest from pytest import approx import numpy as np import pandas as pd from pathcensus.definitions import PathDefinitionsWeighted from pathcensus import PathCensus @pyte...
10,736
3,317
#!/usr/bin/env python27 import io import os import json import logging import datetime import requests import lxml.html from lxml.cssselect import CSSSelector from multiprocessing.dummy import Pool as ThreadPool # Path where the JSONs will get written. Permissions are your job. SAVE_PATH = '.' # Urls of the pages t...
5,781
1,925
import numpy as np from utils import check_integer_values from gensim.models import KeyedVectors from config import PATH_TO_SAVE_DATA, WORD2VEC_FILE_NAME, STOCKCODE_FILE_NAME # =========== TECHNICAL FUNCTIONS =========== def aggregate_vectors(model, products): product_vec = [] for prod in products: ...
1,715
592
# following code is largly adapted from `here <https://github.com/huggingface/transformers/blob/f2c4ce7e339f4a2f8aaacb392496bc1a5743881f/src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py#L206>__` import tensorflow as tf import numpy as np def tf_multinomial_no_replacement(distribution, num_samples): """ ...
5,531
1,799
"""django-livereload""" __version__ = '1.7' __license__ = 'BSD License' __author__ = 'Fantomas42' __email__ = 'fantomas42@gmail.com' __url__ = 'https://github.com/Fantomas42/django-livereload'
195
85
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 8 16:05:54 2019 @author: Chonghua Xue (Kolachalama's Lab, BU) """ from torch.utils.data import Dataset # true if gapped else false vocab_o = { True: ['-'] + ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V'...
1,673
737
""" Custom Fairness Metrics Note that ratio and difference computation is handled by AIF360's sklearn.metrics module. As of the V 0.4.0 release, these are calculated as [unprivileged/privileged] and [unprivileged - privileged], respectively """ from typing import Callable from aif360.sklearn.metrics import...
7,986
2,697
import logging import pytest from tests.common.helpers.assertions import pytest_assert from tests.common.portstat_utilities import parse_portstat from tests.common.utilities import wait logger = logging.getLogger('__name__') pytestmark = [ pytest.mark.topology('any') ] @pytest.fixture(scope='function', autous...
6,815
2,282
from hashlib import sha256 from nacl.secret import SecretBox from nacl.utils import random # Length of a SHA256 double hash SHA256_HASH_LEN = 32 KEY_SIZE = SecretBox.KEY_SIZE def bitcoin_hash(content): return sha256(sha256(content).digest()).digest() def double_sha256(content): return sha256(sha256(conten...
597
223
try: from src.PyMIPS.Datastructure.memory import Memory except: from PyMIPS.Datastructure.memory import Memory import unittest class TestMemory(unittest.TestCase): def test_storage(self): Memory.store_word(16, 2214) Memory.store_word(17, 2014) self.assertEqual(Memory.get_word(221...
829
339
"""The :py:class:`.Schema` class provides a database agnostic way of manipulating tables. Tables ====== Creating Tables --------------- To create a new database table, the :py:meth:`~.Schema.create` method is used. The :py:meth:`~.Schema.create` method accepts a table name as its argument and returns a :py:class:`.Bl...
4,122
1,202
"""The Kostal piko integration.""" import logging import xmltodict from datetime import timedelta from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD, CONF_HOST, CONF_MONITORED_CONDITIONS, ) from homeassistant.components.sensor import SensorEntity from homeassistant.helpers...
6,024
1,962
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from kaskopy.models import Car, RawData class CarItem(scrapy.Item): brand = scrapy.Field() model = scrapy.Field() year = scrapy.Field() ...
601
201
line = input() print(line)
26
10
import re import os import time class LogReader(object): def __init__(self): self.log_file_sizes = {} # (if the file changes more than this, ignore ) - 1 MB self.max_file_size_change = 1000000 # (if the time between checks is greater, ignore ) - 5 minutes self.max_file_time_...
2,466
738
#!/usr/bin/env python # -*- coding: utf-8 -*- import __future__ import sys import json def banner(): ban = '====' * 30 print("{}\nSAMPLE INP:\n{}\n{}".format(ban,ban,open(ip, 'r').read())) print("{}\nSAMPLE OUT:\n{}\n{}".format(ban,ban,open(op, 'r').read())) print("{}\nSTART:\n{}".format(ban,ban)) ...
1,121
448
from .embed import Embed from .file import Attachment from .member import GuildMember, User from .slash import SlashCommandOptionChoice, AnyOption from .commands import MessageButton, MessageSelectMenu, MessageTextInput, MessageSelectMenuOption from typing import Optional, List, Union class BaseInteraction: def __...
10,934
3,112
from django import http from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import login_required from django.core import urlresolvers from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ fr...
3,571
1,007
DEFAULT_TEXT_TYPE = "mrkdwn" class BaseBlock: def generate(self): raise NotImplemented("Subclass missing generate implementation") class TextBlock(BaseBlock): def __init__(self, text, _type=DEFAULT_TEXT_TYPE): self._text = text self._type = _type def __repr__(self): retu...
480
151
""" LoPy LoRaWAN Nano Gateway configuration options """ import machine import ubinascii WIFI_MAC = ubinascii.hexlify(machine.unique_id()).upper() # Set the Gateway ID to be the first 3 bytes of MAC address + 'FFFE' + last 3 bytes of MAC address GATEWAY_ID = '30aea4fffe4e5638' #WIFI_MAC[:6] + "FFFE" + WIFI_MAC[6:12]...
551
279
""" CPF = 079.004.419-64 ---------------------- 0 * 10 = 0 # 0 * 11 = 0 7 * 9 = 63 # 7 * 10 = 70 9 * 8 = 72 # 9 * 9 = 81 0 * 7 = 0 # 0 * 8 = 0 0 * 6 = 0 # 0 * 7 = 0 4 * 5 = 20 # 4 * 6 = 24 4 * 4 = 16 # 4 * 5 =...
1,560
741
import math def rectangle(lenght_rectangle, breadth_rectangle): area_rectangle = lenght_rectangle*breadth_rectangle print(f'The area of rectangle is {area_rectangle}.') def triangle(base_triangle, height_triangle): area_triangle = 0.5 * base_triangle * height_triangle print(f'The area of triangle is {a...
1,414
416
#***************************************************# # This file is part of PFNET. # # # # Copyright (c) 2015, Tomas Tinoco De Rubira. # # # # PFNET is released under the BSD 2-clause license...
1,204
436
import pandas as pd import numpy as np import geopandas as gpd from shapely.geometry import Polygon,LineString import urllib.request import json from .CoordinatesConverter import gcj02towgs84,bd09towgs84,bd09mctobd09 from urllib import parse def getadmin(keyword,ak,subdistricts = False): ''' Input the keyword ...
11,343
3,624
from django.apps import AppConfig class userConfig(AppConfig): name = 'user'
83
26
import time import sys # Set color R = '\033[31m' # Red N = '\033[1;37m' # White G = '\033[32m' # Green O = '\033[0;33m' # Orange B = '\033[1;34m' #Blue def delay_print(s): for c in s: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.01) delay_print delay_print (""+R+" db db d888888b...
819
399
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from logging import StreamHandler, INFO from flask import Flask from flask.ext.mail import Message, Mail from api import create_api from database import init_db API_VERSION = "v1" def check_environment(app): file_backend = os.environ.get('FILE_BACKEND', '...
1,864
631
import asyncio import collections from yarl import URL from .transport import Transport class Client: def __init__( self, url='http://127.0.0.1:7474/', auth=None, transport=Transport, request_timeout=..., *, loop=None ): if loop is None: l...
1,463
423
#Script to calc. area of circle. print("enter the radius") r= float(input()) area= 3.14*r**2 print("area of circle is",area)
125
47
# Copyright (C) 2021 Xilinx, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
2,132
654
from Scanner import * from threading import Thread Scanner = Scan_Handler(verbose=False, verbosity="high", threads=50, ports=[80, 443]) Scanner.Start_Scanner("192.168.0.1", "192.168.0.5") def Background (): for data in Scanner.Get_Outputs_Realtime(): print(str(data)) bg = Thread(target=Background) #bg...
348
150
# -*- coding: utf-8 -*- import unittest from app import app class TestPingView(unittest.TestCase): def setUp(self): app.config['TESTING'] = True self.client = app.test_client() def test_ping(self): response = self.client.get('/ping') assert response.data.decode('utf-8') == 'p...
325
110
#doc4 #1. print([1, 'Hello', 1.0]) #2 print([1, 1, [1,2]][2][1]) #3. out: 'b', 'c' print(['a','b', 'c'][1:]) #4. weekDict= {'Sunday':0,'Monday':1,'Tuesday':2,'Wednesday':3,'Thursday':4,'Friday':5,'Saturday':6, } #5. out: 2 if you replace D[k1][1] with D['k1][1] D={'k1':[1,2,3]} print(D['k1'][1]) #6. tup = ( ...
527
319
from threading import Thread from time import sleep from socket import socket, AF_INET, SOCK_STREAM from re import compile HOST = ('52.49.91.111', 2092) MAX_BUFFER = 2**15 MSGS = compile(r'^ROUND (\d+): (\d+) -> (\w+) \{(.+?)\}( no_proposal)?( \(ROUND FINISHED\))?$').search LEARN_ARGS = compile(r'servers: \[(.+?)\], s...
4,609
2,099
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
7,600
2,207
"""Generic object pool""" from __future__ import annotations __all__ = [ "Manager", "Pool", ] import contextlib import dataclasses import logging import queue import threading from abc import ABCMeta from typing import Generator, Generic, Optional, TypeVar from ._common import DEFAULT_SIZE from .exceptions ...
5,971
1,627
import math def get_dist_bins(num_bins, interval=0.5): bins = [(interval * i, interval * (i + 1)) for i in range(num_bins - 1)] bins.append((bins[-1][1], float('Inf'))) return bins def get_dihedral_bins(num_bins, rad=False): first_bin = -180 bin_width = 2 * 180 / num_bins bins = [(first_bin ...
1,090
472
import unittest import os import json import mock import hashlib from webpack.conf import Conf from webpack.manifest import generate_manifest, generate_key, write_manifest, read_manifest, populate_manifest_file from webpack.compiler import webpack from .settings import ConfigFiles, OUTPUT_ROOT, WEBPACK from .utils impo...
8,155
2,426
import inspect import time from django.conf import settings class _statsd(object): def incr(s, *a, **kw): pass def timing(s, *a, **kw): pass try: from statsd import statsd except ImportError: statsd = _statsd() class FrameOptionsHeader(object): """ Set an X-Frame-Options ...
1,368
421
import pytest from dataclasses import dataclass, field from functools import reduce from typing import List, Optional from helpers.basetest import BaseTestBtc, LedgerjsApdu, TxData, CONSENSUS_BRANCH_ID from helpers.deviceappbtc import DeviceAppBtc, CommException # Test data below is from a Zcash test log from Live te...
22,992
10,168
import atexit import grpc import logging import os import server_pb2 import server_pb2_grpc port: str = None def init_env() -> None: global port port = os.environ['PORT'] logging.info('Found PORT at %s', port) def init_atexit() -> None: def end(): logging.info('bye') atexit.register...
1,776
640
# -*- coding: utf-8 -*- import datetime as dt import uuid import scrapy class DummySpiderSpider(scrapy.Spider): name = "dummy_spider" allowed_domains = ["example.com"] start_urls = ["http://example.com/"] def parse(self, response): yield { "uuid": str(uuid.uuid1()), "...
394
132
# Copyright (c) 2021, JC and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class CustomerAccount(Document): pass
192
57
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # 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 # # Unl...
4,839
1,435
import base64 import shutil import json import re from enum import Enum, auto from typing import Optional import py7zr from cachetools import TTLCache, cached from ruamel.yaml import YAML, YAMLError from logger import getLogger import os import tempfile import zipfile import requests from bs4 import BeautifulSoup l ...
20,561
6,205
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ from django.urls import path from .views import login_view, register_user, reset_password from django.contrib.auth.views import LogoutView from .views import * urlpatterns = [ path('login/', login_view, name="login"), path(...
548
187
# -*- coding: utf-8 -*- # * Copyright (c) 2009-2018. Authors: see NOTICE file. # * # * 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...
2,835
864
from flask import Blueprint admin_blu = Blueprint("admin", __name__, url_prefix="/admin") from .views import * @admin_blu.before_request def admin_identification(): """ 进入后台之前的校验 :return: """ # 我先从你的session获取下is_admin 如果能获取到 说明你是管理员 # 如果访问的接口是/admin/login 那么可以直接访问 is_login = request.ur...
490
226