text
string
size
int64
token_count
int64
import unittest class TestKafkaConsumerConfig(unittest.TestCase): pass
77
25
if not __name__ == "__main__": print("Started <Pycraft_StartupAnimation>") class GenerateStartupScreen: def __init__(self): pass def Start(self): try: self.Display.fill(self.BackgroundCol) self.mod_Pygame__...
7,684
2,120
""" Submit files for a Kattis problem. Copyright (C) 2019, Guillaume Gonnet This project is under the MIT license. """ import os.path as path import re from typing import Dict, List, Text import requests import logging from .login import login logger = logging.getLogger(__name__) # Base headers to use. HEADERS ...
2,985
1,013
#!/usr/bin/env python3 """Script to do basic health checks of the system and turn on an LED on BCM pin 12 (pin 32 on header) if they pass, turn Off otherwise. """ import time import RPi.GPIO as GPIO import subprocess # The BCM pin number that the LED is wired to. When the pin # is at 3.3V the LED is On. LED_PIN = 12...
785
285
import json import numpy as np from tqdm import tqdm # Change these based on experiment #exp_dataset = 'mask_char_oov_test_set.db' #exp_name = 'results_test_mask_char' #exp_dataset = 'mask_2_oov_test_set.db' #exp_name = 'results_test_mask_2' #exp_dataset = 'mask_2_oov_test_set.db' #exp_name = 'results_test_synonyms_ma...
2,676
1,107
# -*- coding: utf-8 -*- """Article forms.""" from flask_wtf import Form, FlaskForm from wtforms import PasswordField, StringField, TextAreaField from wtforms.validators import DataRequired, Email, EqualTo, Length class NewArticleForm(FlaskForm): title = StringField('Article title', validators=[DataRequired(), Len...
528
169
#-*- coding: UTF-8 -*- #上句表示可用中文注释,否则默认ASCII码保存 # Filename : dataanalysis.py # author by : Rev_997 import numpy as np import pandas as pd import matplotlib.pyplot as plt def isiterable(obj): try: iter(obj) return True except TypeError:#not iterable return False #if i...
9,582
3,895
import bts.model as model import torch device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') BATCH_SIZE = 6 FILTER_LIST = [16,32,64,128,256] unet_model = model.DynamicUNet(FILTER_LIST) unet_model.summary(batch_size=BATCH_SIZE, device=device)
259
112
# -*- coding: utf-8 -*- import sphinx_rtd_theme # -- General configuration ----------------------------------------------- extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_te...
1,031
376
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB 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...
13,900
4,123
# -*- coding: utf-8 -*- # @Author: Kai Shen # @Created Time: 2022/2/23 10:14 AM # @Organization: YQN # @Email: mlshenkai@163.com import torch import torch.nn as nn import torch.nn.functional as F class FocalLoss(nn.Module): def __init__(self, gamma=2, weight=None, ignore_index=-100): super(FocalLoss, self...
824
316
import importlib import os import pytest from helpers import running_on_ci import janitor.biology # noqa: F403, F401 # Skip all tests if Biopython not installed pytestmark = pytest.mark.skipif( (importlib.util.find_spec("Bio") is None) & ~running_on_ci(), reason="Biology tests relying on Biopython only requ...
669
231
"""TilePyramid creation.""" import pytest from shapely.geometry import Point from shapely.ops import unary_union from types import GeneratorType from tilematrix import TilePyramid, snap_bounds def test_init(): """Initialize TilePyramids.""" for tptype in ["geodetic", "mercator"]: assert TilePyramid(...
12,182
4,651
# -*- coding: utf-8 -*- """ setup.py script """ import io from collections import OrderedDict from setuptools import setup, find_packages with io.open('README.md', 'rt', encoding='utf8') as f: README = f.read() setup( name='reportbuilder', version='0.0.1', url='http://github.com/giovannicuriel/report...
1,180
388
from __future__ import annotations from abc import ABC, abstractmethod from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class NoElement(Exception): pass class Option(ABC, Generic[T]): def __init__(self): super().__init__() @staticmethod def apply(value: T): ...
2,296
745
import cv2 import rosbag import rospy from cv_bridge import CvBridge def main(): # bag = rosbag.Bag("/home/satco/PycharmProjects/PoseCNN/bag/dataset_one_box.bag") bag = rosbag.Bag("/home/satco/PycharmProjects/PoseCNN/bag/test.bag") # topics = ["/camera1/color/image_raw", "/camera2/color/image_raw"] to...
1,237
441
from django.urls import path from itembase.core.views.location_views import LocationAddressCreateView, LocationAddressDetailView, \ LocationAddressUpdateView, LocationCreateView, LocationDeleteView, LocationDetailView, LocationListView, \ LocationUpdateView app_name = "locations" urlpatterns = [ path("", ...
909
269
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
3,455
1,060
name = input('Enter file name: ') lst=list() lst2=list() with open(name) as f: for line in f: #print(line) blops=line.rstrip() blop=blops.split() #for val in blop: my_lst = [float(val) for val in blop]#list_comprehension for num in my_lst: if num ...
1,038
419
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from PIL import Image # Create your models here. class Home(models.Model): pass class CustomUserManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, f...
2,470
764
height = int(input()) for i in range(1,height+1) : for j in range(1, i+1): m = i*j if(m <= 9): print("",m,end = " ") else: print(m,end = " ") print() # Sample Input :- 5 # Output :- # 1 # 2 4 # 3 6 9 # 4 8 12 16 # 5 10 15 20 25
316
145
"""Search-related testing utilities.""" import tempfile import time from contextlib import contextmanager import haystack from django.conf import settings from django.core.management import call_command from djblets.siteconfig.models import SiteConfiguration from reviewboard.admin.siteconfig import load_site_config ...
2,617
749
# Copyright (C) 2015 Stefan C. Mueller import json import os.path from remoot import pythonstarter, smartstarter import anycall from pydron.backend import worker from pydron.interpreter import scheduler, strategies from twisted.internet import defer preload_packages = [] def load_config(configfile=None): if...
6,434
1,860
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This plugin provides customization of the header displayed by pytest for reporting purposes. """ import os import sys import datetime import locale import math from collections import OrderedDict from astropy.tests.helper import ignore_warnings from ...
4,678
1,401
from typing import Any, List, cast from fastapi import Depends from rx import operators as rxops from api_server.base_app import BaseApp from api_server.fast_io import FastIORouter, WatchRequest from api_server.models import Lift, LiftHealth, LiftRequest, LiftState from api_server.repositories import RmfRepository f...
2,782
871
#!/usr/local/bin/python3.6 """ Copyright (c) 2015-2019 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain ...
5,228
1,510
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
3,592
1,249
from __future__ import print_function, division import numpy as np import Nio import time, os # # Creating a file # init_time = time.clock() ncfile = 'test-large.nc' if (os.path.exists(ncfile)): os.system("/bin/rm -f " + ncfile) opt = Nio.options() opt.Format = "LargeFile" opt.PreFill = False file = Nio.open_file(nc...
1,965
790
#This file is part of ElectricEye. #SPDX-License-Identifier: Apache-2.0 #Licensed to the Apache Software Foundation (ASF) under one #or more contributor license agreements. See the NOTICE file #distributed with this work for additional information #regarding copyright ownership. The ASF licenses this file #to you un...
36,178
9,082
""" This slider controls interpolation between foreground and mask layers. Initial position for slider is at 1.0 (current foreground outline) Sliding left to 0.0 interpolates to mask Sliding right to 3.0 extrapolates away from mask. NOTE: Running this script opens an observer on the current glyph in the Glyph View wi...
7,470
2,318
# Continuação do ex061 (Termos de PA) print('Gerador de PA') print('-=' * 10) primeiro = int(input('Primeiro termo: ')) razão = int(input('Razão: ')) i = 0 n = 10 novos = 10 total = 0 while novos != 0: total = total + novos while i < total: termo = primeiro + razão * i i += 1 print(termo...
429
176
from random import randint from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from order.serializers import OrderSerializer from product.models import Product from order.models import Order from rest_framework import status from rest_framework.test import API...
4,151
1,225
import unittest from .mocks import BotoSessionMock from push_notification import apns class APNSTestCase(unittest.TestCase): def_apns_category = 'MGDailyDealCategory' # def setUp(self): # def tearDown(self): # push_notification # push_background # make_new_deal_message # make_delta_...
6,950
2,199
# -*- coding: utf-8 -*- from HTMLParser import HTMLParser # ------------------------------------------------------- # # LinkExtractor: extract links from html page # class BaseExtractor(HTMLParser): def __init__(self): HTMLParser.__init__(self) self._links = [] @property def links(se...
809
250
## Django Packages from django import forms from django_select2 import forms as s2forms ## App packages from .models import * from datetime import datetime from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput, DateTimePickerInput, MonthPickerInput, YearPickerInput from tags_input import fields from l...
2,227
586
import analyseGithub def test_containsGithubURL_empty(): assert not analyseGithub.containsGitHubURL("") def test_containsGithubURL_noUrl(): assert not analyseGithub.containsGitHubURL("Some test tweet") def test_containsGithubURL_url(): repo = "https://github.com/git/git" assert analyseGithub.contains...
485
161
# -*- coding: utf-8 -*- ''' tests.unit.utils.filebuffer_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2012 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. ''' # Import salt libs ...
1,069
340
############################################################################### # Author: Wasi Ahmad # Project: ARC-II: Convolutional Matching Model # Date Created: 7/18/2017 # # File Description: This script contains ranking evaluation functions. ##################################################################...
2,881
1,006
"""WWUCS Bot module.""" __all__ = [ "__author__", "__email__", "__version__", ] __author__ = "Reilly Tucker Siemens" __email__ = "reilly@tuckersiemens.com" __version__ = "0.1.0"
192
85
# Copyright (c) 2021 PaddlePaddle Authors. 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 required by appli...
10,638
3,421
import insightconnect_plugin_runtime from .schema import DiskDetachInput, DiskDetachOutput, Input, Component class DiskDetach(insightconnect_plugin_runtime.Action): def __init__(self): super(self.__class__, self).__init__( name="disk_detach", description=Component.DESCRIPTION, input=DiskDetac...
551
166
"""Serializers for the payment app.""" from rest_framework import serializers from models import Purchases class TransactionSerializer(serializers.ModelSerializer): """Serializer for Transaction instances. """ class Meta: model = Purchases fields = ('id', 'item', 'price', 'quantity', 'ti...
431
112
import random import seaborn as sns import matplotlib.pyplot as plt import numpy as np from mla.base import BaseEstimator from mla.metrics.distance import euclidean_distance random.seed(1111) class KMeans(BaseEstimator): """Partition a dataset into K clusters. Finds clusters by repeatedly assigning each d...
4,817
1,389
import os import sys import argparse import time import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable # from sru import * import dataloader import modules class Model(nn.Module): def __init__(self, embe...
10,741
3,678
import logging from time import sleep logger = logging.getLogger(__name__) class StopRequestQueue: cursor = 0 queue = None service = None current_request = None request_delay = 0 # seconds def __init__(self, service, request_delay=10): self.queue = [] self.service = service self.request_dela...
1,844
553
#!/usr/bin/env python import cv2, os, sys import numpy as np def extractImage(path): # error handller if the intended path is not found image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) return image def checkImage(image): """ Args: image: input image to be checked Returns: binary ...
5,826
1,884
import unittest from unittest.mock import patch import os from .ansible_test_framework import AnsibleTestFramework, RecordMaker import keeper_secrets_manager_ansible.plugins import tempfile records = { "TRd_567FkHy-CeGsAzs8aA": RecordMaker.make_record( uid="TRd_567FkHy-CeGsAzs8aA", title="JW-F1-R1...
4,047
1,355
"""Packages containing all the possible attributes to recordings, such as - channels (module "chan") with class: - Chan - anatomical info (module "anat") with class: - Surf - annotations and sleep scores (module "annotations") with class: - Annotations Possibly include forward and i...
1,180
294
""" =========== What is Matter Parameters =================== """ #tups = [(125.0, 1.0), (125.0, 1.5), (125.0, 2.0), (125.0, 2.5), (125.0, 3.0), (150.0, 1.0), (150.0, 1.5), (150.0, 2.0), (150.0, 2.5), (150.0, 3.0), (175.0, 1.0), (175.0, 1.5), (175.0, 2.0), (175.0, 2.5), (175.0, 3.0), (200.0, 1.0), (200.0, 1.5), (200.0,...
1,418
1,070
"""Call various Terraform actions.""" import os import os.path from invoke import task import jinja2 import yaml TERRAFORM_VERSION = '0.11.7' @task def install(c, ostype='linux', version=TERRAFORM_VERSION): """Download a local version of Terraform.""" if ostype == 'mac': ostype = 'darwin' file...
3,213
1,062
import sys # import osgeo.utils.gdal2xyz as a convenience to use as a script from osgeo.utils.gdal2xyz import * # noqa from osgeo.utils.gdal2xyz import main from osgeo.gdal import deprecation_warn deprecation_warn('gdal2xyz', 'utils') sys.exit(main(sys.argv))
263
94
from .body_reid_model_name import BodyReidModelName class BodyReidModelFactory(): def create(model_name, model_path, model_precision): if model_name == BodyReidModelName.osnet_x0_25.value: from .model.osnet.osnet_x0_25 import OSNetX025 return OSNetX025...
587
172
import datetime import io import os import tweepy from dotenv import load_dotenv from PIL import Image, ImageDraw, ImageFont class Twitter: """ A class used to manage the connection with the Twitter API ... Methods ------- post_tweet(solver_answers, nyt_answers, pangrams) Creates the...
3,931
1,226
x = 2 print(x) # multiple assignment a, b, c, d = (1, 2, 5, 9) print(a, b, c, d) print(type(str(a)))
106
61
#!/usr/bin/env python # # This is a demo application to demonstrate the functionality of the safrs_rest REST API with authentication # # you will have to install the requirements: # pip3 install passlib flask_httpauth flask_login # # This script can be ran standalone like this: # python3 demo_auth.py [Listen...
4,773
1,613
import goless import time from sys import platform if platform == "linux" or platform == "linux2": import brickpi3 def start_color_sensor(brick, port, channel): print("start color sensor") setup_sensor(brick, port) goless.go(run_color_sensor, brick, port, channel) print("color sensor started") ...
2,045
706
# -*- coding: utf-8 -*- """ :Author: Dominic Hunt """ import logging import numpy as np import scipy as sp import collections import itertools from model.modelTemplate import Model class BPE(Model): """The Bayesian predictor model Attributes ---------- Name : string ...
8,757
2,537
from django.db.models.signals import post_init from factory import DjangoModelFactory, Sequence, SubFactory from factory.django import mute_signals from affiliates.banners import models class CategoryFactory(DjangoModelFactory): FACTORY_FOR = models.Category name = Sequence(lambda n: 'test{0}'.format(n)) ...
1,688
556
from .request import Request from .response import Response class HttpRequestCookieTrait: 'Designed for the Request Object; Adds methods to store COOKIE data' def get_cookies(self, *args): 'Returns COOKIE given name or all COOKIE' return self.get('cookie', *args) def remove_cookies(self,...
7,996
2,367
import pluggy hookimpl = pluggy.HookimplMarker('mylauncher') def get_class(): return CommandPlugin() class CommandPlugin: @hookimpl def setup(self): print("Setup ...") @hookimpl def get_alias(self): return "command" @hookimpl def execute(self, input:str): return...
326
104
#! /usr/bin/env python """Toolbox for unbalanced dataset in machine learning.""" from setuptools import setup, find_packages import os import sys import setuptools from distutils.command.build_py import build_py if sys.version_info[0] < 3: import __builtin__ as builtins else: import builtins descr = """Tool...
5,022
1,433
from .rev_id_scorer import RevIdScorer __all__ = [RevIdScorer]
64
30
""" Conjuntos — Conjunto em qualquer linguagem de programação, estamos fazendo referência à teoria de conjuntos da matemática — Aqui no Python, os conjuntos são chamados de sets Dito isto, da mesma forma que na matemática: — Sets (conjuntos) não possuem valores duplicados; — Sets (conjuntos) não possuem valores ordena...
4,311
1,634
"""Test gpreg.py.""" from typing import Tuple import numpy as np import pytest from gdec import gpreg, npgp @pytest.fixture(scope="module") def dataset() -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: np.random.seed(42) amplitude = 1.0 lengthscale = 12 sigma = 0.5 n = 128 def spe...
1,346
557
#!/usr/bin/env python __author__ = "Yaroslav Litvinov" __copyright__ = "Copyright 2016, Rackspace Inc." __email__ = "yaroslav.litvinov@rackspace.com" from mongo_schema import schema_engine import os def get_schema_files(schemas_dirpath): """ get list of js / json files resided in dirpath param. """ res = [] ...
1,008
329
# OpenWeatherMap API Key weather_api_key = "ae41fcf95db0d612b74e2b509abe9684" # Google API Key g_key = "AIzaSyCuF1rT6NscWq62bcBm0tZM7hKlaeWfONQ"
146
92
#!usr/bin/python import os import numpy as np import common from interpret import qcfile, funcfile, analyzefiles def runAll(args): print('\n\n\nYou have requested to analyze CNV call data') print('\tWARNING:') print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY...
5,240
2,123
# -*- coding: utf-8 -*- """This module contains the MRC file class. """ __author__ = 'Wenzhi Mao' __all__ = ['MRC'] class MRCHeader(): """A header class for mrc file.""" def __init__(self, filename=None, **kwargs): """Provide the filename to parse or set it later.""" self.nx = self.ny = s...
29,527
8,639
from random import randint from django.core.management.base import BaseCommand from django.db import transaction from faker import Faker from hn_users.models import HNUser, User from links.models import Link, Vote faker = Faker() class Command(BaseCommand): help = "Generate Links from a small user subset" ...
2,416
755
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem class CenexSpider(scrapy.Spider): name = "cenex" item_attributes = {"brand": "Cenex", "brand_wikidata": "Q5011381"} allowed_domains = ["www.cenex.com"] def start_requests(self): yield scrapy.http.Js...
3,010
983
import os import multiprocessing if os.name != "nt": # https://bugs.python.org/issue41567 import multiprocessing.popen_spawn_posix # type: ignore from pathlib import Path from typing import Optional # PROFILES_DIR must be set before the other flags # It also gets set in main.py and in set_from_args because t...
6,794
2,450
import asyncio import functools from copy import deepcopy from ensureTaskCanceled import ensureTaskCanceled def _no_closed(method): ''' Can not be run when closed. :return: ''' @functools.wraps(method) def wrapper(*args, **kwargs): self = args[0] if self._closed: r...
2,223
666
import os # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"] = "1" from src.python.baselines import * from pymongo import MongoClient from tqdm import tqdm import tensorflow as tf ### Keras from keras import optimizers from keras.models import Model from keras.layers import Input...
13,886
5,263
import matplotlib.pyplot as plt import openpyxl import sys from fs import FS from journals import Journals from utils import load_sheet from utils import log from word import Word YEARS = [2017, 2018, 2019, 2020, 2021] class InBiMa(): def __init__(self, is_new_folder=False): self.fs = FS(is_new_folder...
5,977
2,018
import pymongo from bson.json_util import dumps from pymongo import MongoClient from UkDatabaseAPI.database.database import Database from UkDatabaseAPI.database.query_builder.mongo_query_builder import MongoQueryBuilder MONGO_URI = "mongodb://localhost:27017" """str: The MongoDB URI.""" class MongoDB(Database): ...
2,183
604
from django.forms import ( Form, CharField, Textarea, PasswordInput, ChoiceField, DateField, ImageField, BooleanField, IntegerField, MultipleChoiceField ) from django import forms from fb.models import UserProfile class UserPostForm(Form): text = CharField(widget=Textarea( attrs={'rows': 1, 'cols...
1,485
455
# Simple implementation of GalaxyInvanders game # Rohan Roy (India) - 3 Nov 2013 # www.codeskulptor.org/#user23_fTVPDKIDhRdCfUp VER = "1.0" # "add various aliens" import simplegui, math, random, time #Global const FIELD_WIDTH = 850 FIELD_HEIGHT = 500 TOP_MARGIN = 75 LEFT_MARGIN = 25 ALIEN_WIDTH = 48 ...
28,863
11,591
from flask import Flask, jsonify, request, render_template, redirect from flask_pymongo import PyMongo from werkzeug import secure_filename import base64 app = Flask(__name__) app.config['MONGO_DBNAME'] = 'restdb' app.config['MONGO_URI'] = 'mongodb://localhost:27017/restdb' mongo = PyMongo(app) @app.route('/') def ...
1,664
608
""" Utilities :Author: Jonathan Karr <karr@mssm.edu> :Date: 2016-11-10 :Copyright: 2016, Karr Lab :License: MIT """ from obj_tables import get_models as base_get_models from wc_lang import core from wc_lang import io from wc_utils.util import git def get_model_size(model): """ Get numbers of model components ...
2,190
717
import synapse.common as s_common import synapse.tests.utils as s_t_utils import synapse.tools.autodoc as s_autodoc class TestAutoDoc(s_t_utils.SynTest): async def test_tools_autodoc_docmodel(self): with self.getTestDir() as path: argv = ['--doc-model', '--savedir', path] outp...
5,267
1,756
# -*- coding: utf-8 -*- import pickle import os import jieba from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.externals import joblib from sklearn.metrics.pairwise import cosine_similarity class TfIdf: def __init__(self, config): self.config = config self.model_dict = {}...
4,174
1,372
""" Module for classifier Models (c) 2020 d373c7 """ import logging import torch import torch.nn as nn from .common import PyTorchModelException, ModelDefaults, _History, _ModelGenerated, _ModelStream from .encoders import GeneratedAutoEncoder from ..layers import LSTMBody, ConvolutionalBody1d, AttentionLastEntry, Line...
19,015
5,388
import re import numpy as np import pandas as pd import matplotlib as mpl mpl.use("pdf") import matplotlib.pyplot as plt from matplotlib import gridspec from peewee import AsIs, JOIN, prefetch, SQL from IPython import embed from bokeh.layouts import row, column from bokeh.plotting import figure, show, output_file fr...
5,369
1,953
"""SharedBrandConfigs API Tests for Version 1.0. This is a testing template for the generated SharedBrandConfigsAPI Class. """ import unittest import requests import secrets from py3canvas.apis.shared_brand_configs import SharedBrandConfigsAPI from py3canvas.apis.shared_brand_configs import Sharedbrandconfig class T...
1,328
367
from abc import ABC, abstractmethod from django.test import TestCase from rest_framework.generics import GenericAPIView from rest_framework.test import APIRequestFactory from apps.cars.factory import UserFactory class AbstractBaseTest(object): class AbstractBaseApiTestCase(TestCase, ABC): """ A...
1,095
277
""" A simple templating tool for Dockerfiles """ import sys import os import click import jinja2 import yaml @click.group() def cli(): """ @Unimplemented """ pass @cli.command() @click.argument("template", required=True, type=str) @click.option("-y", "--yaml_file", required=True, help="Yaml ...
995
352
"""File for holding the different verb forms for all of the verbs in the Total English book series.""" verb_forms = { 'become' : { 'normal' : 'become', 'present' : ['become','becomes'], 'past' : 'became', 'past participle' : 'become', 'gerund' : 'becoming', }, 'be': { 'n...
11,552
4,778
''' Provides API for loading themes ''' from __future__ import absolute_import from os.path import join from .theme import Theme default = Theme(json={}) del join
169
54
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Dirk Stöcker <trac@dstoecker.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software...
4,321
1,303
#!/usr/bin/env python # coding: utf-8 # In[18]: # this definition exposes all python module imports that should be available in all subsequent commands import json import numpy as np import pandas as pd from causalnex.structure import DAGRegressor from sklearn.model_selection import cross_val_score from sklear...
3,222
1,140
import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation matplotlib.use('Agg') import math import numpy as np import sys from os.path import join, isfile import warnings warnings.filterwarnings("ignore") def gda(x, y): x = x.T y = y.T # phi = P(y = 1) # mu[i] = mea...
6,500
2,761
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Bcache(MakefilePackage): """Bcache is a patch for the Linux kernel to use SSDs to cache ot...
1,521
774
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-21 23:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0009_wagtail112upgrade'), ] operations = [ migrations.RenameField( model_name='wagtailsitepage', ...
645
215
# SPDX-FileCopyrightText: © 2020 The birch-books-smarthome Authors # SPDX-License-Identifier: MIT BOOKSTORE_GROUND_FLOOR = 0x0007 BOOKSTORE_FIRST_FLOOR = 0x0008 BOOKSTORE_TERRARIUM = 0x0010 BOOKSTORE_BEDROOM = 0x0020 HOUSE_BASEMENT = 0x0040 HOUSE_GROUND_FLOOR = 0x0380 HOUSE_BEDROOM_LIGHT = 0x0400 HOUSE_BEDROOM_LAMP = ...
1,555
882
import bcrypt salt = bcrypt.gensalt() def generate_hash(passwd, salt=salt): return str(bcrypt.hashpw(passwd, salt)) def match_password(req_pwd, db_pwd): db_pwd = db_pwd.replace('b\'','').replace('\'','').encode('utf-8') return db_pwd == bcrypt.hashpw(req_pwd, db_pwd)
284
123
from test.test_base import TestBase class TestMath(TestBase): def test_isclose(self): _test = self._assert_execute _test('ㄹ (ㄱㅇㄱ ㄱㅇㄱ ㄴㄱ ㅅㅎㄷ ㄱㅎㄷ ㄴ (ㅂ ㅅ ㄱ ㅂㅎㄹ)ㅎㄷㅎ)ㅎㄴ', 'True') _test('ㅂ ㅅ ㅂ ㅂㅎㄹ (ㄱㅇㄱ ㄱㅇㄱ ㄴㄱ ㅅㅎㄷ ㄱㅎㄷ ㄴ (ㅂ ㅅ ㄱ ㅂㅎㄹ)ㅎㄷㅎ)ㅎㄴ', 'True') _test('ㅂ ㅅ ㅈ ㅂㅎㄹ (ㄱㅇㄱ ㄱㅇㄱ ㄴㄱ ㅅㅎㄷ ㄱㅎㄷ ㄴ (ㅂ...
14,200
20,125
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Jan-Piet Mens <jpmens()gmail.com>' __copyright__ = 'Copyright 2014 Jan-Piet Mens' __license__ = """Eclipse Public License - v 1.0 (http://www.eclipse.org/legal/epl-v10.html)""" import smtplib from email.mime.text import MIMEText def plugin(srv, item): ...
1,563
527
""" Module for Serialization and Deserialization of a KNX Disconnect Request information. Disconnect requests are used to disconnect a tunnel from a KNX/IP device. """ from __future__ import annotations from typing import TYPE_CHECKING from xknx.exceptions import CouldNotParseKNXIP from .body import KNXIPBody from ...
1,865
593
from src.sqlite_helper import create_message_table, drop_message_table """ This script will create a SQLite table for you, and should be one time setup The table name is message which will store all the Post message """ create_message_table() """ If you need to drop the message table, un-comment the following code ...
391
109
from java.lang import String import threading import random import codecs import io import itertools import time import os import urllib2 import textwrap import socket import shutil ############################################################# # This is the ZOrba # ##################################################...
5,401
1,947