text
string
size
int64
token_count
int64
import asyncio import pytest from supriya.assets.synthdefs import default from uqbar.strings import normalize from tloen.domain import Application, Instrument from tloen.midi import NoteOnMessage @pytest.fixture async def application(): application = Application() context = await application.add_context(nam...
2,641
928
import os USERNAME='bbenton' PROJECT_CODE='UCOR0044' MAIN_DIR='/glade/u/home/'+USERNAME+'/spring_onset/' MY_CESM_DIR=MAIN_DIR+'/my_cesm' POST_PROC_DIR=MAIN_DIR+'/idealplanets/postprocessing/' PRE_PROC_DIR=MAIN_DIR+'/idealplanets/preprocessing/' SCRATCH_DIR='/glade/scratch/'+USERNAME+'/' CIME_OUTPUT_ROOT=SCRATCH_DIR+'/...
1,357
799
from flask import Blueprint, render_template, request, redirect, Response, url_for from flask_login import login_required, current_user from flask_wtf.csrf import validate_csrf from app.services.models.service import ( Service, get_services...
5,316
1,416
import json from unittest import TestCase, skip from unittest.mock import patch from app_settings.app_settings import AppSettings from rq_settings import prefix, webhook_queue_name from webhook import process_webhook_job def my_get_current_job(): class Result: id = 12345 origin = webhook_queue_na...
915
279
from __future__ import annotations import asyncio import json import logging from dataclasses import dataclass from typing import Any, Awaitable, Callable, Dict, Tuple, Union from starlette.applications import Starlette from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles...
5,799
1,748
import unittest from strings.lsd_string_sort import lsd_sort class LSDSort(unittest.TestCase): def setUp(self): self.licenses = [ "4PGC938", "2IYE230", "3CI0720", "1ICK750", "1OHV845", "4JZY524", "1ICK750", "3C...
650
246
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.experimental.scala.register import rules as all_kotlin_rules from pants.backend.kotlin.lint.ktlint import rules as ktlint_rules from pants.backend.kotlin.lint.ktlint imp...
458
148
""" Lagrange's Interpolation class File """ import sympy as sp import numpy as np from time import process_time as timer class Neville: def __init__(self): self.Q = [] self.time_ellapsed = 0 self.x = np.array([]) self.y = np.array([]) self._x = sp.symbols('x', real=True) ...
2,523
878
from supportbot.bots import FuzzyMatchingSupportbot from helpers import get_fixture_filepath def _make_bot(filename): filepath = get_fixture_filepath(filename) return FuzzyMatchingSupportbot(filepath) def test_fuzzy_matching_reply(): filename = "questions_answers.txt" question = "OK?" bot = _m...
1,103
394
import json import sys from websocket import create_connection sys.path.append('.') sys.path.append('./modules/OSBot-Utils') from osbot_utils.utils.Files import Files from flask import Flask,request,redirect,Response #from flask_socketio import SocketIO, emit import requests from gw_proxy.api.Http_Proxy import Http...
6,668
2,161
from unittest import TestCase from .. .spectrumuncurver import SpectrumUncurver from PIL import Image from scipy.optimize import curve_fit import numpy as np from matplotlib import pyplot as plt class TestSpectrumProcessor(TestCase): def setUp(self) -> None: self.processor = SpectrumUncurver() def te...
1,029
353
# -*- coding: utf-8 -*- import hashlib import logging import os import uuid import importlib from django.conf import settings from django.contrib.auth.models import User from django.utils.crypto import random import pygeoip logger = logging.getLogger('aldryn_accounts') def user_display(user, fallback_to_username=...
4,286
1,435
import time import MeCab from tqdm import tqdm import argparse import torch import torch.nn.functional as F from model import Model from utils.functional import load_image_caption, str2bool mecab = MeCab.Tagger('-Ochasen') parser = argparse.ArgumentParser('Rerank all generated captions') parser.add_argu...
4,513
1,489
import json import pytz from datetime import datetime, timedelta try: # For Python 3.0 and later from urllib.parse import urlparse from urllib.parse import urljoin except ImportError: # Fall back to Python 2.7 from urlparse import urlparse from urlparse import urljoin from .exception import * f...
16,924
4,828
from django.apps import AppConfig class StripeShopConfig(AppConfig): name = 'stripe_shop'
96
34
from .config import get_config, set_config __all__ = ('get_config', 'set_config')
83
29
""" This module contains a list of common imports Useful to rapidly start a Notebook without writing all imports manually. It will also set up the main logging.Logger ## Usage ```python from emutils.imports import * ``` ## Imports - Python Standard Modules: os, sys, time, platform, gc, math, random, collections, it...
3,799
1,188
#----------------------------------------------------------------------------- # Heuristic for coverage calculation # author: Stefano Perticoni #----------------------------------------------------------------------------- import coverageScript import os import sys, string import unittest import urllib, urllib2 cla...
1,294
420
import random import urllib from scapy.layers import http import exfilkit as lpz from exfilkit import methods ENCODING_TABLE = { '0': 'radio', '1': 'spoke', '2': 'thick', '3': 'human', '4': 'atom', '5': 'effect', '6': 'electric', '7': 'expect', '8': 'bone', '9': 'rail', '...
11,276
4,415
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def solver(self, r1, r2): if r1 == None and r2 == None: return Non...
1,422
494
import os import libcxx.test.config import libcxx.android.test.format class Configuration(libcxx.test.config.Configuration): def __init__(self, lit_config, config): super(Configuration, self).__init__(lit_config, config) self.cxx_under_test = None self.cxx_template = None self.lin...
1,919
621
import json from controller import follow, postback, message, cron, image from datetime import datetime from flask import Flask, request, abort, render_template from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import ( MessageEvent, FollowEvent, PostbackEvent, TextMess...
2,341
791
from .context import blocklistde import unittest class ConnectTestSuite(unittest.TestCase): def test_ip_list(self): ip = blocklistde.BlocklistDe.ssh() self.assertGreater(len(ip), 10, 'Found a total of {0} ipaddresses'.format(len(ip))) if __name__ == '__main__': unittest.main()
307
108
#-*- coding: utf-8 -*- from __future__ import (print_function, division, absolute_import, unicode_literals) import networkx as nx import numpy as np import random class VoterModel(object): """Voter model. Wikipedia: https://en.wikipedia.org/wiki/Voter_model """ def __ini...
1,725
493
print(r""" ______ <((((((\\\ / . }\ ;--..--._|} (\ '--/\--' ) \\ | '-' :'| \\ . -==- .-| \\ \.__.' \--._ [\\ __.--| // _/'...
16,016
5,427
import unittest from mock import patch, MagicMock from botocore.exceptions import ClientError from flotilla.cli.scheduler import start_scheduler REGIONS = ['us-east-1'] ENVIRONMENT = 'develop' DOMAIN = 'test.com' class TestScheduler(unittest.TestCase): @patch('flotilla.cli.scheduler.get_instance_id') @patc...
1,992
705
from montreal_forced_aligner.command_line.mfa import parser from montreal_forced_aligner.command_line.validate import run_validate_corpus def test_validate_corpus( multilingual_ipa_tg_corpus_dir, english_ipa_acoustic_model, english_us_ipa_dictionary, temp_dir ): command = [ "validate", multil...
1,677
600
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. # # Modifications Copyright OpenSearch Contributors. See # GitHub history for details. # # Licensed to Elasticsearch B.V. under...
3,857
1,161
from django.db import models class Post(models.Model): content = models.TextField()
90
26
""" Purchases API """ from rest_framework import serializers from apps.users.api.serializers import UserSerializer from apps.inventory.api.serializers import InventoryItemSerializer from apps.products.api.serializers import (MaterialSerializer, ProductDesignSerializer) from .....
3,438
900
import requests URL_USERS = "https://gorest.co.in/public/v2/users" URL_COMMENTS = "https://gorest.co.in/public/v2/comments" def extract_users(): """ Method for get users from API Rest :return: """ r = requests.get(url=URL_USERS) return r.json() def extract_comments(): """ Method for...
619
217
# Google sheets from __future__ import print_function import httplib2 import os from apiclient import discovery import oauth2client from oauth2client import client from oauth2client import tools try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: ...
3,063
1,052
"""Top-level package for pythx.""" __author__ = """Dominik Muhs""" __email__ = "dominik.muhs@consensys.net" __version__ = "1.3.2" from pythx.conf import config from pythx.api.client import Client from mythx_models.exceptions import ( MythXBaseException, MythXAPIError, ValidationError, ValidationError,...
323
119
import actstream.urls from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin import ore.core.urls import ore.accounts.urls import ore.projects.urls import ore.versions.urls import ore.teams.urls import ore.discourse_sso.urls...
1,529
550
import uuid def set_created_by_if_empty(model, user): """ This function is called by our save function because django throws exceptions on object access if something doesn't exist. You cannot dereference a related field if it doesn't exist. Meaning you have to do a try except block. """ try...
895
269
import os import time import copy import random import argparse import numpy as np from PIL import Image from tqdm import tqdm as tq import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.utils import data from model_utils import * from data_utils import * from t...
6,882
2,391
from __future__ import annotations import asyncio import aiohttp from datetime import datetime class Forecast: def __init__(self, totals: dict, grid_x: int, grid_y: int, cwa: str, city: str, state: str): self.totals = totals self.simplified_dict = {key: '...' for key in totals.keys()} self....
2,398
698
# ----------------------------------------------------------------------------- # Copyright (c) 2020 Nicolas P. Rougier. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- # This example shows how to display a mesh # ----------...
1,170
361
import os, sys from PIL import Image import argparse from os import listdir from os.path import isfile, join if __name__ == '__main__': maxheigth = 320 maxwidth = 320 parser = argparse.ArgumentParser(description='Cleaning files that are too big.') parser.add_argument('-dir', '--d', help="Directory name...
1,193
384
""" Problem: Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of words 'quick', 'brown', 'the'...
1,543
513
import sys import argparse import os import piexif from PIL import Image def jpg_exif_remove(args): """ Removes EXIF data from directory of jpeg images whilst preserving image orientation and quality. Parameters ---------- in_dir: string, directory containing jpgs to have EXIF removed, default 'images' out...
2,872
1,099
from .conn import BoilerConn from .controller import WaterColumnController, WaterTempController from .core import Main from .reader import WaterColumnReader, WaterTempReader __all__ = [ 'BoilerConn', 'WaterColumnController', 'WaterTempController', 'WaterColumnReader', 'WaterTempReader', 'Main',...
385
119
import io from datetime import datetime import nextcord as discord from nextcord.ext import commands import aiohttp import pandas # Load config from config import config color = config.color class Covid(commands.Cog): def __init__(self, client): self.client = client @commands.command(name = 'covid')...
8,226
1,858
import os import argparse parser = argparse.ArgumentParser(description = 'gem5 with fault injection') parser.add_argument('-log', '--log-file', type = str, dest = 'logFile', help = 'The input file of debug info of Gem5 simulator') parser.add_argument('-in', '--input-fault', type = str, dest = 'faultFile', h...
2,462
927
from django.conf.urls import include, patterns from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^testproject/', include('...
1,362
380
# Copyright (c) 2018 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. import mock import errno from iml_common.lib.shell import Shell from iml_unit_testcase import ImlUnitTestCase class CommandCaptureCommand(object): def __init__(se...
5,404
1,498
from mmxai.interpretability.classification.torchray.extremal_perturbation.multimodal_extremal_perturbation import * from mmf.models.mmbt import MMBT from mmf.models.fusions import LateFusion from mmf.models.vilbert import ViLBERT from mmf.models.visual_bert import VisualBERT from PIL import Image def torchray_multimo...
2,017
529
import pytest from .util import make_tempdir from moonpy.util import json_dumps, read_json def test_json_dumps_sort_keys(data): result = json_dumps(data["data"], sort_keys=True) assert result == data["sorted_file_contents"] def test_read_json_file(data): with make_tempdir({data["file_name"]: data["file...
812
270
import re, collections bot = collections.defaultdict(list) output = collections.defaultdict(list) values = open('d10.in').read().splitlines() pipeline = {} for value in values: if value.startswith('value'): n, b = map(int, re.findall(r'-?\d+', value)) bot[b].append(n) elif value.startswith('...
869
361
import glob from torch.utils.data import Dataset import torchvision.transforms.functional as TF import torchvision as tv import xml.etree.ElementTree as ET from PIL import Image import numpy as np import random import os from transformers import BertTokenizer from .utils import nested_tensor_from_tensor_list MAX_D...
6,063
2,021
from idt.duckgo import DuckGoSearchEngine from idt.bing import BingSearchEngine from idt.bing_api import BingApiSearchEngine from idt.flickr_api import FlickrApiSearchEngine __name__ = "factories" class SearchEngineFactory: def __init__(self,data,n_images,folder,verbose,root_folder,size,engine,api_key): self.data...
1,177
438
# New video tutorials are available at https://www.microprediction.com/python-1 to help you # get started creating streams (see the 4th module in particular) import logging import urllib import time import pytz import random from datetime import datetime from pprint import pprint from microprediction import MicroWrite...
3,075
941
from copy import copy from unittest.mock import Mock import jwt import pytest from django.contrib.auth.models import AnonymousUser from django.core.cache import cache from django.test import RequestFactory from jwcrypto.jwk import JWK, JWKSet from .common import QUERY_DICT, SESSION_DICT class JWKTestHelper: __s...
2,188
782
import abc import numpy as np def split_train_test(data, labels, dim): """ Method that randomly choose the train and test sets from data and labels. # Arguments: data: Numpy matrix with data for extract the validation data labels: Numpy array with labels dim: Size for validation d...
3,384
962
from enum import Enum import time from collections import defaultdict from nltk.corpus import stopwords from dataanalysis import nlp_utils as nlp from ontomatch import glove_api from ontomatch import ss_utils as SS from datasketch import MinHash, MinHashLSH from knowledgerepr.networkbuilder import LSHRandomProjectionsI...
26,945
8,682
# -*- coding: utf-8 -*- import scrapy import requests import pymongo import time import re from datetime import datetime from details.items import DetailsItem class TruyenqqSpider(scrapy.Spider): name = 'truyenqq' # allowed_domains = ['truyenqq.com'] # start_urls = ['http://truyenqq.com/'] client = py...
3,034
949
# -*- coding:utf-8 -*- from django.shortcuts import get_object_or_404, render from django.views.generic import View from django.core.paginator import Paginator from article.models import Category, Post from article.utils import get_page_num_list class ArticleListView(View): """ 分类文章列表View """ def get...
1,902
716
li=[1,2,3] result=sum(li) print(result)
40
22
from card import * from .sjuan_card_stack import * @adt class SjuanAction: SKIP: Case ASK_FOR_CARDS: Case def __str__(self): return self.match( skip = lambda: "skip", ask_for_cards = lambda: "ask for cards" ) @adt class SjuanInsert: SJUAN...
852
295
import argparse import yaml import logging import os import sys import time from schema import Schema, SchemaError import requests from prometheus_client import CollectorRegistry, Gauge, push_to_gateway from apscheduler.schedulers.background import BlockingScheduler class Config(object): def __init__(self): ...
5,739
1,698
import json import os f = open('ntu_mods.json', "r") mod_json = json.loads(f.read()) filtered_dict = {} count = 0 for course in mod_json['COURSES']: if "CE" in course['COURSE']: filtered_dict = course count += 1 path = os.path.abspath("./courses/" + course['COURSE'] + ".json") with...
501
173
import config, userapp api = userapp.API(app_id=config.USERAPP_APP_ID, debug=True, throw_errors=False) user_result = api.user.login(login="epicrawbot", password="play_withBitz!")
180
66
import numpy as np import cv2 #import matplotlib.pyplot as plt from collections import deque import imutils from KCF_tracker import tracker import argparse import sys class find_person: def __init__ (self,a): self.direction = [] for track in a : self.direction.append(a[track...
338
98
"""VGG11/13/16/19 in Pytorch.""" import torch import torch.nn as nn cfg = { 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512,...
2,545
1,106
from typing import Dict class FuncDesc: def __init__(self, func_name:str, type_by_arg:Dict[str, str], output_ty:str): self.name = func_name self.output_ty = output_ty self.ordered_argname_type_pairs = sorted(list(type_by_arg.items()), ...
841
257
#!/usr/bin/python3 import requests import json def run(token, username, repository, collaborator): url = f"https://api.github.com/repos/{username}/{repository}/collaborators/{collaborator}" authorization = f"token {token}" headers = { "Accept": "application/vnd.github.v3+json", "Authoriza...
1,001
341
from files.datafile import DataFile import glob import os import sys def read_data(file_name): with open(file_name, 'rb') as file: data, index = DataFile.from_bytes(bytearray(file.read())) return data.get() def write_data(file_name, data): data_file = DataFile() data_file.set(type(data)...
1,281
448
from microbit import * from enum import * class PIR(object): """基本描述 人体红外检测, 运动检测 Args: RJ_pin (pin): 连接端口 """ def __init__(self, RJ_pin): if RJ_pin == J1: self.__pin = pin8 elif RJ_pin == J2: self.__pin = pin12 elif RJ_pin == J3: ...
845
338
import time from hive_gns.database.access import delete class Pruner: @classmethod def delete_old_ops(cls): sql = f""" DELETE FROM gns.ops WHERE created <= NOW() - INTERVAL '30 DAYS'; """ return delete(sql) @classmethod def run_pruner(cls): whi...
390
129
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and relate...
7,604
2,499
from django.db import models class Article(models.Model): article_id = models.AutoField(primary_key=True) article_heading = models.CharField(max_length=256) article_body = models.TextField()
206
65
# importing tkinter module that will handle display window and text import tkinter as tk #Create a class that will generate new tkinter window with message for a given text def Reminder(reminder_text): app_window = tk.Tk() app_window.title("Health Reminder") # The bell method will adds a bell sound app...
856
255
import numpy as np import torch import torch.nn as nn import torch.nn.init as init import os import torch.nn.functional as F from utils import * class Model(nn.Module): def __init__(self, model_dir=None, model_name=[]): super(Model, self).__init__() #self.DNet = torch.load(os.path.join(model_dir, m...
10,688
4,468
############################################################################### # The MIT License (MIT) # # Copyright (c) 2017 Justin Lovinger # # 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 Softwar...
18,655
5,901
import logging from django.apps import apps from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.http import Http404 logger = logging.getLogger(__name__) class LTIModel(models.Model): """Mixin for models that can be created through LTI. ...
2,921
846
# test128_row.py Test for device driver on 96 row display import machine from ssd1351 import SSD1351 as SSD # Initialise hardware def setup(): pdc = machine.Pin('X1', machine.Pin.OUT_PP, value=0) pcs = machine.Pin('X2', machine.Pin.OUT_PP, value=1) prst = machine.Pin('X3', machine.Pin.OUT_PP, value=1) ...
546
264
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Interpolate onto a volume # Parameters for debugging NPts = 1000000 math = vtk.vtkMath() math.RandomSeed(31415) # create pipeline # points = vtk.vtkBoundedPointSour...
2,202
827
from paver.easy import * import paver.doctools from paver.setuputils import setup setup( name='PyOptimizer', version='1.0', packages=['PyOptimizer'], url='https://github.com/alesgaco/PyOptimizer', license='MIT', author='Aldo Esteban Garces Correa', author_email='aegarcesc@unal.edu.co', d...
384
134
import nltk from nltk import word_tokenize import string from nltk.stem import WordNetLemmatizer from wordcloud import WordCloud, STOPWORDS #nltk.download('punkt') #nltk.download('averaged_perceptron_tagger') #nltk.download('wordnet') class generate: def __init__(self, text): self.text = text def...
3,381
1,093
#! /usr/bin/python # -*- coding:utf-8 -*- """ Author: AsherYang Email: ouyangfan1991@gmail.com Date: 2018/6/21 Desc: ffStore 微信小程序直营店在微信申请的测试 AppId, AppSecret """ APP_ID = 'wx72877ae8bdff79b0' APP_SECRET = '35c17c2b6f81e7b03735f17f546820bc'
248
160
# coding: utf-8 import re import os import unicodedata import math import six from django.utils.module_loading import import_string from filebrowser.settings import NORMALIZE_FILENAME, CONVERT_FILENAME def convert_filename(value): """ Convert Filename. """ if NORMALIZE_FILENAME: chunks = v...
1,037
339
#!/usr/bin/python3 # # This script is used for custom compilation scripts with selected # modules in order to achieve a selected enviroment for the running # code. This is done using the test.json file located in every test. # # The first argument is the name of the test enviroment, being the # folder name where test....
1,985
687
#!/usr/bin/python3 import os.path import argparse from src.app import main as app_main def run(): parser = argparse.ArgumentParser() # command line arguments parser.add_argument( "--input-path", help="Absolute path to input directory where .csv files reside", # nargs="+", ...
1,512
483
import os import json import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES from steembase import PrivateKey from appdirs import user_data_dir import logging log = logging.getLogger(__name__) appname = "piston" appauthor = "Fabian Schuh" walletFile = "wallet.dat" prefix = "STM" # prefix ...
8,310
2,468
#!/bin/env python # Demonstration of the imposition of a simple cartesian geometry on a set of # processes. In this case we generate a uniform 2-D grid in which each # element passes a value to its nearest neighbour to the right. from mpi4py import MPI import numpy as np import sys if __name__ == "__main__": # I...
1,710
509
import pandas as pd import sys # NOTE: Each list below must be divisible by last entry of prev list # (15 by 5, 30 by 15, 1D by 6H, etc.) _UNITS = [ ["1min"], ["5min"], ["15min"], ["30min"], ["1H"], ["4H", "6H"], ["1D"], ["3D", "1W", "1M"], ] _DATE_FORMAT = "%m/%d/%Y" _TIME_FORMAT = "%H...
2,300
797
#!/bin/python from deap import base from deap import creator from deap import tools from copy import deepcopy import random from .. import functions getPromoterFromMap = lambda x: [x[z] for z in list(x.keys())] def constructPhenotype(stratSettings, chrconf, Individue): Settings = {} GeneSize=2 R = lamb...
3,131
1,061
############################################################# ## ## ## Copyright (c) 2003-2017 by The University of Queensland ## ## Centre for Geoscience Computing ## ## http://earth.uq.edu.au/centre-geoscience-computing ## ## ...
1,124
284
from objects.modulebase import ModuleBase import discord from io import BytesIO from PIL import Image from PIL.ImageOps import mirror from utils.funcs import find_image class Module(ModuleBase): usage_doc = '{prefix}{aliases} [image]' short_doc = 'Makes a slap meme' long_doc = ( 'Flags:\n' ...
2,266
743
from unittest.mock import Mock from pyapp_ext.aiosmtplib import helpers class TestEmail: def test_init(self, monkeypatch): mock_factory = Mock() monkeypatch.setattr(helpers, "get_client", mock_factory) helpers.Email(name="foo") mock_factory.assert_called_with("foo")
308
103
"""Tests for the Bulb API with a light strip.""" from typing import AsyncGenerator import pytest from pywizlight import PilotBuilder, wizlight from pywizlight.bulblibrary import BulbClass, BulbType, Features, KelvinRange from pywizlight.tests.fake_bulb import startup_bulb @pytest.fixture() async def light_strip() -...
1,444
535
# -*- coding: utf-8 -*- #!/usr/bin/env python3 __author__ = 'Luka Opasic, MD' __email__ = 'opasic@evolbio.mpg.de' __version__ = '1.1.0' from argparse import ArgumentParser from operator import itemgetter from random import shuffle from scipy.sparse import lil_matrix from time import sleep, time from timeit import def...
47,068
13,803
def stimulus_create(type, wl, va, ratio): # STIMULUS_CREATE generates a 2D stimulus vector for phototaxis experiments of desired type and resolution # Inputs: # type - type of stimulus, e.g. 'bar'/'dog'/'square'/'log' (see below for full list) # wl - "width" or "wavelength" of pattern in degre...
8,973
3,314
#!/usr/bin/python3 """ file: app.py purpose: Holds the view for the Flask web application and handling of the database. """ from .gui_constants import GUI_CONSTANTS, DANGER, ENVIRONMENT, STATE import datetime from flask import Flask, request, session, g, redirect, url_for, abort, \ render_temp...
7,296
2,211
# -*- coding: UTF-8 -*- from django.http import HttpResponse, HttpResponseRedirect from datetime import datetime, date from apps.seguridad.decorators import login_required, credential_required from apps.seguridad.models import Usuario, Perfil from apps.titulos.models.TituloNacional import TituloNacional import csv fro...
945
349
# Stimulate OR bit operator using Perceptron neural function def ORBitwiseOperation(x1, x2, bias): weight = 1 if x1*weight + x2*weight + bias <= 0: return 0 return 1 # Bias = 0 and Weight = 1 print('ORBitwiseOperation: 0,0', ORBitwiseOperation(0, 0, 0)) print('ORBitwiseOperation: 0,1', ORBitwiseOp...
463
184
from __future__ import unicode_literals from raster.models import RasterLayer from django import forms from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.gis import admin from django.http import HttpResponseRedirect from django.shortcuts import render from .models import AggregationAre...
3,642
992
# -*- coding: utf-8 -*- """get_matches_api.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1QpfVmsmtCPV9dhTsq6pRW7l7bXjwzKzr Author: Aminu Habib Import Libraries """ import requests import json from prettytable import PrettyTable #import sqlite...
2,624
912
from yeahml.build.components.callbacks.objects.base import TrainCallback def print_mapper(cur_func): def _print_mapper(self, *args, **kwargs): print(f"{cur_func.__name__}: {self.monitor}") return _print_mapper class Printer(TrainCallback): def __init__(self, monitor="something", relation_key=No...
2,554
840
import numpy as np from unittest import TestCase from diffprivlib.accountant import BudgetAccountant from diffprivlib.tools.histograms import histogram2d from diffprivlib.utils import global_seed, PrivacyLeakWarning, BudgetError class TestHistogram2d(TestCase): def test_no_params(self): x = np.array([1, ...
3,043
1,378