id
stringlengths
3
8
content
stringlengths
100
981k
4809588
from algorithms.classic.sample_based.core.vertex import Vertex from structures import Point from structures.tracked import Tracked from structures.factory import prefer_tracked from simulator.services.services import Services import torch from abc import ABC, abstractmethod from typing import Callable, List, Tuple, An...
4809601
import sys import os import pathlib import argparse import subprocess import json from datetime import datetime import pandas def create_parser(): parser = argparse.ArgumentParser( description="Run a comparison between IPC and our method.") parser.add_argument( "-i", "--input", metavar="path/...
4809637
from social_core.backends.saml import SAMLIdentityProvider, \ DummySAMLIdentityProvider, SAMLAuth
4809680
import locale from operator import itemgetter, attrgetter from itertools import tee, islice, chain def naturalsort(iterable, key=None): """ Locale-aware alphabetical string sorting, Besides string, key can be index or argument name """ locale.setlocale(locale.LC_ALL, '') _getter = itemgetter(...
4809694
from collections import defaultdict import tensorflow as tf from smart_compose.utils.parsing_utils import InternalFtrType class KeyValueArrayDict(tf.Module): """A dictionary holding mapping of key -> sparse values In prefix lookup, we need to return tokens starting with user input. A naive approach is to b...
4809711
import sys, os, pytest sys.path.append(os.getcwd()) from do_grader_lib import PartQuality from anyint import grader input_data = '' quality = PartQuality('test', 7, 10) greedy_submission = '7\n123\n' opt_submission = '10\n123\n' # Score Test def test_full_credit(): result = grader.grade(input_data, quality, o...
4809740
import sys def layer_from_config(config): """ Construct a layer from a configuration. Args: A dictionary configuration of the layer metadata. Returns: An object which is a subclass of `Layer`. """ layer_config = dict(config) layer_obj = getattr(sys.modules['paysage.layers...
4809760
from .immediate_scope import ImmediateScope from .per_lookup_scope import PerLookupScope from .scope import Scope from .singleton_scope import SingletonScope from .singleton_scoped_provider import SingletonScopedProvider from .thread_scope import ThreadScope from .thread_scoped_provider import ThreadScopedProvider
4809773
import torch def prepare_training_inputs(sampled_exps, device='cpu'): states = [] actions = [] rewards = [] next_states = [] dones = [] for sampled_exp in sampled_exps: states.append(sampled_exp[0]) actions.append(sampled_exp[1]) rewards.append(sampled_exp[2]) n...
4809799
from __future__ import annotations from typing import Any from homeassistant.const import ATTR_DEVICE_CLASS, CLOUD_NEVER_EXPOSED_ENTITIES, CONF_NAME, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant, State, callback from homeassistant.helpers.area_registry import AreaEntry, AreaRegistry from homeassista...
4809817
import os # noqa from django.test import TestCase # from rodan.models.workflowrun import WorkflowRun # from rodan.models.workflowjob import WorkflowJob from rodan.models.runjob import RunJob from model_mommy import mommy from rodan.test.helpers import RodanTestTearDownMixin, RodanTestSetUpMixin class RunJobTestCase(...
4809829
import pytest from unittest.mock import Mock import numpy as np import pandas as pd from sklearn_pandas import DataFrameMapper from sklearn.compose import make_column_selector from sklearn.preprocessing import StandardScaler class GetStartWith: def __init__(self, start_str): self.start_str = start_str ...
4809836
from __future__ import annotations import unittest from apm import * class Glob(unittest.TestCase): def test_empty(self): self.assertTrue(match( [1, 2, 3], [1, Many(...), 2, 3] )) def test_at_least(self): self.assertTrue(match( [1, 2, 3], ...
4809860
import click import json import subprocess def run_command(cmd, as_list=True): try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True ) except Exception as e: print 'Warning: {0}'.format(e) return [] if as_list:...
4809912
try: from judgments import Judgment, judgments_from_file, judgments_to_file, judgments_by_qid from butterfingers import butterfingers except ImportError: from .judgments import Judgment, judgments_from_file, judgments_to_file, judgments_by_qid from .butterfingers import butterfingers def typoIt(judgm...
4809966
from factory import Factory, Faker from pss_project.api.models.rest.metadata.EnvironmentMetadata import EnvironmentMetadata class EnvironmentMetadataFactory(Factory): class Meta: model = EnvironmentMetadata os_version = Faker('word') cpu_number = Faker('random_int', min=1, max=16) cpu_socket ...
4810020
import numpy as np import pandas as pd from staircase.constants import inf from staircase.core.arrays import docstrings from staircase.core.stairs import Stairs from staircase.core.stats.statistic import corr as _corr from staircase.core.stats.statistic import cov as _cov from staircase.util._decorators import Appende...
4810092
import os import tensorflow as tf import numpy as np from tflayers import * EPS = 1e-7 def prepare_input(d,q): f = np.zeros(d.shape).astype('int32') for i in range(d.shape[0]): f[i,:] = np.in1d(d[i,:],q[i,:]) return f class Model(object): def __init__(self, params, W_init, embed_dim, device=...
4810093
import os class SparkFiles(object): """ Resolves paths to files added through L{SparkContext.addFile()<pyspark.context.SparkContext.addFile>}. SparkFiles contains only classmethods; users should not create SparkFiles instances. """ _root_directory = None _is_running_on_worker = False...
4810110
from abc import ABC import collections import csv from io import BytesIO, StringIO from django.contrib.auth.decorators import login_required from django.contrib import messages from django.core.exceptions import ValidationError from django.db import transaction from django.db.models import Count from django.http impor...
4810113
from django.db import models from django.utils.translation import gettext_lazy as _ class BootstrapType(models.TextChoices): SUCCESS = 'SUCCESS', _('SUCCESS') DANGER = 'DANGER', _('DANGER') WARNING = 'WARNING', _('WARNING') INFO = 'INFO', _('INFO')
4810136
import ccxt import pandas query = 40 ccxt_client = ccxt.binance() tohlcv_colume = ['timestamp', 'open', 'high', 'low', 'close', 'volume'] def get_klines(pair, interval): return pandas.DataFrame(ccxt_client.fetch_ohlcv(pair, interval, limit=query), columns=tohlcv_colume) def candlestick(klines): # Create a ne...
4810167
from functools import wraps from uuid import uuid1 from types import NoneType from django.http import HttpResponse from jsonrpc._json import loads, dumps from jsonrpc.exceptions import * empty_dec = lambda f: f try: from django.views.decorators.csrf import csrf_exempt except (NameError, ImportError): csrf_exempt = ...
4810173
import securityheaders from securityheaders import Util from securityheaders.models import Header, Directive, Keyword from securityheaders.singleton import Singleton import warnings class ModelFactory(Singleton): def __init__(self): self.clazzes = dict() self.headers = dict() def getmodel(sel...
4810174
from CurrentMediaPlayer import CurrentMediaPlayer from MediaAdapter import MediaAdapter from MoviePlayer import MoviePlayer currentMediaPlayer = CurrentMediaPlayer() mediaAdapter = MediaAdapter(currentMediaPlayer) moviePlayer = MoviePlayer(mediaAdapter) # Testing for MKV moviePlayer.play("<NAME>.mkv") # Testing for ...
4810187
import http.cookiejar from math import * import requests from scipy import integrate s = requests.Session() from requests_html import HTMLSession sqrt(1) session = HTMLSession() session.cookies = http.cookiejar.MozillaCookieJar("anything.txt") mn, mx = 0, 0 def int_(x): def wrapper(a, b=x): global mn, ...
4810262
import sqlite3 class DataBase(): conexion = sqlite3.connect('IceandFire.db') cursor = conexion.cursor() cursor.execute('''CREATE TABLE ICEANDFIRE (url int PRIMARY KEY NOT NULL, name text NOT NULL, grender text NOT NULL, culture text NOT NULL, born text NOT NULL, ...
4810269
import Configuration import Constants from BatterySimple import BatterySimple from BatteryHeightDifferenceBased import BatteryHeightDifferenceBased # The BatteryFactory is responsible for returning the correct battery object depending on the configuration def get_battery(battery_life, agent): battery_model = Confi...
4810309
import time def test_pumps_actually_stop(GPIO, smbus): from grow.pump import Pump, global_lock ch1 = Pump(channel=1) ch1.dose(speed=0.5, timeout=0.05, blocking=False) time.sleep(0.1) assert ch1.get_speed() == 0 def test_pumps_are_mutually_exclusive(GPIO, smbus): from grow.pump import Pump,...
4810322
import sys, os root_dir = os.path.join(os.path.dirname(__file__),'..') if root_dir not in sys.path: sys.path.insert(0, root_dir) import socket import time from visualization.socket_utils import BaseSocketClient def send_rand(client): import numpy as np N_person = 4 datas = [] for i in range(N_perso...
4810372
import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from scipy.spatial.distance import squareform try: import plotly.graph_objects as go except ImportError: pass def __calculate_plot_data(variogram, points): # get the direction mask direction_mask = sq...
4810392
from dataclasses import dataclass from enum import Enum from bakelite.proto.serialization import struct, enum from bakelite.proto.runtime import Registry, ProtocolBase from typing import List registry = Registry() @struct(registry, r'''{"members": [{"type": {"name": "uint8", "size": null}, "name": "a", "value...
4810396
import abc class oveja(): @abc.abstractmethod def clone(self): pass class dolly(oveja): def __init__(self,nombre,tipo): self.nombre=nombre self.tipo=tipo def set_nombre(self,nombre): self.nombre=nombre def set_tipo(self,tipo): self.tipo=tipo def get_tipo(self): return self.tipo def get_nombre(self):...
4810439
import random import torch from ray.rllib.agents import ppo, pg, dqn, a3c from ray.rllib.agents.a3c.a3c_torch_policy import ( A3CTorchPolicy, add_advantages, ) from ray.rllib.agents.callbacks import DefaultCallbacks from ray.rllib.agents.dqn.dqn_torch_policy import postprocess_nstep_and_prio from ray.rllib.age...
4810472
import json import logging import os from pathlib import Path from typing import Any, Dict, Union logger = logging.getLogger(__name__) try: from _jsonnet import evaluate_file except ImportError: def evaluate_file(filename: str, **_kwargs: Any) -> str: logger.warning("jsonnet is unavailable, treating ...
4810514
import socket from vstruct2.types import * ''' Inet Packet Structures ''' ethp = venum() ethp.ipv4 = 0x0800 ethp.ipv6 = 0x86dd ethp.vlan = 0x8100 ipproto = venum() ipproto.ICMP = 1 ipproto.TCP = 6 ipproto.UDP = 17 ipproto.IPV6 = 41 TCP_F_FIN = 0x01 TCP_F_SYN = 0x02 TCP_F_RST = 0x04 TCP_F_PUSH = 0x...
4810520
from optimizer import * from krelu import * import time def refine_gpupoly_results(nn, network, num_gpu_layers, relu_layers, true_label, labels_to_be_verified, K=3, s=-2, timeout_lp=10, timeout_milp=10, timeout_final_lp=100, timeout_final_milp=100, use_milp=False, ...
4810611
import socket from requests.adapters import HTTPAdapter from requests.packages.urllib3.response import HTTPResponse from requests.packages.urllib3.exceptions import MaxRetryError from requests.packages.urllib3.exceptions import TimeoutError from requests.packages.urllib3.exceptions import SSLError as _SSLError from re...
4810623
from rest_framework.permissions import BasePermission from kolibri.core.auth.permissions.general import _user_is_admin_for_own_facility class NetworkLocationPermissions(BasePermission): """ A user can access NetworkLocation objects if: 1. User can manage content (to get import/export peers) 2. User i...
4810636
from mock import patch import unittest try: from urlparse import parse_qs from urlparse import urlparse except ImportError as e: from urllib.parse import urlparse from urllib.parse import parse_qs @patch("pyga.requests.urlopen") class TestGA(unittest.TestCase): def test_request(self, mocked): ...
4810678
import torch import numpy as np from mmdet.utils import get_root_logger from .builder import DATASETS class RandomDataStream: def __init__(self, data, generator, shuffle=True, dtype=torch.int32): self._size = len(data) self.data = torch.Tensor(data).to(dtype=dtype) self._shuffle = shuffle ...
4810707
import matplotlib import sys # Do not display GUI only when generating output if __name__ != '__main__' or len(sys.argv) >= 3: matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.axes as axes import numpy as np import sklearn.decomposition from sklearn.manif...
4810710
from diagrams import Diagram, Cluster from diagrams.aws.compute import EC2, ECS from diagrams.aws.database import RDS from diagrams.aws.network import ELB, VPC, TransitGateway with Diagram("vpc", show=False, direction="TB") as diag: with Cluster("VPC"): with Cluster(f"Private Subnet 1"): ECS("E...
4810740
import sys import logging from logging import config from sb_service.common import logging_util from external_tools.daemon.daemonize import Daemon from common import constants from sb_service.daemons.PostProcessDaemon import PostProcessDaemon class PostProcessDaemonJava(Daemon): def __init__(self, pidfile): ...
4810743
from .manifold import ( Stereographic, StereographicExact, PoincareBall, PoincareBallExact, SphereProjection, SphereProjectionExact, ) from . import math
4810748
import sys # def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): def text_from_bits(bits, encoding='utf-8', errors='ignore'): try: n = int(bits, 2) val = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0' return val except Exception as e: ...
4810764
from dsl.impl import HIGHER_ORDER_FUNCTIONS, FIRST_ORDER_FUNCTIONS, LAMBDAS def build_operator_space(): operators = [] for func in HIGHER_ORDER_FUNCTIONS: for lambd in LAMBDAS: if lambd.type == func.input_type[0]: operators.append(Operator(func, lambd)) operators += [Op...
4810793
import sys import logging sys.path.append("../../") levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] def changed(btn): app.setLogLevel(app.getOptionBox("LogLevel")) def filer(btn): if app.getRadioButton("place") == "File": app.setLogFile("a.log") def submit(level): msg = app.getEntry(l...
4810808
import os import re import json def ensure_file_directory(file): inception(os.path.dirname(os.path.realpath(file))) def inception(directory): parent_directory = os.path.dirname(directory) if not os.path.exists(parent_directory): inception(parent_directory) if not os.path.exists(directory): ...
4810883
from state import called def setup(): called.append('test_pak2.setup') def teardown(): called.append('test_pak2.teardown') def test_two_one(): called.append('test_pak2.test_two_one') def test_two_two(): called.append('test_pak2.test_two_two')
4810911
import pandas as pd from pymatgen.core import Composition binaries = pd.read_csv('binary_band_gap.csv') # We create a column holding the Composition object. # Note the use of list comprehension in Python. binaries['composition'] = [Composition(c) for c in binaries['Formula']] electronegs = [[el.X for el in c] for c in...
4810932
from django.db.backends import BaseDatabaseValidation class DatabaseValidation(BaseDatabaseValidation): pass
4810951
import logging import gym from igibson.object_states import AABB from igibson.object_states.utils import detect_closeness from igibson.render.mesh_renderer.mesh_renderer_settings import MeshRendererSettings from igibson.render.mesh_renderer.mesh_renderer_vr import VrSettings from igibson.robots import REGISTERED_ROBO...
4810982
from amadeus.client.decorator import Decorator class HotelSentiments(Decorator, object): def get(self, **params): ''' Provides ratings and sentiments scores for hotels .. code-block:: python amadeus.e_reputation.hotel_sentiments.get(hotelIds='TELONMFS,ADNYCCTB']) :pa...
4811006
import setuptools # To use a consistent encoding from codecs import open import os here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setuptools.setup( name='jax-spectral', version='0.0.1', description='scip...
4811011
a&&b||c a &&= a b ||= c a : source.python && : invalid.illegal.operator.python, source.python b : source.python || : invalid.illegal.operator.python, source.python c : source.python a : source.python : source.python && : i...
4811012
from django.contrib.auth.decorators import login_required from django.conf.urls import url from systori.apps.company.views import ( CompanyList, CompanyCreate, CompanyUpdate, CompanyDelete, ) urlpatterns = [ url(r"^companies$", login_required(CompanyList.as_view()), name="companies"), url( ...
4811039
import os import pytest from vivid import create_runner from vivid.backends.experiments import LocalExperimentBackend from vivid.features.decomposition import PCABlock, GaussianMixtureBlock @pytest.mark.parametrize('block', [ PCABlock('pca'), GaussianMixtureBlock('gmm') ]) def test_pca_block(tmpdir, regress...
4811046
from flask import Flask from flask_restplus import Api, Resource, fields, reqparse app = Flask(__name__) # API Configs api = Api(app, version="0.1", title="People API with Flask-RESTPlus", description="A quite simple API to working with personal data") # Namespaces peopleCollection_api = api.namespace("peopleCollec...
4811053
from twitch_highlights import TwitchHighlights twitch_credentials = { "client_id": "##############################", # Your client id here "client_secret": "##############################" # Your client secret here } acr_credentials = { "access_key": "################################"...
4811066
import cv2 import numpy as np import dlib from imutils import face_utils from keras.models import load_model detector = dlib.get_frontal_face_detector() model_simple = load_model('Simple_Autoencoder_face.h5') model_deep = load_model('Deep_Autoencoder_face.h5') model_conv = load_model('Convolutional_Autoencoder_face.h...
4811199
from datetime import datetime import math from . import FeedSource SECONDS_PER_DAY = 60 * 60 * 24 class Norm(FeedSource): def _norn_feed(self, amplitude, reference_timestamp, current_timestamp, period, phase_offset): """ Given the reference timestamp, the current timestamp, the period (in days), the ph...
4811204
import sys import inspect from collections import namedtuple from functools import update_wrapper if sys.version_info < (3,): # Python 2 from httplib import responses as http_reasons from cStringIO import StringIO as BytesIO from urlparse import urlparse, parse_qsl def _exec(code, g): exec...
4811216
import argparse def parse_args(): parser = argparse.ArgumentParser(description='3D Object Point Cloud Completion') # Optimization arguments parser.add_argument('--optim', default='adagrad', help='Optimizer: sgd|adam|adagrad|adadelta|rmsprop') parser.add_argument('--momentum', default=0.9, type=float, ...
4811242
text = "X-DSPAM-Confidence: 0.8475"; s = text.find(' ') newText = text[s:].strip() n = float(newText) print(n)
4811349
import morepath from .app import App def run(): morepath.autoscan() morepath.run(App()) if __name__ == '__main__': run()
4811402
import unittest import rx from rx import operators as rxop from rxbp.multicast.testing.testmulticastobservable import TestMultiCastObservable from rxbp.multicast.testing.testmulticastobserver import TestMultiCastObserver from rxbp.testing.tscheduler import TScheduler class TestLiftObservable(unittest.TestCase): ...
4811427
import numpy as np import tensorflow as tf from rlo.layers import DenseGNN, SparseGNN from rlo.pipelines import DensePipeline, SparsePipeline from rlo import utils from testutils import parse_expr_typed, load_dataset def eval_dense_gnn( expressions, use_subtree_match_edges, hidden_dim, num_propagatio...
4811434
import sys if 'scoring_engine.checks' in sys.modules: del sys.modules['scoring_engine.checks'] import scoring_engine.checks def test_scoring_engine_checks(): assert sys.modules['scoring_engine.checks'] == scoring_engine.checks
4811436
from pathlib import Path import cv2 import numpy as np import utils from joblib import Parallel, delayed def merge_test(file_name): result = np.zeros((num_folds, 1280, 1918)) for fold in range(num_folds): img_path = file_name.parent.parent.parent / str(fold) / 'test' / (file_name.stem + '.png') ...
4811441
from malcolm.yamlutil import check_yaml_names, make_block_creator profiling_web_server_block = make_block_creator( __file__, "profiling_web_server_block.yaml" ) __all__ = check_yaml_names(globals())
4811457
from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime, timedelta from typing import Any, List, Optional, Tuple, Union, ClassVar, Type import attr from attr.converters import optional as c_optional from attr.validators import in_, instance_of, optional as v_optional fro...
4811504
import FWCore.ParameterSet.Config as cms OutALCARECOEcalTrg_noDrop = cms.PSet( # put this if you have a filter SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('pathALCARECOEcalTrg'), ), outputCommands = cms.untracked.vstring( 'keep CaloTowersSorted_towerMaker_*_*', ...
4811543
import flask import flask_login from flask import Blueprint from flask_login import LoginManager from lib.resp import Resp from lib.admin import const from lib.admin import account from lib.admin.models import User from lib.admin.database import db from lib.admin.bcrypt import bcrypt admin = Blueprint('ad...
4811558
import threading import sys sys.path.append(r"..") from xpersec import XPerSec sys.path.append(r"..\..\..\..") import zerorpc.client counter = XPerSec("calls") def thread_func(): ITERS = 40000 s = zerorpc.client.ZeroRpcClient("tcp://localhost:5555") for i in range(ITERS): result = s.mult(i, i+1) ...
4811560
from __future__ import annotations from ._version import version as __version__ __all__ = ["__version__"]
4811598
from pathlib import Path import pytest from warn.platforms.job_center.cache import Cache from .conftest import write_file @pytest.fixture def cache_dir(tmp_path): """Create a path for a cache test.""" return str(tmp_path.joinpath("ks")) @pytest.mark.parametrize( "test_input", [ # Initial ...
4811607
import TB2J def print_license(): print(f""" TB2J version {TB2J.__version__} Copyright (C) 2018-2020 TB2J group. This software is distributed with the 2-Clause BSD License, without any warranty. For more details, see the LICENSE file delivered with this software. """)
4811612
import unittest import numpy as np import tensorflow as tf from neural_network_decision_tree import tf_kron_prod, tf_bin, nn_decision_tree class TestNeuralNetworkDecisionTree(unittest.TestCase): def test_tf_kron_prod(self): sess = tf.InteractiveSession() a = np.array([[1, 2], ...
4811701
import pyb import stm # This script sets up a timer to do quadrature decoding # # It was tested using a switch similar to https://www.sparkfun.com/products/9117 pin_a = pyb.Pin('X1', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE, af=pyb.Pin.AF1_TIM2) pin_b = pyb.Pin('X2', pyb.Pin.AF_PP, pull=pyb.Pin.PULL_NONE, af=pyb.Pin.AF1...
4811752
from mk_sendmany import mk_multisend_code, get_multisend_gas from ethereum.tools import tester2 from ethereum import utils # from ethereum.slogging import get_logger, configure_logging # logger = get_logger() # configure_logging(':trace') c = tester2.Chain() args = {utils.int_to_addr(10000 + i ** 3): i ** 3 for i i...
4811755
import pandas as pd import numpy as np from collections import OrderedDict def calculate_profits( bids, transactions, reservation_prices=None, fees=None, **kwargs): """Extras from the transactions and the bids the profit of each player and the market maker Paramete...
4811763
import torch import torch.nn as nn import torch.nn.functional as func from torch.distributions import Normal from torch.utils.data import Dataset from torchvision.datasets import CIFAR10 from torchvision.transforms import ToTensor, Compose, RandomAffine, ColorJitter from torchsupport.training.multiscale_training impo...
4811771
import ast import json from dbconnection import db_connect db_object = db_connect() global db db = db_object.apiscan def check_scan_status(data): # Return the Scan status total_scan = data['total_scan'] count = 0 for key,value in data.items(): if value == 'Y' or value == 'y': coun...
4811774
from src.gamemodes import game_mode, GameMode, InvalidModeException from src.messages import messages from src.events import EventListener from src import channels, users @game_mode("rapidfire", minp=6, maxp=24, likelihood=0) class RapidFireMode(GameMode): """Many roles that lead to multiple chain deaths.""" d...
4811814
from functools import wraps def get_list(function): """ 列表页面 获取 搜索 :param function: self.model :return: """ @wraps(function) def wrapped(self): # user = self.request.user # groups = [x['name'] for x in self.request.user.groups.values()] # request_type = self.reque...
4811836
import csv import xml import xml.etree.ElementTree as ET from datetime import datetime import logging logger = logging.getLogger(__name__) from holdings.dto import base ################################### Class Definitions ####################################### class Report13FHR(base.SECForm): def __init__(se...
4811840
import numpy as np from sklearn.metrics.pairwise import euclidean_distances from scipy.sparse import coo_matrix def squared_distances(X1, X2, L=None): if L is None: dist = euclidean_distances(X1, X2, squared=True) else: dist = euclidean_distances(X1.dot(L.T), X2.dot(L.T), squared=True) r...
4811874
from django.utils import timezone from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.utils import formats from django.db.models import ( Model, CharField, DateTimeField, ForeignKey, CASCADE, PositiveI...
4811876
import sys, unittest from tools import SamplesTestCase OUTPUT_HELLO_FUNCS = '''\ Hello: mult Hello: fact ''' class TestHelloPassPlugin(SamplesTestCase): def test_hello_on_fact(self): self.assertOptPluginOutput('hello_pass.so', ['-hello-funcs'], 'fact.ll', OUTPUT_HELLO_FUNCS) if __name__ == '_...
4811878
from repose.fields import * class TimePattern(String): """ :class:`Field` subclass for Philips Hue time pattern. Details can be found in the `Philips Hue Documentation <http://www.developers.meethue.com/documentation/datatypes-and-time-patterns>`_. .. todo:: The :class:`TimePattern` field needs impl...
4811926
import numpy N, M = map(int, input().split()) A = numpy.array([input().split() for _ in range(N)], int) print(numpy.prod(numpy.sum(A, axis=0), axis=0))
4811930
from django.template import Context from bluebottle.clients import properties class ClientContext(Context): """ A Context with builtin properties support. Mostly meant for rendering mail templates that don't get the ContextProcessor goodness """ def __init__(self, *args, **kw): super(C...
4811941
import pytest import re import numpy as np import pandas as pd from formulae.matrices import design_matrices from formulae.transforms import BSpline @pytest.fixture(scope="module") def data(): rng = np.random.default_rng(1234) size = 21 data = pd.DataFrame( {"seq": np.linspace(0, 1, 21), "x1": r...
4811962
from abc import abstractmethod, ABCMeta class Controller(object, metaclass=ABCMeta): @abstractmethod def initialize(self): pass @abstractmethod def act(self, observations, actions): pass @abstractmethod def train(self, rollouts, train_step): pass
4812002
from django.conf.urls import url from ..views.admin import AnnouncementAdminAPI urlpatterns = [ url(r"^announcement/?$", AnnouncementAdminAPI.as_view(), name="announcement_admin_api"), ]
4812022
from datetime import date def lambda_handler(event, context): today = str(date.today()) with open("holidays.txt") as datafile: if today in datafile.read(): return {"holiday": True} return {"holiday": False}
4812065
import pytest from pybetter.cli import process_file from pybetter.improvements import FixEqualsNone NO_CHANGES_MADE = None TRIVIAL_NONE_COMPARISON = ( """ if a == None: pass """, """ if a is None: pass """, ) NONE_IDENTITY_CHECK_IGNORED = ( """ if a is None: ...
4812074
import pytest from waterbutler.providers.figshare.path import FigsharePath class TestFigsharePath: def test_folder_path(self): path = FigsharePath('/folder/', _ids=('', '142132'), folder=True, is_public=False) assert path.identifier_path == '142132/' assert path.identifier == '142132' ...
4812134
import numpy.testing as test import numpy as np from unittest import TestCase from datetime import datetime from PyFVCOM.tide import * from PyFVCOM.utilities.time import date_range, make_signal from matplotlib.pyplot import * class TideTest(TestCase): def setUp(self): """ Make a set of data for the var...