id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9856992 | from flask import url_for
from flask.ext.wtf import Form
from wtforms.fields import (
StringField,
PasswordField,
BooleanField,
SubmitField,
TextAreaField,
DateField,
SelectMultipleField
)
from wtforms.fields.html5 import EmailField
from wtforms.validators import (
Length,
Email,
... |
9857000 | from conans import ConanFile, CMake
import os
class TinyreflTool(ConanFile):
name = 'tinyrefl-tool'
version = '0.4.1'
url = 'https://github.com/Manu343726/tinyrefl'
description = ' A work in progress minimal C++ static reflection API and codegen tool'
scm = {
'type': 'git',
'url': 'http... |
9857010 | import argparse
import os
import sys
import numpy as np
import soundfile
from mir_eval.util import midi_to_hz
from onsets_and_frames import *
def load_and_process_audio(flac_path, sequence_length, device):
random = np.random.RandomState(seed=42)
audio, sr = soundfile.read(flac_path, dtype='int16')
ass... |
9857038 | from mcidle.networking.packets.packet import Packet
from mcidle.networking.types import String, VarIntPrefixedByteArray, VarInt, Integer, VarIntArray, \
Long, Byte, Double, Float, Boolean, UUID, Short, UnsignedByte
"""
Note: not using an OrderedDict for `definition` will break
in anything older than Python 3.7.1... |
9857048 | import glob
import os
from frelatage.dictionary.dictionary import Dictionary
def load_dictionary(dictionary_folder: str) -> bool:
"""
Load all the dictionaries from the dictionary folder
"""
dictionary = Dictionary()
dictionaries = []
if os.path.isdir(dictionary_folder):
# find all ".d... |
9857056 | algorithm='ddpg'
env_class='UnityMLVectorMultiAgentNew'
model_class='LowDim2x'
environment = {
'name': 'compiled_unity_environments/Crawler_Linux_v5/CrawlerLinux.x86_64',
}
model = {
'state_size': 129,
'action_size': 20,
'fc1_units': 400,
'fc2_units': 300
}
agent = {
'action_size': 20,
'u... |
9857090 | import unittest
import utils
from grammar import Grammar
class SplitByCommasTest(unittest.TestCase):
def test_simple(self):
self.assertEqual(['A', 'B', 'C'], utils.split_by('A, B, C', ','))
def test_without_space(self):
self.assertEqual(['A', 'B', 'C'], utils.split_by('A,B,C', ','))
def... |
9857114 | import json
from airiam.terraform.entity_terraformers.BaseEntityTransformer import BaseEntityTransformer
class IAMPolicyDocumentTransformer(BaseEntityTransformer):
def __init__(self, entity_json: dict, policy_name, principal_name=None):
policy_document_name = f"{policy_name}_document"
if principa... |
9857200 | import os
def initialize():
if os.name == 'nt':
from clipmanager.hotkey.win32 import GlobalHotkeyManagerWin
return GlobalHotkeyManagerWin()
elif os.name == 'posix':
from clipmanager.hotkey.x11 import GlobalHotkeyManagerX11
return GlobalHotkeyManagerX11()
|
9857222 | from jsf import JSF
from fastapi import FastAPI
app = FastAPI(docs_url="/")
generator = JSF.from_json("custom.json")
@app.get("/generate", response_model=generator.pydantic())
def read_root():
return generator.generate()
|
9857227 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.us_classified_docs import us_classified_docs
def test_us_classified_docs():
"""Test module us_classified_docs.py by downloading
us_classified... |
9857234 | import sklearn.discriminant_analysis
from autotabular.pipeline.components.classification.lda import LDA
from .test_base import BaseClassificationComponentTest
class LDAComponentTest(BaseClassificationComponentTest):
__test__ = True
res = dict()
res['default_iris'] = 1.0
res['default_iris_iterative'... |
9857241 | import piquant.statistics as statistics
import piquant.tpms as t
import numpy as np
import pandas as pd
import scipy.stats as scistats
import test_tpms
def _get_test_tpms():
tpms = pd.DataFrame.from_dict({
t.REAL_TPM: test_tpms.REAL_TPMS_VALS,
t.CALCULATED_TPM: test_tpms.CALC_TPMS_VALS,
te... |
9857247 | import spacy
# Defina o componente customizado
def length_component(doc):
# Calcule o tamanho do doc
doc_length = len(doc)
print(f"This document is {doc_length} tokens long.")
# Retorne o doc
return doc
# Carregue o modelo pequeno do idioma inglês
nlp = spacy.load("en_core_web_sm")
# Adicione o ... |
9857254 | import asyncio
import csv
from collections import deque
from datetime import datetime
from typing import List, Deque, AsyncGenerator, Any
from aat.config import EventType, InstrumentType, Side, TradingType
from aat.core import ExchangeType, Event, Instrument, Trade, Order
from aat.exchange import Exchange
class CSV(E... |
9857270 | import time
import dgl
import torch
from .. import utils
@utils.benchmark('time')
@utils.parametrize('batch_size', [4, 256, 1024])
@utils.parametrize('feat_size', [16, 128, 512])
@utils.parametrize('readout_op', ['sum', 'max', 'min', 'mean'])
@utils.parametrize('type', ['edge', 'node'])
def track_time(batch_size, fe... |
9857281 | from threading import Thread
from Queue import Queue
import logging
def serialize_soap(entry):
d = {}
for k, v in entry:
if isinstance(v, bool):
d[k] = v
elif isinstance(v, int):
d[k] = v
elif isinstance(v, float):
d[k] = v
elif isinstance(v, ... |
9857296 | import autograd.numpy as np
from pymop.problem import Problem
class Ackley(Problem):
def __init__(self, n_var=10, c1=20, c2=.2, c3=2 * np.pi):
super().__init__(n_var=n_var, n_obj=1, n_constr=0, xl=-32, xu=32, type_var=np.double)
self.c1 = c1
self.c2 = c2
self.c3 = c3
def _ev... |
9857327 | from insights.parsers import ros_config
from insights.tests import context_wrap
import doctest
ROS_CONFIG_INPUT = """
log mandatory on default {
mem.util.used
mem.physmem
kernel.all.cpu.user
kernel.all.cpu.sys
kernel.all.cpu.nice
kernel.all.cpu.steal
kernel.all.cpu.idle
kernel.all.cpu.... |
9857405 | from pyglet.gl import *
class DrawEnv(object):
'''Sets up drawing environment.
My have either or both of a "before" and "after" method.
'''
pass
class DrawBlended(DrawEnv):
'''Sets up texture env for an alpha-blended draw.
'''
def before(self):
glPushAttrib(GL_ENABLE_BIT | GL_CO... |
9857410 | from __future__ import unicode_literals
from django.test import override_settings
from .cases import StaticFilesTestCase
class TestTemplateTag(StaticFilesTestCase):
def test_template_tag(self):
self.assertStaticRenders("does/not/exist.png", "/static/does/not/exist.png")
self.assertStaticRenders... |
9857411 | import os
import random
import click
import tensorflow as tf
from noisemaker.util import load, save, shape_from_file
import noisemaker.cli as cli
import noisemaker.effects as effects
import noisemaker.generators as generators
import noisemaker.value as value
@click.group(help="""
This script is deprecated.... |
9857424 | import os
import mock
import pytest
import yaml
import paasta_tools.config_utils as config_utils
from paasta_tools.utils import AUTO_SOACONFIG_SUBDIR
@pytest.fixture(autouse=True)
def mock_subprocess():
with mock.patch(
"paasta_tools.config_utils.subprocess", autospec=True
) as mock_subprocess:
... |
9857426 | import os
import glob
import obspy
import scipy
import time
import pyasdf
import numpy as np
from numba import jit
from scipy import signal
import matplotlib.pyplot as plt
from obspy.core.util.base import _get_function_from_entry_point
'''
check efficiency of detrend, demean
'''
def detrend(data):
'''
remove ... |
9857442 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import gym
import gym.spaces
import numpy as np
class Norm... |
9857454 | import argparse
import copy
import json
import logging
import os
import numpy as np
import torch
import transformers
from data import get_data
from evaluate import EVAL_FUNC_MAP
from model import MODEL_CLASS_MAP
from tqdm import tqdm
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(messag... |
9857476 | from html.parser import HTMLParser
class SAMLPostFormParser(HTMLParser):
"""
Parses the SAML Post binding form page for the SAMLRequest value.
"""
saml_request_value = None
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
if tag != "input" or attrs_dict.get("name"... |
9857544 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import... |
9857549 | r"""
This module contains occupation components used by the Leauthaud11 composite model.
"""
import numpy as np
import math
from scipy.special import erf
import warnings
from .occupation_model_template import OccupationComponent
from .. import model_defaults
from ..smhm_models import Behroozi10SmHm
from ..assembias_... |
9857598 | import seldom
from seldom import testdata
class FileDataTest(seldom.TestCase):
"""
Randomly generate test data
"""
def test_testdata(self):
"""
used testdata test
"""
self.open("https://www.runoob.com/try/try.php?filename=tryhtml_input")
self.switch_to_frame(id... |
9857625 | from .simple_filter import SimpleFilter
from .greedy_filter import GreedyFilter
from .correlated_filter import CorrelatedFilter
from .bayes_search_cv import BayesSearchCV
__all__ = ['SimpleFilter', 'GreedyFilter', 'CorrelatedFilter', 'BayesSearchCV']
|
9857630 | import numpy as np
from scipy import spatial
from ..configure.config import cfg
def get_weight(dist, r, method="barnes"):
"""
barnes权重函数,给定距离dist和影响半径r,返回权重值
:param dist: 数据点距离插值点的距离
:param r: 有效影响半径
:param method 插值方法
:return: 该点在插值上的权重
"""
if method == "barnes":
weight = np.ex... |
9857699 | from tensorflow.python.framework import ops
class GraphKeys(ops.GraphKeys):
# For rank service
RANK_SERVICE_FG_CONF = '__rank_service_fg_conf'
RANK_SERVICE_INPUT = '__rank_service_input'
RANK_SERVICE_OUTPUT = '__rank_service_output'
RANK_SERVICE_EMBEDDING = '__rank_service_embedding'
RANK_SERVICE_INPUT_SR... |
9857718 | TLDS = {'aaa': {'aaa': False},
'aarp': {'aarp': False},
'abarth': {'abarth': False},
'abb': {'abb': False},
'abbott': {'abbott': False},
'abbvie': {'abbvie': False},
'abc': {'abc': False},
'able': {'able': False},
'abogado': {'abogado': False},
'abudhabi': {'abudhabi': False},
'ac': {'ac': False,
'com... |
9857734 | from __future__ import print_function
import socket
import sys
import json
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def trigger_event(message):
if not len(message):
return
event = json.loads(message)
step = event['step']
app = event['app']
eprint('Rece... |
9857774 | import os
import time
import numpy
import pygame
from common.drone import Drone
from pathplan.pathplanning import save_path_plan
class PyGameScreen:
def __init__(self, tello):
self.controls_keypress, self.controls_keyrelease = get_keys_control(tello)
self.screen = self.init_pygame_screen()
self.listeners = ... |
9857778 | from unittest2 import TestCase
from whitepages.business import WhitePagesBusiness
class TestWhitePagesBusiness(TestCase):
def setUp(self):
self.basic_input = {
"results": [
{
"id": {
"key": "Business.b5b36dfd-dfb3-4700-9cdc-fc736fa7b... |
9857807 | from chitra.data_processing.default.nlp import DefaultTextProcessor
from chitra.data_processing.default.vision import DefaultVisionProcessor
|
9857827 | class NotifyDataErrorValidationRule(ValidationRule):
""" NotifyDataErrorValidationRule() """
def Validate(self,value,cultureInfo,owner=None):
""" Validate(self: NotifyDataErrorValidationRule,value: object,cultureInfo: CultureInfo) -> ValidationResult """
pass
|
9857855 | import math
import torch
from torch import nn
import numpy as np
from tkbc.models import TComplEx
from transformers import RobertaModel
from transformers import BertModel
from transformers import DistilBertModel
# from kb.include_all import ModelArchiveFromParams
# from kb.knowbert_utils import KnowBertBatchifier
# fro... |
9857860 | from django.apps import AppConfig
class LedgerConfig(AppConfig):
name = 'ledger'
def ready(self):
super(LedgerConfig, self).ready()
import ledger.signals |
9857892 | import asyncio
import cozmo
import cv2
import getopt
import logging
import numpy as np
import sys
import threading
import time
import datetime
from cozmo.util import degrees, distance_mm, speed_mmps
from matplotlib import pyplot as plt
""" A simple line follow logic, which guides Cozmo along a line.
For best results... |
9857903 | import logging
import os
import sys
_root_logger = logging.getLogger()
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.WARNING)
# if root logger has handlers, propagate messages up and let root logger process them
if not _root_logger.hasHandlers():
_logger.addHandler(logging.StreamHandler(sys.stdo... |
9858029 | import speechpy
import scipy.io.wavfile as wav
import numpy as np
def extract_features(signal, fs):
frames = speechpy.processing.stack_frames(signal, sampling_frequency=fs, frame_length=0.020, frame_stride=0.01, filter=lambda x: np.ones((x,)),zero_padding=True)
power_spectrum = speechpy.processing.power_spectr... |
9858041 | import torch.nn as nn
from blocks import SetAttentionBlock
from blocks import InducedSetAttentionBlock
from blocks import PoolingMultiheadAttention
class SetTransformer(nn.Module):
def __init__(self, in_dimension, out_dimension):
"""
Arguments:
in_dimension: an integer.
ou... |
9858053 | from .add_tags import AddTagsBulkAction
from .add_to_collection import AddToCollectionBulkAction
from .delete import DeleteBulkAction
__all__ = ['AddToCollectionBulkAction', 'AddTagsBulkAction', 'DeleteBulkAction']
|
9858062 | from EventManager.Models.RobotRunnerEvents import RobotRunnerEvents
from EventManager.EventSubscriptionController import EventSubscriptionController
from ConfigValidator.Config.Models.RunTableModel import RunTableModel
from ConfigValidator.Config.Models.FactorModel import FactorModel
from ConfigValidator.Config.Models.... |
9858080 | import os.path as osp
from torch.optim import Adam
import unittest
from pd_mesh_net.utils import create_model, create_optimizer
class TestCreateOptimizer(unittest.TestCase):
def test_create_adam_optimizer(self):
# Create a model.
model_name = 'mesh_classifier'
network_params = {
... |
9858103 | import cProfile
import cellyzer.io as io
call_file_path = "../../demo/demo_datasets/long_data/calls_.csv"
msg_file_path = "../../demo/demo_datasets/long_data/messages_.csv"
cell_file_path = "../../demo/demo_datasets/long_data/antennas.csv"
def test_read_call():
io.read_call(call_file_path)
def test_read_msg():... |
9858136 | import FWCore.ParameterSet.Config as cms
# Default Geant4e propagator setup, uses Muons as particle hypotesis
# ParticleName can be any particle described in the Geant4 documentation
# http://geant4.web.cern.ch/geant4/UserDocumentation/UsersGuides/ForApplicationDeveloper/html/ch05s03.html
# The chargen ( e.g. mu+ or m... |
9858187 | from canvas.tests.tests_helpers import (CanvasTestCase, create_content, create_user, create_group, create_comment,
create_staff)
from services import Services, override_service
class TestFeed(CanvasTestCase):
def test_page_loads(self):
self.assertStatus(200, '/feed'... |
9858203 | import os
import glob
import shutil
import pytest
from tests import helpers
from scrub.utils import do_clean
from scrub.utils import scrub_utilities
@pytest.mark.parametrize('operation', ['normal', 'tool_error', 'upload_error', 'invalid_config', 'custom_config'])
def test_collaborator(operation):
# Import the mod... |
9858209 | import numpy as np
def adjust_box_sort(box):
start = -1
_box = list(np.array(box).reshape(-1,2))
min_x = min(box[0::2])
min_y = min(box[1::2])
_box.sort(key=lambda x:(x[0]-min_x)**2+(x[1]-min_y)**2)
start_point = list(_box[0])
for i in range(0,8,2):
x,y = box[i],box[i+1]
if [... |
9858262 | import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
import os
from fpdf import FPDF
import imageio
class MIP_Generator :
"""a class to generate MIP"""
def __init__(self, numpy_array:np.ndarray):
"""constructor
Args:
numpy_array (np.ndarray): [3D np.ndarray ... |
9858280 | import torch
import torch.nn as nn
def grad_false(m):
for param in m.parameters():
param.requires_grad = False
class BaseNetwork(nn.Module):
_n = None
def save(self, path):
torch.save(self.state_dict(), path)
def load(self, path):
self.load_state_dict(torch.load(path))
... |
9858326 | import torch
import torch.nn as nn
import torch.nn.functional as F
class CenConv2d(nn.Module):
"""Conv2d layer with Weight Centralization.
The args is exactly same as torch.nn.Conv2d. It's suggested to set bias=False when
using CenConv2d with MABN.
"""
def __init__(self, in_planes, out_planes, ke... |
9858343 | from plivo.utils.validators import *
from plivo.xml import PlivoXMLElement, map_type
class WaitElement(PlivoXMLElement):
_name = 'Wait'
_nestable = []
@property
def length(self):
return self.__length
@length.setter
def length(self, value):
self.__length = int(value) if value ... |
9858363 | from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'travis_cron.views.home', name='home'),
... |
9858366 | import os
from glob import glob
import torch
from torch.utils.data.dataset import Dataset
from torchvision.datasets.folder import default_loader
from PIL import Image
import numpy as np
def find_classes(classes_file):
# read classes file, separating out image IDs and class names
image_ids = []
targets =... |
9858394 | from ..const import INDENT, Emoji
from ..file_path import PypjFilePath
from ..resource import get_my_resource
from ..setting import PypjSetting
from .task import Task
class PreCommit(Task):
def __init__(self, setting: PypjSetting, path: PypjFilePath) -> None:
name = "Pre-commit"
super().__init__(n... |
9858402 | from math import log10, log
import re
def do_search(db, q, object_type, limit):
""" Search for objects (profiles, tables, topics) matching query q.
Return a list, because it's easier to work with than a SQLAlchemy
ResultProxy object (notably, the latter does not support indexing).
"""
if object_t... |
9858421 | from bottle import *
import os
@get('/ping_test')
def ping_test():
return {"message": "pong"}
@get('/env_test')
def env_test():
return {"message": os.environ['KEY']}
@get('/mount_test')
def mount_test():
with open("/data/data.txt", "rt") as in_file:
text = in_file.read()
return {"message"... |
9858439 | import torch
import torch.nn as nn
from . import constants
from . import evaluation
from .util import utilities as util_
def compute_graph_score(pred_mask, gt_mask,
obj_F_weight=0.8, obj_det_weight=0.2):
"""Compute score of graph compared with GT mask.
Score with Overlap F measu... |
9858472 | import datetime
import sys
import uuid
from peewee import Model
from flask_peewee.utils import get_dictionary_from_model
from flask_peewee.utils import get_model_from_dictionary
class Serializer(object):
date_format = '%Y-%m-%d'
time_format = '%H:%M:%S'
datetime_format = ' '.join([date_format, time_forma... |
9858487 | import simtk.openmm as mm
import simtk.unit as unit
from openmmplumed import PlumedForce
import numpy as np
import unittest
class TestTorchForce(unittest.TestCase):
def testForce(self):
# Create a System that applies a force based on the distance between two atoms.
numParticles = 4
syste... |
9858490 | import komand
from .schema import AddWatchlistInput, AddWatchlistOutput
# Custom imports below
from cbapi.errors import ServerError
from cbapi.response.models import Watchlist
class AddWatchlist(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="add_watchlist",
... |
9858521 | import numpy as np
class cov(object):
def __init__(self, params=None):
self.params = params
if self.params is None:
self.params = np.log(1)
self.nparams = 1
self.sigma2, self.prec = self._trans_params(params)
def get_cov(self, N, params=None):
''' compute t... |
9858642 | from __future__ import print_function
class EditDistance:
def __init__(self):
self.__prepare__()
def __prepare__(self, N = 0, M = 0):
self.dp = [[-1 for y in range(0,M)] for x in range(0,N)]
def __solveDP(self, x, y):
if (x==-1):
return y+1
elif (y==-1):
... |
9858643 | from django.core.management.base import LabelCommand
from django.template import loader
from django.template import TemplateDoesNotExist
import sys
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
# work arround htt... |
9858668 | from pca.exceptions import (
ConfigError,
ErrorCatalog,
)
class DIErrors(ErrorCatalog):
DEFINITION_NOT_FOUND = ConfigError(
hint=(
"A dependency definition for DI was tried to be injected, but it has not been found."
)
)
ALREADY_REGISTERED = ConfigError(hint="This conte... |
9858673 | import streamlit as st
VIDEO_URL = "https://static.streamlit.io/examples/star.mp4"
st.video(VIDEO_URL)
st.write(
"""
#### Video credit:
Creator: User _fxxu_ from _Pixabay_.
License: Free for commercial use. No attribution required.
https://pixabay.com/en/service/license/
URL:
https://p... |
9858714 | import pytest
import trello
from todo.connection import TrelloConnection
from todo.configuration import Configuration
TEST_LIST_INBOX = 'gtd.py__INBOX'
@pytest.fixture
def config():
return Configuration.from_file()
@pytest.fixture
def test_conn(config):
if config.test_board is None:
pytest.fail(
... |
9858729 | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag.annotation import Type
from ztag.annotation import Manufacturer
from ztag import protocols
import ztag.test
class FtpOverlandStorage(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
... |
9858746 | import json
import re
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel
from ikea_api import Constants
from ikea_api.wrappers import types
from ikea_api.wrappers._parsers.item_base import (
ItemCode,
ItemType,
get_is_combination_from_item_type,
)
__all__ = ["main"]
clas... |
9858749 | import json
import os
import re
from collections import Counter
from copy import deepcopy
from transition_amr_parser.amr import AMR
"""
AMRStateMachine applies operations in a transition-based AMR parser, but combined with a pointer for arcs.
It maintains a cursor on the token sequence and moves from left to right an... |
9858782 | import nltk
import pandas as pd
import re
import sys
import os
import logging
import urllib.request
from nltk import tokenize
from .configs import *
from azureml.logging import get_azureml_logger
def download_file_from_blob(filename):
logger = logging.getLogger(__name__)
# Define the path of the shared fol... |
9858790 | def _aspect_impl(target, ctx):
print(ctx.rule.kind)
return []
print_aspect = aspect(
implementation = _aspect_impl,
attr_aspects = [],
) |
9858814 | from pbge.plots import Plot
import game
import gears
import pbge
import pygame
import random
from game import teams, ghdialogue
from game.content import gharchitecture, ghterrain, ghwaypoints, plotutility
from pbge.dialogue import Offer, ContextTag, Reply
from game.ghdialogue import context
from game.content.ghcutscene... |
9858837 | from machine import I2C
import HTS221
from pyb import Timer
i2c = I2C(1)
hts = HTS221.HTS221(i2c)
def tim_irq(t):
print(hts.get_irq())
tim = Timer(1, freq = 1)
tim.callback(tim_irq)
|
9858867 | import pytest
import salt.utils.schedule
from tests.support.mock import MagicMock
try:
import pytz.exceptions
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
def test_correct_tz_offset():
kwargs = {
"opts": {},
"functions": {"timezone.get_offset": lambda: "0200"},
"clean... |
9858879 | from django.urls import path
from django.views.generic import TemplateView
from .views.template import HomeView, SnippetCreateView, SnippetView, TicketCreateView, TicketView, TicketSearchResultsView
from .views.api import SnippetCreateAPIView, SnippetAPIView
from .constants import REDOC_DESCRIPTION
from rest_framewor... |
9858906 | from html2image import Html2Image
# This file contains examples of how to use the
# load_str, load_file, screenshot_url and screenshot_loaded_file methods.
# minimal html : quite unconventional but browsers can read it anyway
my_html_string = """\
<link rel="stylesheet" href="red_background.css">
<h1> An interesting ... |
9858918 | import pytest
from app.models import EmailBranding, BRANDING_ORG
from tests.app.db import create_email_branding
def test_get_email_branding_options(admin_request, notify_db, notify_db_session):
email_branding1 = EmailBranding(colour='#FFFFFF', logo='/path/image.png', name='Org1')
email_branding2 = EmailBrand... |
9858949 | from bokeh.io import save
from bokeh.models import Circle, LinearAxis, Plot, Range1d
aliases = dict(a="above", b="below", l="left", r="right")
def make_figure(axes):
xdr = Range1d(start=-1, end=1)
ydr = Range1d(start=-1, end=1)
plot = Plot(title=None, x_range=xdr, y_range=ydr, width=200, height=200, tool... |
9858951 | class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
m, n, d = len(grid), len(grid[0]), 1
piled = collections.defaultdict(set)
dist = collections.defaultdict(int)
bfs = [(i, j, i, j) for i in range(m) for j in range(n) if grid[i][j] == 1]
total, res = len... |
9858954 | from Queue import Queue
from abc import ABCMeta, abstractmethod
from functools import partial
from threading import Thread
import unittest
import os
import uuid
import sys
from bd2k.util.fnmatch import fnmatch
try:
# Note that subprocess isn't thread-safe so subprocess is actually required. I'm just putting
#... |
9858982 | import os
MAX_SEND_RCV_SIZE=1024*32
def sendall_str(conn, s):
if len(s) > MAX_SEND_RCV_SIZE:
cut = "\n... [TRUNCATED]"
sz = MAX_SEND_RCV_SIZE-len(cut)-2 # -2 to be on the safe side
s = "%s%s" % (s[:sz], cut)
conn.sendall(bytes(s, "UTF-8"))
def my_log(msg):
from datetime import da... |
9859005 | import pagexml
import torch.nn as nn
class RoISorter(nn.Module):
# Module to sort detected Regions of Interest by reading order (left-right,top-bottom)
def __init__(self):
super(RoISorter,self).__init__()
def forward(self,rois):
pxml = pagexml.PageXML()
pxml.newXml('retinanet_... |
9859013 | import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from helper import *
# FEATURE LOSS NETWORK
def lossnet(input, keep_prob,n_layers=14, training=True, reuse=False, norm_type="SBN",
ksz=3, base_channels=32, blk_channels=5):
layers = []
if norm_type == "NM": # ADA... |
9859056 | import copy
import pytest
from pybaseball.cache import cache_record
def test_bad_cache_record() -> None:
with pytest.raises(ValueError):
cache_record.CacheRecord()
def test_supports_self_true() -> None:
func_data = {'func': '_test_func', 'args': (1, 2, 3), 'kwargs': {'named_param': True}}
recor... |
9859082 | def test_create_fetch_entity_with_list(ds_entity):
entity_key = "test_entity"
list_values = [1, 2, 3]
dict_values = {"test": "test"}
int_value = 3
test_entity = ds_entity(entity_key, list_field=list_values, dict_field=dict_values, int_field=int_value)
test_entity.save()
fetched_test_entity =... |
9859085 | import tensorflow as tf
class vggM:
def __init__(self):
self.learningRates = {}
def extractFeature(self, inputs):
with tf.variable_scope('VGGM') as scope:
scope.reuse_variables()
with tf.variable_scope('layer1'):
weights = tf.get_variable("weights")
... |
9859090 | import FWCore.ParameterSet.Config as cms
# AlCaPhiSymRecHits producer
alCaPhiSymRecHits = cms.EDProducer("AlCaPhiSymRecHitsProducer",
endcapHitCollection = cms.string('EcalRecHitsEE'),
eCut_barrel = cms.double(0.15),
ecalRecHitsProducer = cms.string('ecalRecHit'),
eCut_endcap = cms.double(0.75),
Ve... |
9859113 | from pylmcp import Object
from pylmcp.util import Buffer
import json
class Message(object):
def __init__(self,
obj: Object,
source_entity_id: int,
source_service_id: int,
source_group: str = '',
content_type: str = 'lmcp',
... |
9859119 | from pysbr.queries.query import Query
class LeagueMarkets(Query):
"""Get the betting markets available for a particular league.
Only market ids are returned by the query, without market names. For some leagues,
this query returns many more market ids than the markets found on SBR.
Args:
leag... |
9859131 | import ticdat.utils as utils
from ticdat.utils import verify, gurobi_env
try:
import docplex.mp.model as cplex
except Exception as e:
cplex = "docplex"
try:
import gurobipy as gurobi
except Exception as e:
gurobi = "gurobipy"
try:
import xpress
except:
xpress = "xpress"
class Model(object):
... |
9859139 | import unittest
from .mixins import BallotAPITestMixin
import ballotapi.cli
class CommandlineTestCase(BallotAPITestMixin, unittest.TestCase):
def setUp(self):
""" Patch stdout and stderr to capture output """
self._capture_output()
def tearDown(self):
""" Revert stdout and stderr pat... |
9859199 | from cointk.backtest import backtest
from cointk.strategies import NaiveStrategy
import random
random.seed(1)
strategy = NaiveStrategy(n_prices=1000, threshold=0.8)
backtest(strategy)
|
9859291 | from codewatch.assertion import assertion
def file_filter(_file_name):
return False
@assertion()
def error_assertion(_stats):
# throw an exception
raise KeyError(0)
|
9859295 | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class IsisLevel1LANHelloPDU(Base):
__slots__ = ()
_SDM_NAME = 'isisLevel1LANHelloPDU'
_SDM_ATT_MAP = {
'CommonHeaderIntradomainRoutingProtocolDiscriminator': 'isisLevel1LANHelloPDU.isisHeader.commonHeader.intradomainRo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.