text
string
size
int64
token_count
int64
import os import jinja2 import logging from lib.config import Config class Template: def __init__(self, env_search_term="ENV"): self.log_name = f'{Config.logger_name}.{self.__class__.__name__}' self.log = logging.getLogger(self.log_name) self.path = None self.name = None s...
2,440
717
from typing import Optional from pydantic import BaseModel, root_validator, validator from fief.crypto.encryption import decrypt from fief.db.types import DatabaseType from fief.errors import APIErrorCode from fief.schemas.generics import UUIDSchema from fief.settings import settings def validate_all_database_setti...
2,829
821
# Generated by Django 3.2.12 on 2022-03-01 23:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('art', '0006_auto_20220301_1452'), ] operations = [ migrations.AlterField( model_name='artimage...
491
179
from __future__ import absolute_import, unicode_literals import string from django.contrib.auth.models import User from django.utils.crypto import get_random_string from celery import shared_task, current_task @shared_task def create_random_user_accounts(total_user): for i in range(total_user): use...
844
259
# Generated by Django 2.2.27 on 2022-04-16 16:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fehler_auth', '0002_auto_20211002_1511'), ] operations = [ migrations.AlterField( model_name='invite', name='email'...
392
149
from random import choice, gauss, random class Gene(object): def __init__(self, config, key): self.config = config self.key = key def __str__(self): attrib = ['key'] + [a for a in self.__gene_attributes__] attrib = ['{0}={1}'.format(a, getattr(self, a)) for a in attrib] ...
5,637
1,674
from tapis_cli.clients.services.mixins import ServiceIdentifier __all__ = ['AppIdentifier'] class AppIdentifier(ServiceIdentifier): service_id_type = 'App' dest = 'app_id' def validate_identifier(self, identifier, permissive=False): try: self.tapis_client.apps.get(appId=identifier) ...
552
143
from agents.agent import Agent from random import randint class Antifa(Agent): def __init__(self): super().__init__() self.is_spy = False def __str__(self): return 'Basic Antifa' def assign_mission(self, board): number_to_assign = board.number_to_assign() board....
835
261
# -*- encoding: utf-8 -*- """ @File : metadata.py @Time : 2020/1/1 @Author : flack @Email : opencoding@hotmail.com @ide : PyCharm @project : faketranslate @description : 描述 """
234
91
import requests, json, time from multiprocessing.dummy import Pool pool = Pool(100) transactions0 = [] transactions1 = [] transactions2 = [] transactions3 = [] transactions4 = [] transactions5 = [] transactions6 = [] transactions7 = [] transactions8 = [] transactions9 = [] nodeid = { 'id0': 0, 'id1': 1, ...
6,062
2,203
# django from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string # utiltities import threading class EmailThread(threading.Thread): """ Class uses a thread to send email """ def __init__(self, subject, content, recipient_list, is_html): sel...
1,550
522
from flask import Flask from flask_sqlalchemy import SQLAlchemy from service.api_service import Service class SampleController(object): def __init__(self,app:Flask,db:SQLAlchemy,service:Service) -> None: self.app=app self.db=db self.service=service self.add_routes(app) def add_ro...
628
195
import numpy as np import pandas as pd import datetime import json class DateTimeTransformer(object): def __init__(self): self._new_columns = [] self._old_column = None self._min_datetime = None self._transforms = [] def fit(self, X, column): self._old_column = column ...
3,533
1,090
# -*- 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...
10,592
3,067
import json from django.urls import reverse from django.shortcuts import render from django.db.models import Q from django.views.generic.base import View from django.contrib.auth import authenticate,login,logout from django.contrib.auth.backends import ModelBackend from django.contrib.auth.hashers import make_password ...
13,568
4,432
__all__ = [ 'Users' ]
25
13
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'd:\MITE12\ksapriori\gui\sales_transaction.ui' # # Created by: PyQt5 UI code generator 5.12.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FormSalesTransaction(ob...
5,794
1,797
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='{{ cookiecutter.app_name }}', version='0.0.1', description='{{ cookiecutter.description }}', author='{{ cookiecutter.author }}', author_email='{{ cookiecutter.author_email }}', license='{{ cookiecutter.license }}', ...
727
231
from flask import Flask, request, render_template, send_file, Response import io import base64 import csv import json import time from collections import OrderedDict import numpy import pandas as pd from numpy import genfromtxt from flask import jsonify from flask_cors import CORS from LoadingNetwork import...
27,975
9,858
# coding: utf-8 # flake8: noqa """ Our City App Our City App internal apis # noqa: E501 The version of the OpenAPI document: 0.0.1 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import # import models into model package from oca.models.home_screen import HomeScre...
697
205
import svgwrite def cross(dwg, x, y, r = 5): dwg.add(dwg.line((x - r, y), (x + r, y), stroke='red', stroke_width=.1)) dwg.add(dwg.line((x, y - r), (x, y + r), stroke='red', stroke_width=.1)) if __name__ == '__main__': dwg = svgwrite.Drawing('test.svg', size=('150mm', '150mm'), viewBox=('0 0 150 150')) ...
428
219
from poketype import PokemonTypeIdentifier from flask import Flask, request, make_response,jsonify import os id = PokemonTypeIdentifier() app = Flask(__name__,static_url_path='/static') @app.route('/findtype',methods=['GET']) def classify(): poke_name=request.args.get('pokename') results = id.predict_type(poke...
597
211
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import math import copy import types def fgsm_attack(image, epsilon, data_grad): print('Attacking...') # Collect the element-wise sign of the data gradient sign_data_grad = data_grad.sign() # Create th...
13,975
4,762
from django.shortcuts import render from leads.models import Lead from leads.serializers import LeadSerializer from rest_framework import generics # Create your views here. class LeadListCreate(generics.ListCreateAPIView): queryset = Lead.objects.all() serializer_class = LeadSerializer
296
81
""" First class definition""" class Cat: pass class RaceCar: pass cat1 = Cat() cat2 = Cat() cat3 = Cat()
117
45
""" The aiobotocore integration will trace all AWS calls made with the ``aiobotocore`` library. This integration isn't enabled when applying the default patching. To enable it, you must run ``patch_all(botocore=True)`` :: import aiobotocore.session from ddtrace import patch # If not patched yet, you can ...
870
254
# # This file is part of LUNA. # import shutil import tempfile import argparse from nmigen import Elaboratable from .gateware.platform import get_appropriate_platform def top_level_cli(fragment, *pos_args, **kwargs): """ Runs a default CLI that assists in building and running gateware. If the user's opt...
3,161
886
"""search for HUC12 by name.""" import json from paste.request import parse_formvars from pyiem.util import get_dbconn def search(q): """Search for q""" pgconn = get_dbconn("idep") cursor = pgconn.cursor() d = dict(results=[]) cursor.execute( """SELECT huc_12, hu_12_name from huc12 WH...
761
271
""" Setup module. """ from setuptools import setup from mmsim import __version__ setup( name='mmsim', version=__version__, description='A simple Micromouse Maze Simulator server', long_description="""The server can load different mazes and any client can connect to it to ask for the current po...
1,570
486
""" A fast version of the original inference. Constructing one graph to infer all the samples. Originaly one graph for each sample. """ import tensorflow as tf import os from model import CycleGAN import utils import scipy.misc import numpy as np try: from os import scandir except ImportError: # Python 2 polyfill...
2,556
863
""" This test will show how to use the various Json serializer(s) """ from lazy.io.pathz import get_path from lazy.serialize import SimdJson, OrJson, Json, Serializer from lazy.utils import get_logger, timer logger = get_logger('lazytest') test_file = './files/naics_codes.json' test_path = get_path(test_file, resolve...
8,879
5,348
import http.client def getFunctionPublicIP(): conn = http.client.HTTPSConnection('api.ipify.org', 443) conn.request('GET', '/?format=json') ip = conn.getresponse().read() print(ip) conn.close() return str(ip) def non_zero_balance(balance): """ Return the balance with zero-value coins...
1,018
322
import argparse import json import sys import os try: from utility_functions import load_csv_files_into_db, generate_vocabulary_load except(ImportError): sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], os.path.pardir, os.path.pardir, "src"))) from utility_functions import load_...
2,442
864
# Python modules. import pytest # Django modules. from django.urls import reverse from django.test import TestCase # !Triplinker modules: from tests.helpers.create_user import new_user @pytest.mark.django_db def test_signup_view(client): url = reverse('accounts:signup') response = client.get(u...
1,588
568
#!/usr/bin/env python # convert jpg tp png from glob import glob import cv2 pngs = glob('./*.jpg') for j in pngs: img = cv2.imread(j) cv2.imwrite(j[:-3] + 'png', img) # delete jpg files import glob import os dir = "/Users/wangmeijie/ALLImportantProjects/FlameDetectionAPP/Models/MaskRCNN/02_26_2020/Mask_RCNN...
414
175
import xml.sax import re import os import json import time current_milli_time = lambda: int(round(time.time() * 1000)) RE_LINKS = re.compile(r'\[{2}(.*?)\]{2}', re.DOTALL | re.UNICODE) IGNORED_NAMESPACES = [ 'wikipedia', 'category', 'file', 'portal', 'template', 'mediaWiki', 'user', 'help', 'book', 'draft', ...
4,544
1,389
# We can transition on native options using this # //command_line_option:<option-name> syntax _BUILD_SETTING = "//command_line_option:test_arg" def _test_arg_transition_impl(settings, attr): _ignore = (settings, attr) return {_BUILD_SETTING: ["new arg"]} _test_arg_transition = transition( implementation ...
1,571
498
import io import avro.io try: from avro.schema import parse except ImportError: from avro.schema import Parse as parse class ApacheAvroAdapter(object): NAME = 'avro' def __init__(self): with open('specs/str.avsc', 'r') as f: schema = parse(f.read()) self.str_reader = a...
7,116
2,343
# coding: utf-8 # 2021/5/30 @ tongshiwei
41
25
import pytest from nameko.events import EventDispatcher, event_handler from nameko.rpc import rpc from nameko.testing.services import entrypoint_hook, entrypoint_waiter from nameko.web.handlers import http from prometheus_client import REGISTRY, Counter from nameko_prometheus import PrometheusMetrics @pytest.fixture...
4,004
1,222
from django import forms from warehouse.models import Product, ProductAdditionalInformation class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' field_order = [ 'product_name', 'product_code', 'product_quantity', ...
604
154
from amuse.test.amusetest import TestWithMPI from amuse.units import nbody_system from amuse.units import units import os import sys import numpy import math from amuse.community.sei.interface import SeiInterface from amuse.community.sei.interface import Sei from amuse import datamodel class TestSeiInterface(TestWit...
1,210
438
from datetime import datetime, timedelta from enum import Enum, auto from dateutil.relativedelta import relativedelta from .baseclasses import Constant, MethodEnum from .formulars import days_feb, eastern_calc, thanksgiving_calc, year_start class ConstantOption(Enum): TIME_VARIABLE = auto() DATE_VARIABLE = ...
20,063
7,270
# !/usr/bin/env python # -*- coding: UTF-8 -*- """ UTILITY TO START A LOCAL SERVER Copyright (c) 2015 __Michele Pasin__ <http://www.michelepasin.org>. All rights reserved. Shows local repo within a server """ MODULE_VERSION = 0.1 USAGE = "@todo" import time, optparse, os, rdflib, sys, webbrowser import SimpleHT...
2,295
875
# Copyright (C) 2021 Sarah Roggendorf # # SPDX-License-Identifier: MIT from typing import Callable, Tuple, Union import dolfinx.common as _common import dolfinx.fem as _fem import dolfinx.log as _log import dolfinx.mesh as _mesh import dolfinx_cuas import numpy as np import ufl from dolfinx.cpp.graph import Adjace...
14,866
4,935
""" usage: python movielens-mongodb.py [movies] [ratings] [links] """ import sys import re import csv import os # import tmdbsimple as tmdb from pymongo import MongoClient from pymongo import ASCENDING, DESCENDING from datetime import datetime from time import sleep def import_movies(db, mfile): movies = [] ...
5,218
1,750
balance = 700 papers=[100, 50, 10, 5,4,3,2,1] def withdraw(balance, request): if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) orgnal_request = request while request > ...
1,400
419
from django import forms from django.forms.utils import flatatt from django.utils import formats from django.utils.encoding import force_text from django.utils.html import format_html class AjaxValidatingTextInput(forms.TextInput): def __init__(self, *args, **kwargs): super(AjaxValidatingTextInput, self)....
1,126
346
"""Change unique constraint on collection Revision ID: 8e3f80979dc9 Revises: 3d5fae27a215 Create Date: 2019-12-18 13:14:56.466907 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '8e3f80979dc9' down_revision = '3d5fae27a215' branch_labels = None depends_on = None...
1,406
462
# -*- coding: utf-8 -*- """Test miscellaneous objects from the standard library""" import uuid import unittest import jsonpickle class UUIDTestCase(unittest.TestCase): def test_random_uuid(self): u = uuid.uuid4() encoded = jsonpickle.encode(u) decoded = jsonpickle.decode(encoded) ...
1,685
784
import os import time import tensorflow as tf import numpy as np import pandas as pd from .configs import * from .models import init_models EPOCH_NUMBER = 10000 EARLY_STOP = True EARLY_STOP_MAX_ITER = 40 def _train(session, saver, models, train_data, valid_data): model_file_path = _init_model_file_path() p...
3,435
1,114
"""Aito `Query API <https://aito.ai/docs/api/#query-api>`__ Request Class""" import re from abc import ABC from typing import Dict, Optional, Union, List from .aito_request import AitoRequest, _PatternEndpoint, _PostRequest from ..responses import SearchResponse, PredictResponse, RecommendResponse, EvaluateResponse, ...
3,817
1,191
#!/usr/bin/env python # coding: UTF-8 from __future__ import division from pychebfun import Chebfun import operator import unittest import pytest from . import tools import numpy as np import numpy.testing as npt #------------------------------------------------------------------------------ # Unit test for arbitrary...
3,417
1,102
#!/usr/bin/env python #encode=utf-8 #vim: tabstop=4 shiftwidth=4 softtabstop=4 #Created on 2013-8-17 #Copyright 2013 nuoqingyun xuqifeng import copy import logging import traceback class RPCException(Exception): message = "An Unknown RPC related exception occurred" def __init__(self, messa...
1,878
622
import unittest import socket import json import base64 import zlib import gzip import bs4 from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread import WebRequest from . import testing_server class TestPlainCreation(unittest.TestCase): def test_plain_instantiation_1(self): wg = W...
12,029
4,832
'''Barst Measurement Computing DAQ Wrapper ========================================== ''' from functools import partial from pybarst.mcdaq import MCDAQChannel from kivy.properties import NumericProperty, ObjectProperty from moa.threads import ScheduledEventLoop from moa.device.digital import ButtonViewPort from cplco...
5,220
1,538
import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pr...
2,827
930
N, T, C, P = map(int, input().split()) print(((N - 1) // T) * C * P)
69
35
from multiprocessing import Pool, Manager from time import sleep from wmi import WMI from win32com.client import GetObject from subprocess import Popen from collections import Iterable from tqdm import tqdm from os import getpid from sapy_script.Session import Session session_process = None all_processes_id = [] de...
5,702
1,768
import json import os import os.path as path import re from flask import Blueprint, request blueprint = Blueprint("editor", __name__) robotsrc_path = path.join(os.getcwd(), "robotsrc") if not path.exists(robotsrc_path): os.mkdir(robotsrc_path) main_path = path.join(robotsrc_path, 'main.py') main_file = open(main...
2,158
711
import pytest from hai.event_emitter import EventEmitter class Thing(EventEmitter): event_types = {'one', 'two'} @pytest.mark.parametrize('omni', (False, True)) def test_event_emitter(omni): t = Thing() events = [] def handle(sender, **args): assert sender is t events.append(args) ...
1,131
406
""" Tests for dit.divergences.jensen_shannon_divergence. """ from nose.tools import assert_almost_equal, assert_raises from dit import Distribution from dit.exceptions import ditException from dit.divergences.jensen_shannon_divergence import ( jensen_shannon_divergence as JSD, jensen_shannon_divergence_pmf as...
2,598
1,180
import torch maxdisp = 10 disp_scans = torch.arange(maxdisp).view(1,maxdisp,1,1) zeros_scans = torch.arange(maxdisp).view(1,maxdisp,1,1) semseg = torch.arange(16).view(4,4) zeros_scans = torch.cat([zeros_scans.repeat(1, repeat,1, 1) for i in range(1)],dim=0)
261
133
from sqlalchemy import Table, Column, String, DateTime, Text from modules.persistence import Base, getModelBase CustomBase = getModelBase('leavemessage') class Message(Base, CustomBase): user = Column(String(200)) nick = Column(String(100)) message_time = Column(DateTime) to_nick = Column(String(100...
383
121
''' Descripttion: Version: 1.0 Author: ZhangHongYu Date: 2022-02-05 18:23:00 LastEditors: ZhangHongYu LastEditTime: 2022-05-17 16:26:12 ''' import os import sys import json import argparse from transformers import AlbertTokenizer from pytorch_pretrained_bert import BertTokenizer, BertForMaskedLM file_path = sys.argv[1...
1,490
533
from sqlalchemy import Column from sqlalchemy.types import JSON, Text, Boolean, TIMESTAMP, BigInteger from sqlalchemy.dialects import postgresql as psql from steampipe_alchemy.mixins import FormatMixins from steampipe_alchemy import Base class AwsRoute53ResolverRule(Base, FormatMixins): __tablename__ = 'aws_route...
1,651
525
import re from mimetypes import guess_type from django.conf import settings from datagrowth.processors import ExtractProcessor from datagrowth.utils import reach from core.constants import HIGHER_EDUCATION_LEVELS, RESTRICTED_MATERIAL_SETS class SharekitMetadataExtraction(ExtractProcessor): youtube_regex = re....
8,825
2,548
# # Copyright 2019-Present Sonatype 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 ...
1,518
457
import sublime, sublime_plugin import os #import subprocess def is_legal_path_char(c): # XXX make this platform-specific? return c not in " \n\"|*<>{}[]()" def move_while_path_character(view, start, is_at_boundary, increment=1): while True: if not is_legal_path_char(view.substr(start)): ...
6,046
1,774
#-*- coding: utf-8 -*- # # Copyright (C) 2007 Ole Trenner, <ole@jayotee.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import unittest from trac.db import DatabaseManager from trac.test import EnvironmentStub, M...
3,718
1,138
from autograd import grad import autograd.numpy as np import autograd.numpy.random as npr import autograd.scipy.special as sp from gamma_def import * # Define helper functions for score fnc estimator def logQ(sample, alpha, m): """ Evaluates log of variational approximation, vectorized. """ temp = alp...
1,962
829
x = float(input('Qual o valor da casa que quer comprar? ')) y = int(input("em quantos anos quer comprar a casa? ")) z = int(input("Qual seu salario? ")) w = y*12 if x / w > (z/100)*30: print("Voce não pode comprar a casa") else: print('Voce pode comprar a casa a parcela é de {:.2f}'.format(x/y))
305
121
import torch import random from torch.utils.data import Dataset, DataLoader from abc import ABC from models.base_model import Model from torch.utils.tensorboard import SummaryWriter from typing import List class BaseDataset(Dataset, ABC): name = 'base' def __init__(self, config: dict, mode: str = 'train'): self....
3,313
1,259
# Generated by Django 3.2 on 2021-04-21 13:01 from django.db import migrations, models class Migration(migrations.Migration): replaces = [('dataset', '0005_keyword'), ('dataset', '0006_remove_keyword_relevancy')] dependencies = [ ('dataset', '0004_alter_theme_id'), ] operation...
660
229
from .converter import Converter, Converters, ron
50
16
# -*- coding: utf-8 -*- """ Created on Wed Jan 23 08:25:37 2019 @author: AdeolaOlalekan """ from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import BTUTOR, CNAME, Edit_User, QSUBJECT, Post class login_form(forms.Fo...
2,385
737
# Lists # Basics foods = ['rice', 'Meat', 'vegetables', 'Eggs'] print(foods) # Same as foods[len(foods):] = ['butter'] foods.append('butter') print(foods) # Same as foods[len(foods):] = ['tomatoes', 'chili sauce'] foods.extend(['tomatoes', 'Chili sauce']) print(foods) # Reverse order of elements in th...
3,165
1,179
from flask import render_template def index(): return render_template("index.html", title='pond5 test')
110
31
"""Top-level package for Feature Flag Server SDK.""" __author__ = """Enver Bisevac""" __email__ = "enver@bisevac.com" __version__ = "0.1.0"
141
58
#!/usr/bin/env python import math, socket, struct, numpy as np, sys # Get the gradient of the potential of an obstacle # particle at (ox, oy) with the origin at (mx, my) # Get the potential of an obstacle particle at (ox, oy) # with the origin at (mx, my) def potential(mx, my, ox, oy): 1.0 / ((mx - ox)**2 + (m...
4,919
1,658
from itertools import imap, chain from pycparser import c_generator, c_ast from decomp import data, ida from decomp.c import decl as cdecl, types as ep_ct from decomp.cpu import ida as cpu_ida XXX_INTRO_HACK = cpu_ida.ida_current_cpu().insns.support_header + ''' #include <stdint.h> typedef union EPANOS_REG { uint8...
5,031
2,007
# -*- coding: utf-8 -*- __all__ = ( "extract_directory", "cleanup_data_directory", "dataset_schema", "validate_directory", "validate_directory_against_xsd", ) from .extract_ecospold2 import extract_ecospold2_directory from ..filesystem import check_cache_directory, get_from_cache, cache_data import...
1,112
356
#!/usr/bin/env python3 import stack import queue opset = {'*','+','(',")"} def readinfix(): fh = open("infix.txt") li = [] li += fh.read() print (li) return li def eval(): evlist = readinfix() postlist = [] st = stack.Stack() for op in evlist: if op in opset: s...
626
206
import random from qlazy import QState def classical_strategy(trials=1000): win_cnt = 0 for _ in range(trials): # random bits by Charlie (x,y) x = random.randint(0,1) y = random.randint(0,1) # response by Alice (a) a = 0 # response by Bob (b) b = 0 ...
2,102
762
# -*- coding: utf-8 -*- from .instance import BlockchainInstance from graphenecommon.blockchainobject import ( BlockchainObject as GrapheneBlockchainObject, BlockchainObjects as GrapheneBlockchainObjects, ObjectCache, ) @BlockchainInstance.inject class BlockchainObject(GrapheneBlockchainObject): pass ...
410
112
arr_1 = ["1","2","3","4","5","6","7"] arr_2 = [] for n in arr_1: arr_2.insert(0,n) print(arr_2)
102
56
from decimal import Decimal def ensure_decimal(value): return value if isinstance(value, Decimal) else Decimal(value)
124
37
from .idle_module import ( IdleManager, IIdleManager ) __all__ = ( "IdleManager", "IIdleManager" )
117
49
# This sample exercises the type analyzer's assert type constraint logic. from typing import Union def foo(a: Union[str, int]) -> int: if True: # This should generate an error because # a could be a str. return a assert isinstance(a, int) return a
289
85
import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend as K from keras.models import Sequential,Model from keras.layers import * from keras.optimizers import SGD,Adam class OurLayer(Layer): def reuse(self, layer, *args, **kwargs): if not layer.built: if len(a...
2,764
870
import numpy as np import pytest from infiniteremixer.remix.audiochunkmerger import AudioChunkMerger @pytest.fixture def chunk_manager(): return AudioChunkMerger() def test_chunk_manager_is_instantiated(chunk_manager): assert isinstance(chunk_manager, AudioChunkMerger) def test_audio_chunks_are_concatena...
774
286
from subprocess import PIPE, Popen # Converts celsius temps to fahrenheit def c2f(celsius): return (9.0 / 5) * celsius + 32 # Gets the CPU temperature in degrees C def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() return floa...
738
278
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
4,247
1,228
import json import logging from json import JSONDecodeError from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, ) from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from pretix.base.models import Organizer from . import tas...
1,354
413
# Copyright (c) 2020 Horizon Robotics and ALF Contributors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
12,300
3,356
import os from automon.log import Logging log = Logging(name=__name__, level=Logging.ERROR) class ConfigSlack: slack_name = os.getenv('SLACK_USER') or '' slack_webhook = os.getenv('SLACK_WEBHOOK') or '' slack_proxy = os.getenv('SLACK_PROXY') or '' slack_token = os.getenv('SLACK_TOKEN') or '' SL...
956
407
"""Top-level package for z2z Metadata analysis.""" __author__ = """Isthmus // Mitchell P. Krawiec-Thayer""" __email__ = 'project_z2z_metadata@mitchellpkt.com' __version__ = '0.0.1'
182
73
# Authors: Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause)
81
35
import inspect import os import re class TemplateHandler: # Constant definitions tab = " " nl = "\n" sem = ";" end = sem + nl def __init__(self, template_dir: str): self.templatepath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + \ ...
1,659
452
import base64 import binascii import logging import re import typing as t from discord import Colour, Message, NotFound from discord.ext.commands import Cog from bot import utils from bot.bot import Bot from bot.constants import Channels, Colours, Event, Icons from bot.exts.moderation.modlog import ModLog from bot.ut...
8,660
2,638