id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11421506 | import torch
import torch.nn as nn
import pytorch3d.ops as ops
from .operations import gather_points
from .geo_operations import furthest_point_sample
from typing import List
class SharedMLP(nn.Sequential):
def __init__(self, args: List[int], activation: str = None, normalization: str = None, **kwargs):
s... |
11421508 | import sqlite3
import csv
import pickle
import numpy as np
import sys
sys.path.append("../")
from Sentence_Encoder.meta_query_encoder import encode
import tensorflow.compat.v1 as tf
import tensorflow_text
import tensorflow_hub as hub
tf.disable_eager_execution()
sess = tf.InteractiveSession(graph=tf.Graph())
ConvRT_m... |
11421509 | from .bulletin import Bulletin
import datetime
class Maharashtra(Bulletin):
def __init__(self, basedir):
statename = 'MH'
super().__init__(basedir, statename)
self.bulletin_url = 'https://arogya.maharashtra.gov.in/pdf/ncovidepressnote{}{:02d}.pdf'
self.startdate = datetime.date... |
11421513 | import ipywidgets as widgets
from traitlets import Unicode, List, Dict
import os
import typing
import itertools
try:
from IPython.core.display import display, Javascript
except:
raise Exception("This module must be run in IPython.")
DIRECTORY = os.path.abspath(os.path.dirname(__file__))
# import logging
# lo... |
11421543 | from torch.optim.lr_scheduler import _LRScheduler
class NoamScheduler(_LRScheduler):
# from https://github.com/tugstugi/pytorch-saltnet/blob/master/utils/lr_scheduler.py
def __init__(self, optimizer, warmup_steps):
self.warmup_steps = warmup_steps
super().__init__(optimizer)
def get_lr(se... |
11421546 | import torch
from . import Reducer
import torchdrift.utils
class PCAReducer(Reducer):
"""Reduce dimensions using PCA.
This nn.Modue subclass reduces the dimensions of the inputs
specified by `n_components`.
The input is a 2-dimensional `Tensor` of size `batch` x `features`,
the output is a `Tens... |
11421547 | from django.template import Context, Template
from django.test import TestCase
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django_imgix.templatetags._version import __version__
def render_template(string, context=None):
context = context or {}
context ... |
11421548 | from PyQt5.QtWidgets import (
QApplication,
QWidget,
QHBoxLayout,
QVBoxLayout,
QDesktopWidget,
QPushButton,
QLabel,
QTabWidget,
QMenu, QAction, QTextEdit, QFileDialog, QListWidget, QListWidgetItem, QCheckBox)
from PyQt5.QtGui import QPixmap, QCursor
from PyQt5.QtCore import QSize, QT... |
11421582 | import pytest
from lcs import Perception
from lcs.agents.racs import Configuration, Effect
from lcs.representations import UBR
from lcs.representations.RealValueEncoder import RealValueEncoder
class TestEffect:
@pytest.fixture
def cfg(self):
return Configuration(classifier_length=2,
... |
11421641 | class Tab(object): pass
class ChatTab(Tab): pass
class PrivateTab(ChatTab): pass
class MucTab(ChatTab): pass
class ConversationTab(ChatTab): pass
class RosterInfoTab(Tab): pass
class XMLTab(Tab): pass
class DynamicConversationTab(Tab): pass
class StaticConversationTab(Tab): pass
class GapTab(Tab): pass
|
11421650 | from yui.types.slack.attachment import Attachment
from yui.types.slack.attachment import Field
def test_field_class():
title = 'Test title for pytest'
value = '123'
field = Field(title=title, value=value, short=True)
assert field.title == title
assert field.value == value
assert field.short
... |
11421652 | import FWCore.ParameterSet.Config as cms
siStripDetInfoFileWriter = cms.EDAnalyzer("SiStripDetInfoFileWriter",
FilePath = cms.untracked.string('myfile.txt')
)
|
11421694 | from norminette.rules import Rule
from norminette.scope import GlobalScope, ControlStructure
class CheckBlockStart(Rule):
def __init__(self):
super().__init__()
self.depends_on = ["IsBlockStart"]
def run(self, context):
"""
Braces signal that the control structure, function, o... |
11421699 | import os
import pickle
import random
import numpy as np
import torch
from rdkit import Chem
from rdkit.Chem.rdchem import Mol
from torch.utils.data import Dataset
from torch_geometric.utils import to_dense_adj
from tqdm import tqdm
from datasets.utils import rdmol_to_dict, dict_to_dgl_graph
from utils import chem as... |
11421719 | import os,time,sys
""" Add the higher level directory to PYTHONPATH to be able to access the models """
sys.path.append('../')
""" Change this to modify the loadDataset function """
from load import loadDataset
"""
This will contain a hashmap where the
parameters correspond to the default ones modified
by any comm... |
11421727 | from django.conf import settings
from django.core.management import BaseCommand
from desecapi.exceptions import PDNSException
from desecapi.pdns import _pdns_delete, _pdns_get, _pdns_post, NSLORD, NSMASTER, pdns_id, construct_catalog_rrset
class Command(BaseCommand):
# https://tools.ietf.org/html/draft-muks-dnso... |
11421789 | from enum import IntEnum
class Facility(IntEnum):
"""
Complete list of all MSFT Band's facilities
"""
Invalid = 0
ReservedBase = 1
ReservedEnd = 31
DriverDma = 32
DriverBtle = 33
DriverPdb = 34
DriverI2c = 35
DriverAdc = 36
DriverGpio = 37
DriverDac = 38
DriverA... |
11421793 | from pythonnobrasil import config
from pythonnobrasil.cal import TomlCalendar
def test_toml_calendar():
calendar = TomlCalendar(config.CONFERENCIAS_PATH)
assert calendar
assert calendar.events
|
11421832 | import json
import events
from jsonschema import ValidationError
from pytest_mock import mocker
import time
import itertools
import metricpublisher.logger_handler
import metricpublisher.publisher_handler
import metricpublisher.schema
CONVERT_SECONDS_TO_MILLIS_FACTOR = 1000
def test_standard_valid_input():
"""Tes... |
11421893 | import FWCore.ParameterSet.Config as cms
pclMetadataWriter = cms.EDAnalyzer("PCLMetadataWriter",
readFromDB = cms.bool(True),
recordsToMap = cms.VPSet()
)
|
11421944 | from aim.cli.upgrade._legacy_repo.proto.base_pb2 import BaseRecord
from aim.cli.upgrade._legacy_repo.proto.metric_pb2 import MetricRecord
def deserialize_pb_object(data) -> BaseRecord:
base_pb = BaseRecord()
base_pb.ParseFromString(data)
return base_pb
def deserialize_pb(data):
base_pb = deserialize... |
11421952 | from jwcrypto import jwk
##
# Engine keys only work with the openssl backend
##
from cryptography.hazmat.backends.openssl import rsa
from cryptography.hazmat.backends.openssl import backend
class EngineJWK(jwk.JWK):
def _get_private_key(self, arg=None):
return self._engine_priv
def _get_public_key(sel... |
11421958 | import numpy as np
class Graph():
def __init__(self, max_hop=1, dilation=1):
self.max_hop = max_hop
self.dilation = dilation
# get edges
self.num_node, self.edge, self.center = self._get_edge()
# get adjacency matrix
self.hop_dis = self._get_ho... |
11421977 | from ..abstract import ErdReadOnlyConverter
from ..primitives import *
from gehomesdk.erd.values.fridge import FridgeIceBucketStatus, ErdFullNotFull
class FridgeIceBucketStatusConverter(ErdReadOnlyConverter[FridgeIceBucketStatus]):
def erd_decode(self, value: str) -> FridgeIceBucketStatus:
"""Decode Ice bu... |
11422050 | from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext, Row
from pyspark.sql.types import *
def parsePoint(l):
return [float(x) for x in l.split(';')]
if __name__ == '__main__':
conf = SparkConf().setAppName("SparkSQL")
sc = SparkContext(conf=conf)
sqlCtx = SQLContext(sc)
red_win... |
11422081 | from requests import HTTPError
class ParamRequired(HTTPError):
"""A required parameter is missing."""
class NonFieldErrors(HTTPError):
"""A non field error ocurred."""
class ImproperlyConfigured(Exception):
"""Webodm is somehow improperly configured"""
pass
|
11422092 | from avatar2 import QemuTarget
from avatar2 import MemoryRange
from avatar2 import Avatar
from avatar2.archs import ARM, MIPS_24KF
from avatar2.targets import Target, TargetStates
from avatar2.message import *
import tempfile
import os
import time
import intervaltree
import logging
from nose.tools import *
qemu = ... |
11422137 | from django.db import models
from profiles.models import Profile, ProfileHub
from hubs.models import Hub, HubGeolocation
class Project(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
description = models.TextField(blank=False, null=False)
start = models.DateTimeField(blank=... |
11422138 | config = {
"RPC": "",
"REST": "",
"VALIDATOR_ADDR": "",
"VALOPER": "",
"DELEGATOR": "",
"VALCONS": "",
"NODE_EXPORTER_URL": "",
"ETH_RPC": "",
"TELEGRAM_TOKEN": "",
"TELEGRAM_CHAT_ID... |
11422152 | from pygments.formatters.html import HtmlFormatter
class CustomHtmlFormatter(HtmlFormatter):
"""Custom HTML formatter. Adds an option to wrap lines into HTML <p> tags."""
def __init__(self, **options):
super().__init__(**options)
self.lineparagraphs = options.get('lineparagraphs', '')
def... |
11422187 | import os
import torch
import torch.nn as nn
# helper printing function
def get_network_description(network):
s = str(network)
n = sum(map(lambda x: x.numel(), network.parameters()))
return s, n
# helper saving function
def save_network(save_dir, network, network_label, iter_label, gpu_ids):
save_file... |
11422190 | import torch
import torch.nn as nn
from codes.model.encoder import EmptyLayer
from codes.model import GCN, GAT, TDecoder
class BaseFusion(nn.Module):
def __init__(self, types, config):
super(BaseFusion, self).__init__()
self.types = types
if 'transformer' in types:
self.decode... |
11422195 | from argparse import Namespace
import pandas as pd
import os
def select_hyperparameter(experiment, hparamset, hyperparameter_path):
assert hparamset is None or isinstance(hparamset,int)
# first hyperparameter tuning <- parameters used for some experiments, kept for backwards compatibility
if hparamset is ... |
11422217 | import sublime
import sublime_plugin
def lookup_symbol(window, symbol):
if len(symbol.strip()) < 3:
return []
index_locations = window.lookup_symbol_in_index(symbol)
open_file_locations = window.lookup_symbol_in_open_files(symbol)
def file_in_location_list(fname, locations):
for l in... |
11422234 | import pymysql, os, json
from dbutils.pooled_db import PooledDB
# 初始化日志模块
import logging, platform, traceback
log_location = "./logs/database.log"
logging.basicConfig(filename=log_location, level=logging.INFO)
class DBPoolHandler(object):
def __init__(self, host, port, user, password, database):
self.PO... |
11422289 | age = 66
if age >= 60:
print('your age is', age)
print('old')
elif age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')
|
11422323 | from datetime import datetime, timedelta
from functools import reduce
from importlib import import_module
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.test.client import RequestFactory
from .. import middleware
def is_recent(time):
return datetime.now() - tim... |
11422333 | import pytest
import json
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from .app import create_app
from flask import url_for
@pytest.fixture
def app():
return create_app()
... |
11422340 | import tensorflow as tf
import os
import cv2
from config import config
import dlib
import argparse
from data_utils import *
from model import *
def parse_arg(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("--trained_weights", type=str,
default="weights/gl... |
11422351 | import numpy as np
import tensorflow as tf
from scipy.optimize import minimize, OptimizeResult
from sklearn.utils import check_random_state
from .base import convert
from .optimizers.utils import from_bounds
from .optimizers.svgd import SVGD
from .optimizers.svgd.base import DistortionConstant, DistortionExpDecay
fro... |
11422383 | nombres_magos=['Luis', 'Pedro', 'Antonio']
def show_magicians(nombres_magos):
for magos in nombres_magos:
print (magos)
show_magicians(nombres_magos)
def make_great(nombres_magos):
for i in range(len(nombres_magos)):
nombres_magos[i] += " the great"
make_great(nombres_magos)
show_magicians(n... |
11422425 | from django.contrib.auth.models import User
class APISetUp:
def setUpUrls(self):
self.reset_password_create_url = "/reset-password"
self.reset_password_submit_url = "/reset-password/submit"
self.reset_password_validation_url = "/reset-password/token-validation"
def check_password(self... |
11422492 | import sys
si = sys.stdin.readline
n = int(si())
a = list(map(int, si().split()))
a.sort()
def func(target_idx):
L, R = 0, n - 1
target = a[target_idx]
while L < R:
if L == target_idx: L += 1
elif R == target_idx: R -= 1
else:
if a[L] + a[R] > target: R -= 1
... |
11422521 | from os import path
from sarna.report_generator.style import *
from test import TEST_PATH
def test_get_document_render_styles():
styles = get_document_render_styles(
path.join(
TEST_PATH,
'resources',
'style_test.docx'
)
)
default_style = styles.get_st... |
11422522 | import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join, splitext, basename
try:
# Python 2
from node_bridge import node_bridge
except:
from .node_bridge import node_bridge
BIN_PATH = join(sublime.packages_path(), dirname(realpath(__file__)), 'node_modules/stylefmt/bin/cli.js')... |
11422598 | import pathlib
def get_cert():
return "<CERT>"
def write_password(filename):
cert = get_cert()
path = pathlib.Path(filename)
path.write_text(cert) # NOT OK
path.write_bytes(cert.encode("utf-8")) # NOT OK
path.open("w").write(cert) # NOT OK
|
11422634 | from rest_framework import __version__
from rest_framework.routers import DefaultRouter
from tests.app.views import ExplosiveViewSet
from tests.app.views import QuoteViewSet
from tests.app.views import SnippetViewSet
v = tuple([int(x) for x in __version__.split(".")])
basename = 'basename' if v >= (3, 9) else 'base_n... |
11422675 | from django.http import HttpResponse
from django.shortcuts import render
from daiquiri.core.renderers.voresource import VoresourceRenderer
from daiquiri.core.renderers.vosi import AvailabilityRenderer, CapabilitiesRenderer, TablesetRenderer
from daiquiri.query.models import Example
from .vo import get_resource, get_a... |
11422687 | import math
import random as r
import time
from functools import lru_cache
from os.path import join
import pathlib
import cv2
import numpy as np
import scipy.signal
from PIL import Image
import torch
import torch.nn.functional as F
from scipy.ndimage.interpolation import map_coordinates
from torch.distributions import... |
11422739 | import dataclasses
import re
from typing import Optional
def _coerce_type(s: Optional[str]) -> Optional[int]:
if s is None:
return None
else:
return int(s)
@dataclasses.dataclass(frozen=True)
class VersionRepresentation:
major: int
minor: int
patch: Optional[int] = None
pre_r... |
11422747 | import os
import sqlite3
import numpy as np
from pandas import read_sql_query, DataFrame, Series
from gtfspy.gtfs import GTFS
from gtfspy.util import timeit
from gtfspy.routing.journey_data import attach_database
class JourneyDataAnalyzer:
# TODO: Transfer stops
# TODO: circuity/directness
def __init__(... |
11422799 | class CreateTable:
def __init__(self, table_name, columns):
self.table_name = table_name
self.columns = columns
def __repr__(self):
class_name = self.__class__.__name__
column_repr = ""
for column in self.columns:
if column.primary_key:
colum... |
11422803 | import torch
from torch import nn
from models.baseNet import BaseNet
from models.layers import *
class SetOfSetBlock(nn.Module):
def __init__(self, d_in, d_out, conf):
super(SetOfSetBlock, self).__init__()
self.block_size = conf.get_int("model.block_size")
self.use_skip = conf.get_bool("mo... |
11422830 | readMe = """A Python 3 script to check the security patch date of Android devices managed by
Meraki Systems Manager and generate a report or apply tags to them to trigger enforcement actions.
Script syntax, Windows:
python android_patch_audit.py [-c <config_file>]
Script syntax, Linux and Mac:
py... |
11422831 | import re
from pathlib import Path
from typing import Optional
__all__ = ('SasstasticError', 'is_file_path')
class SasstasticError(RuntimeError):
pass
def is_file_path(p: Optional[Path]) -> bool:
return p is not None and re.search(r'\.[a-zA-Z0-9]{1,5}$', p.name)
|
11422887 | from __future__ import absolute_import
import collections
import functools
import logging
import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.settings
from tornado import stack_context, httputil
from tornado.concurrent import Future
from tornado.httpclient import HTTP... |
11422902 | import netomaton as ntm
from netomaton import TuringMachine, HeadCentricTuringMachine
if __name__ == "__main__":
# A Turing machine with two possible states for the head, and two possible states for each cell in the tape.
# A reproduction of the Turing machine given on page 79 (figure (b)) of Wolfram's New K... |
11422921 | import sys, os
import ast
import re
import numpy as np
import pickle
from subprocess import check_call
from csv import DictReader
from frontend.label_normalisation import HTSLabelNormalisation
prep_lab_scp = './scripts/prepare_labels_from_txt.sh'
glob_conf = './conf/global_settings.cfg'
ques_file = './conf/questions.... |
11422942 | import asyncio
from services.data.models import RunRow
from services.utils import has_heartbeat_capable_version_tag, read_body
from services.metadata_service.api.utils import format_response, \
handle_exceptions
from services.data.postgres_async_db import AsyncPostgresDB
class RunApi(object):
_run_table = Non... |
11422952 | from torch import nn, Tensor
__reference__ = [
"Large Kernel Matters -- Improve Semantic Segmentation by Global Convolutional Network",
"https://arxiv.org/abs/1703.02719",
]
class BoundaryRefine(nn.Module):
def __init__(self, dim):
super().__init__()
self.non_linearity = nn.ReLU(inplace=T... |
11423018 | import unittest
import quiet_times
class TestQuietTimes(unittest.TestCase):
def test_get_quiet_times(self):
times = quiet_times.get_quiet_times('../data/quiet_times.json')
self.assertTrue(len(times) > 0)
self.assertEqual(17, times[1].start.hour)
self.assertEqual(27, times[1].star... |
11423031 | from ..markup import Markup, get_installed_markups, get_markup_choices
from ..elements.elementbase import Attribute
from ..tags.content import RenderBase
from ..tags.context import DataSetter, LogicElement
from ..compat import text_type
from textwrap import dedent
class _Markup(RenderBase):
"""Insert markup in t... |
11423079 | import asyncio
import shutil
import subprocess
from pathlib import Path
from typing import Any, List
from jinja2 import Environment, PackageLoader
from . import logger
from .exceptions import FetchError, GenerateError, GenerateScriptError
from .fetcher import fetch
from .parser import Blueprint
_environment = Enviro... |
11423104 | import os
import errno
import socket
import struct
from select import select
from .utils import DictWrapper
from . import netlink, connector
PROC_CN_MCAST_LISTEN = 0x1
PROC_CN_MCAST_IGNORE = 0x2
PROC_EVENT_NONE = 0x00000000
PROC_EVENT_FORK = 0x00000001
PROC_EVENT_EXEC = 0x00000002
PROC_EVENT_UID = 0x00000004
PROC_EV... |
11423106 | from bs4 import BeautifulSoup
from urllib.parse import urljoin
import repo
def crawl(url, queued_count, maximum_items, get_html, extract_content):
if not url:
print('URL not provided', url)
return
already_seen = _seen(url)
if already_seen:
print('URL already seen ', already_seen)
... |
11423114 | from pulsar.apps import rpc
def get_model(wsrequest):
"""Get a Rest model from a websocket rpc request
:param wsrequest:
:return: a :class:`~RestModel`
"""
model = wsrequest.pop_param('model')
restmodel = wsrequest.app.models.get(model)
if not restmodel:
raise rpc.InvalidParams('M... |
11423132 | import csv
from rdflib import Graph, Literal, Namespace, URIRef
from rdflib.namespace import DCTERMS, RDF, RDFS, SKOS, XSD
input_file = csv.DictReader(open("test_sheet.csv"))
# make a graph
output_graph = Graph()
for row in input_file:
# convert it from an OrderedDict to a regular dict
row = dict(row)
#{'Sub... |
11423170 | from gi.repository import Gst
from brave.helpers import create_intersink_channel_name, block_pad, unblock_pad
class Connection():
'''
A connection connects a 'source' to a 'dest'. Valid connections are:
- input to mixer
- mixer to mixer
- input to output
- mixer to output
'''
def ... |
11423182 | from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from win10toast import ToastNotifier
import time
URL = 'http://www.cricbuzz.com/cricket-match/live-scores'
def notify(title, score):
# Function for Windows toast desktop notification
toaster = ToastNotifier()
# toaster.show_toast(s... |
11423218 | import torch
import torch.nn as nn
import torch.nn.functional as F
class TextCNN(nn.Module):
'''
An embedding layer that maps the token id into its corresponding word
embeddings. The word embeddings are kept as fixed once initialized.
'''
def __init__(self, vocab, finetune_ebd=False, num_f... |
11423223 | import django
if django.VERSION < (2, 0):
from django.conf.urls import url
else:
from django.urls import re_path as url
from admin_tools.dashboard import views
urlpatterns = [
url(
r'^set_preferences/(?P<dashboard_id>.+)/$',
views.set_preferences,
name='admin-tools-dashboard-set-p... |
11423259 | class A:
def f(self):
return 'A'
@classmethod
def cm(cls):
return (cls, 'A')
class B(A):
def f(self):
return super().f() + 'B'
@classmethod
def cm(cls):
return (cls, super().cm(), 'B')
class C(A):
def f(self):
return super().f() + 'C'
@classmetho... |
11423273 | import logging
from dd import autoref as _bdd
import dd.bdd
from nose.tools import assert_raises
from common import Tests
from common_bdd import Tests as BDDTests
logging.getLogger('astutils').setLevel('ERROR')
Tests.DD = _bdd.BDD
BDDTests.DD = _bdd.BDD
def test_find_or_add():
bdd = _bdd.BDD()
bdd.decla... |
11423309 | import logging
from django.db import transaction
from django.core.management.base import BaseCommand
from django.core.exceptions import ValidationError
from dataview.items.models import CraigsListItem
from craigslist.pipeline import KafkaPipeline
from craigslist.utils import get_statsd_client, METRIC_ITEMS_IMPORTED_K... |
11423311 | from django.core.management.base import BaseCommand, CommandError
# from electionsproject.settings import mccelectionsenv
from django.core.management import call_command
from results.slackbot import slackbot
import time
class Command(BaseCommand):
help = 'Automatically run the two main election scripts: download_... |
11423340 | import ptt
from ptt.parser import PttParseContentError
def test_get_meta_over18():
board = ptt.Board('Gossiping')
meta = board.get_meta(num=20)
assert len(meta) == 20
def test_get_meta():
board = ptt.Board('Soft_Job')
meta = board.get_meta(num=20)
assert len(meta) == 20
board = ptt.Boar... |
11423348 | import json
import click
from .client import NomadgenAPI
from .helpers import validate_json_output, jobToJSON
nomadgen_client = NomadgenAPI()
def abort_if_false(ctx, param, value):
if not value:
ctx.abort()
@click.group()
@click.option(
"--addr", default="http://127.0.0.1:4646", help="Address of n... |
11423382 | import functools
import time
from django.db import connection, reset_queries
def query_debugger(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
reset_queries()
number_of_start_queries = len(connection.queries)
start = time.perf_counter()
result = func(*args, **kwarg... |
11423396 | from unittest.mock import create_autospec, ANY, patch, call
import pytest
from stack.commands import DatabaseConnection
from stack.commands.list.firmware import Command
from stack.commands.list.firmware.model.plugin_basic import Plugin
from stack.exception import CommandError
class TestListFirmwareModelBasicPlugin:
"... |
11423402 | from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
from .common import CommonInfo
class Donation(CommonInfo):
from .session import Session
from .user import CDCUser
user = models.ForeignKey(
CDCUser,
blank=True,
... |
11423451 | import sublime
from Tutkain.api import edn
from Tutkain.src.repl import ports
from unittest import TestCase
class TestPorts(TestCase):
def setUp(self):
sublime.run_command("new_window")
self.window = sublime.active_window()
def tearDown(self):
if window := self.window:
w... |
11423496 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import gym
class PPO():
def __init__(self,
actor_critic,
clip_param,
ppo_epoch,
num_mini_batch,
v... |
11423507 | class MCMCSampler(object):
"""
Base class for all MCMC samplers.
"""
def initialize_sample(self, seed=None):
raise NotImplementedError
def mcmc_chain(self, T_burnin, T, seed=None):
self.t = 0
self.T_burnin = T_burnin
sample = self.initialize_sample(seed=seed)
... |
11423562 | from collections import OrderedDict
from .cdeclparser import lines_to_statements
PURE_ENUM_MAP = {
'MouseButton': 'MouseButton',
'Key': 'Key',
'TournamentAction': 'Tournament::ActionID',
'TextColor': 'Text::Enum',
'TextSize': 'Text::Size::Enum',
}
def take_pure_enums(line_gen):
result = []
... |
11423611 | import pytest
from tests.blogs_tests.factory import PostFactory
from tests.evaluation_tests.test_permissions import get_users_with_set_perms
from tests.factories import UserFactory
@pytest.mark.django_db
@pytest.mark.parametrize("reverse", [True, False])
def test_post_authors_permissions_signal(client, reverse):
... |
11423624 | import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print("a:", a)
print("b:", b)
|
11423649 | import logging
from contextlib import ExitStack
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt="%Y-%m-%d %H:%M:%S")
logger = logging.getLogger(__name__)
import os
import argparse
import numpy ... |
11423657 | from starlette.config import Config
config = Config(".env")
PROVIDER_MODULES = "chatbot.providerconf"
|
11423690 | from api.models.album_auto import AlbumAuto
from api.models.album_date import AlbumDate
from api.models.album_place import AlbumPlace
from api.models.album_thing import AlbumThing
from api.models.album_user import AlbumUser
from api.models.face import Face
from api.models.long_running_job import LongRunningJob
from api... |
11423692 | import json
from pathlib import Path
import argparse
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-m', '--model', default=None, type=str)
args = parser.parse_args()
return args
def load_json(path):
with open(path, 'r') as f:
x = json.load(f... |
11423706 | import unittest
import numpy as np
import sys
sys.path.append('../src')
import parameters_simulation as p
from driving_env import Highway
import traci
from copy import deepcopy
class Tester(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(Tester, self).__init__(*args, **kwargs)
def test... |
11423726 | import unittest
from transforms.frft import *
from transforms.z_transform import *
class FRFTTest(unittest.TestCase):
def xtest_1(self):
size = 2048
l = 20
a = 1/2
x_grid = get_fcft_grid(size, l)
f_x = np.exp(-x_grid ** 2 * a)
ff_x = fcft(f_x, l, l, l)
# pl... |
11423777 | from __future__ import division
import json
import math
import sys
import htmlmin
template = """
<html>
<head>
<link href="site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=EB+Garamond" rel="stylesheet">
<script type="text/javascript" src="app.js"></script>
<script src="ht... |
11423779 | import numpy as np
import utiltools.robotmath as rm
import trimesh.transformations as tf
from panda3d.core import *
class Rigidbody(object):
def __init__(self, name = 'generalrbdname', mass = 1.0, pos = np.array([0,0,0]), com = np.array([0,0,0]),
rotmat = np.identity(3), inertiatensor = np.identit... |
11423821 | from commodities.models.orm import FootnoteAssociationGoodsNomenclature
from commodities.models.orm import GoodsNomenclature
from commodities.models.orm import GoodsNomenclatureDescription
from commodities.models.orm import GoodsNomenclatureIndent
from commodities.models.orm import GoodsNomenclatureIndentNode
from comm... |
11423824 | from ipaddress import IPv4Address
from CybORG.Shared import Observation
from CybORG.Shared.Actions.ConcreteActions.ExploitAction import ExploitAction
from CybORG.Shared.Enums import OperatingSystemPatch, OperatingSystemType, OperatingSystemDistribution
from CybORG.Simulator.Host import Host
from CybORG.Simulator.Proce... |
11423860 | from rcli.autodetect import _ensure_entry_points_is_dict
def test_ensure_entry_points_is_dict_works_with_none():
assert _ensure_entry_points_is_dict(None) == {}
def test_ensure_entry_points_is_dict_works_with_dict():
expected = {
"console_scripts": ["foobarbaz=foo.bar:baz"],
}
assert _ensure... |
11423870 | def f(x):
return x**x
def simpson38 (a,b,n):
h = abs(b-a)/n
S = 0
while a-b<-h/2:
S += f(a)+3*f(a+h/3)+3*f(a+2*h/3)+f(a+h)
a += h
return S*h/8 |
11423874 | expected_output = {
"GigabitEthernet0/0/0/0": {
"enabled": True,
"int_status": "up",
"ipv6": {
"2001:db8:8548:1::2/64": {
"ipv6": "2001:db8:8548:1::2",
"ipv6_prefix_length": "64",
"ipv6_subnet": "2001:db8:8548:1::",
},
... |
11423884 | import datetime
from collections import Counter, deque
import numpy as np
from covid19sim.run import simulate
from covid19sim.utils.utils import extract_tracker_data
from tests.utils import get_test_conf
def print_dict(title, dic, is_sorted=None):
if not is_sorted:
items = dic.items()
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.