id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
166250 | from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.template import RequestContext, loader
from django_translate.services import trans as _, transchoice
def hello(request):
return render_to_response("hello.html", context=RequestContext(request))
def apples(req... |
166277 | from data.types.pixel_coordinate_system import PixelCoordinateSystem
from data.types.bounding_box_format import BoundingBoxFormat
from data.types.bounding_box_coordinate_system import BoundingBoxCoordinateSystem
from data.types.pixel_definition import PixelDefinition
def _common_routine(bounding_box, image_size, boun... |
166316 | import FreeCAD
import FreeCADGui
from pivy import coin
import arch_texture_utils.faceset_utils as faceset_utils
class Light():
def __init__(self, obj):
obj.Proxy = self
self.setProperties(obj)
def setProperties(self, obj):
pl = obj.PropertiesList
if not 'Color' in pl:
... |
166319 | from packaging.version import parse as Version
import sys
import requests
def get_pypi_xmlrpc_client():
"""This is actually deprecated client."""
import xmlrpc.client
return xmlrpc.client.ServerProxy("https://pypi.python.org/pypi", use_datetime=True)
class PyPIClient:
def __init__(self, host="http... |
166349 | import numpy as np
import os
import math
import random
from argparse import ArgumentParser
from util.config import configure
from tqdm import tqdm
import renderer.randomize.scene_randomizer as sr
'''
This script creates a folder structure containing 'size' + 'testing_size' batches,
where each batch consists of a cer... |
166353 | import FWCore.ParameterSet.Config as cms
from L1TriggerConfig.L1GtConfigProducers.l1GtPrescaleFactorsTechTrig_cfi import *
#
L1GtPrescaleFactorsTechTrigRcdSource = cms.ESSource("EmptyESSource",
recordName = cms.string('L1GtPrescaleFactorsTechTrigRcd'),
iovIsRunNotTime = cms.bool(True),
firstValid = cms.vui... |
166373 | import traceback
import logging
import attr
from .. import entities, exceptions
logger = logging.getLogger(name=__name__)
@attr.s
class User(entities.BaseEntity):
"""
User entity
"""
created_at = attr.ib()
updated_at = attr.ib(repr=False)
name = attr.ib()
last_name = attr.ib()
userna... |
166379 | from datetime import timedelta
from .interchange import WaypointType
class ActivityStatisticCalculator:
ImplicitPauseTime = timedelta(minutes=1, seconds=5)
def CalculateDistance(act, startWpt=None, endWpt=None):
import math
dist = 0
altHold = None # seperate from the lastLoc variable,... |
166396 | from torch import nn
class Discriminator(nn.Module):
def __init__(self, hidden_size=512):
super(Discriminator,self).__init__()
self.model = nn.Sequential(
nn.Linear(hidden_size, hidden_size//2),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(hidden_size//2, 256),
nn.LeakyReLU(0.2, inplace=True),
nn.Li... |
166418 | import discord
from discord.ext import commands
from modules.economy import Economy
from modules.helpers import *
class GamblingHelpers(commands.Cog, name='General'):
def __init__(self, client: commands.Bot) -> None:
self.client = client
self.economy = Economy()
@commands.command(hidden=True)... |
166481 | from __future__ import absolute_import
from __future__ import print_function
from .fsm import reset
|
166498 | import sys
import pytest
import tempfile
import subprocess
from unittest import mock
from andriller import adb_conn
fake_adb = tempfile.NamedTemporaryFile()
@pytest.fixture
def ADB(mocker):
mocker.patch('andriller.adb_conn.ADBConn.kill')
mocker.patch('andriller.adb_conn.ADBConn._opt_use_capture', return_valu... |
166518 | import pytest
from insta_api.insta_api import InstaAPI
from insta_api.endpoints import *
@pytest.fixture(scope="module")
def insta():
insta = InstaAPI(use_cookies=False)
yield insta
insta._close_session()
class TestEndpoints:
""" These tests make sure that the API endpoints are still reachable and ... |
166547 | import cv2
import numpy as np
from PIL import Image
from PIL import ImageDraw
from subprocess import Popen, PIPE
import pycocotools.mask as coco_mask_util
def draw_bboxes(image, bboxes, labels=None, output_file=None, fill='red'):
"""
Draw bounding boxes on image.
Return image with drawings as BGR ndarray.... |
166607 | class Solution(object):
def alertNames(self, keyName, keyTime):
"""
:type keyName: List[str]
:type keyTime: List[str]
:rtype: List[str]
"""
mapp = {}
for i in range(len(keyName)):
name = keyName[i]
if(name not in mapp):
... |
166619 | from peewee import *
db = SqliteDatabase('course.db', check_same_thread=True)
class BaseModel(Model):
class Meta:
database = db
class GradeData(BaseModel):
semester = CharField(4)
course_no = TextField()
course_name = TextField()
grades = TextField()
total = IntegerField()
type =... |
166641 | from rest_framework import serializers
import ast
from pulpo_forms.fields import Validations, Dependencies, Option
class ValidationSerializer(serializers.Serializer):
"""
Serializer for the validations in the versions json
"""
max_len_text = serializers.IntegerField(required=False, allow_null=True)
... |
166643 | from xml.etree import ElementTree
class Parser:
def __init__(self, path):
self.entity_mentions = []
self.event_mentions = []
self.relation_mentions = []
self.parse_xml(path + '.apf.xml')
def parse_xml(self, xml_path):
tree = ElementTree.parse(xml_path)
root = t... |
166645 | from datetime import timedelta
import pytest
from .conf import TlsTestConf
class TestProxy:
@pytest.fixture(autouse=True, scope='class')
def _class_scope(self, env):
conf = TlsTestConf(env=env, extras={
'base': "LogLevel proxy:trace1 proxy_http:trace1 ssl:trace1",
env.domain... |
166657 | import numpy as np
import pandas as pd
from nilearn import image, input_data
from nilearn.datasets import load_mni152_brain_mask
def get_masker(mask_img=None, target_affine=None):
if isinstance(mask_img, input_data.NiftiMasker):
return mask_img
if mask_img is None:
mask_img = load_mni152_brai... |
166725 | from .settings import *
DATABASES['default']['USER'] = 'djangomigrator'
with open(BASE_DIR + '/_etc_passwords_djangomigrator.txt') as fp:
DATABASES['default']['PASSWORD'] = fp.read().strip()
|
166750 | import numpy as np
import cv2
import collections
import numbers
import random
import math
import copy
from up.data.datasets.transforms import Augmentation
from up.utils.general.registry_factory import AUGMENTATION_REGISTRY
@AUGMENTATION_REGISTRY.register('color_jitter_mmseg')
class RandomColorJitterMMSeg(Augmentatio... |
166762 | import torch
from torch import nn
from .utils import Conv, ConcatBlock
class PathAggregationNetwork(nn.Module):
def __init__(self, in_channels_list, depth):
super().__init__()
self.inner_blocks = nn.ModuleList()
self.layer_blocks = nn.ModuleList()
self.upsample_blocks = nn.ModuleL... |
166802 | import argparse
import pickle
import numpy as np
from numba import njit
@njit
def count_trees(tau, phi, order, traversal):
assert traversal == 'dfs' or traversal == 'bfs'
K = len(tau)
expected_colsum = np.ones(K)
expected_colsum[0] = 0
first_partial = np.copy(tau)
np.fill_diagonal(first_partial, 0)
firs... |
166811 | from .base import GenerativeAPS
from .fitter import GaussNewtonAPSFitter
from .algorithm import Inverse, Forward
|
166822 | import magma as m
from magma.testing.utils import has_warning, has_error
def _check_foo_interface(Foo):
assert list(Foo.interface.ports.keys()) == ["I", "O"]
assert isinstance(Foo.interface.ports["I"], m.Bit)
assert Foo.interface.ports["I"].is_output()
assert isinstance(Foo.interface.ports["O"], m.Bit... |
166823 | from tqdm import tqdm
def apply_with_progress_bar(desc=None):
def decorator(key_func):
def func_wrapper(iterable):
pbar = tqdm(total=len(iterable), desc=desc)
for obj in iterable:
pbar.update()
key_func(obj)
pbar.close()
return fu... |
166839 | from helpers import render_frames
from graphs.ForwardRendering import ForwardRendering as g
from falcor import *
g.unmarkOutput("ForwardLightingPass.motionVecs")
m.addGraph(g)
m.loadScene("grey_and_white_room/grey_and_white_room.fbx")
ctx = locals()
# default
render_frames(ctx, 'default', frames=[1,16,64,128,256])
e... |
166875 | import os
import os.path
import yaml
class Configuration:
def __init__(self):
self.path = os.path.dirname(__file__)
def get_liq_bands(self):
return self.__load_config(os.path.join(self.path,'liq_bands.yml'))
def get_trades_bands(self):
return self.__load_config(os.path.join(self.p... |
166901 | import pytest
from super_mario.base_pipeline import BasePipeline
from super_mario.decorators import process_pipe
from super_mario.exceptions import GlobalContextUpdateException
@pytest.fixture
def simple_pipeline():
class SimplePipeline(BasePipeline):
pipeline = [
'sum_numbers',
'... |
166912 | import py
import sys, struct
import ctypes
from pypy.rpython.lltypesystem import lltype, rffi, llmemory
from pypy.rpython.tool import rffi_platform
from pypy.rpython.lltypesystem.ll2ctypes import lltype2ctypes, ctypes2lltype
from pypy.rpython.lltypesystem.ll2ctypes import standard_c_lib
from pypy.rpython.lltypesystem.l... |
166945 | import unittest
from oeqa.sdk.case import OESDKTestCase
class PerlTest(OESDKTestCase):
@classmethod
def setUpClass(self):
if not (self.tc.hasHostPackage("nativesdk-perl") or
self.tc.hasHostPackage("perl-native")):
raise unittest.SkipTest("No perl package in the SDK")
de... |
166955 | from expungeservice.record_creator import RecordCreator
from expungeservice.models.record import Record
from tests.factories.case_factory import CaseFactory
def test_sort_by_case_date():
case1 = CaseFactory.create(case_number="1", date_location=["1/1/2018", "Multnomah"])
case2 = CaseFactory.create(case_number... |
166959 | import json
from onadata.apps.api.models import Team
from onadata.apps.api.tests.viewsets.test_abstract_viewset import\
TestAbstractViewSet
from onadata.apps.api.viewsets.team_viewset import TeamViewSet
class TestTeamViewSet(TestAbstractViewSet):
def setUp(self):
super(self.__class__, self).setUp()
... |
167002 | import turtle as t
tim = t.Turtle()
scr = t.Screen()
def move_forward():
tim.forward(10)
def move_backward():
tim.backward(10)
def clockwise():
tim.setheading(tim.heading() - 10)
def anticlockwise():
tim.setheading(tim.heading() + 10)
def clear():
tim.clear()
tim.penup()
tim.home(... |
167005 | import os.path, sys
from ctypes import *
from modules.windows_thumbnailcache.lib.olefile import olefile
from modules.windows_thumbnailcache.lib.yjSysUtils import *
#from lib.yjSQLite3 import TSQLite3
import base64, hashlib
def exit(exit_code, msg=None):
if debug_mode: exit_code = 0
if msg: print(msg)
sys.... |
167018 | class EvaluatorTestCases:
expressions = [
("1 2 + 2.5 * 2 5 SUM", 14.5, float, 3),
("1 2 3 SUM 4 5 SUM 6 7 SUM", sum(range(8)), int, 3),
("1 2 3 SUM 4 5 SUM 6 7 SUM 8.5 *", sum(range(8)) * 8.5, float, 4),
]
not_ok = [
"""
void test(){
int a; int b... |
167036 | import unittest
import pytest
from tfsnippet.utils import BaseRegistry, ClassRegistry
class RegistryTestCase(unittest.TestCase):
def test_base_registry(self):
a = object()
b = object()
# test not ignore case
r = BaseRegistry(ignore_case=False)
self.assertFalse(r.ignore_... |
167037 | import argparse
import torch.nn.functional as F
from .. import load_graph_data
from ..train import train_and_eval
from ..train import register_general_args
from .gat import GAT
def gat_model_fn(args, data):
heads = ([args.n_heads] * args.n_layers) + [args.n_out_heads]
return GAT(data.graph,
a... |
167076 | import random
import structlog
from shapely.geometry import Point
import matplotlib.pyplot as plt
from matplotlib import cm
from deepcomp.env.util.utility import log_utility, step_utility, linear_clipped_utility
from deepcomp.util.constants import MIN_UTILITY, MAX_UTILITY, SUPPORTED_UTILITIES
class User:
"""
... |
167099 | import torch.nn as nn
import torch.nn.functional as F
from fcdd.models.bases import FCDDNet
class FCDD_CNN224_VARK(FCDDNet):
def __init__(self, in_shape, k=3, **kwargs):
assert k % 2 == 1, 'kernel size needs to be uneven'
p = (k - 1) // 2
super().__init__(in_shape, **kwargs)
self.c... |
167126 | from hwt.hdl.constants import INTF_DIRECTION
from hwt.synthesizer.param import Param
from hwt.synthesizer.unit import Unit
class UnitWrapper(Unit):
"""
Class which creates wrapper around original unit instance,
original unit will be stored inside as subunit named baseUnit
:note: This is example of la... |
167146 | from ..responses import *
from ..utils import send_json, pop_args, byte_to_dict, get_user
from django.contrib.auth.models import User as Default_User
from ..models import User
from django.contrib.auth.hashers import make_password
from django.views import View
import sys
sys.path.append("../../")
import json
from Django... |
167156 | import numpy as np
from transonic import Array, const
from transonic.backends import backends
backend = backends["cython"]
type_formatter = backend.type_formatter
def compare(result, dtype, ndim, memview, mem_layout=None, positive_indices=None):
A = Array[dtype, ndim, memview, mem_layout, positive_indices]
... |
167157 | from collections import defaultdict
class Solution(object):
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if len(s1) != len(s2) or set(s1) != set(s2):
return False
if s1 == s2:
return True
if n... |
167168 | from citrination_client.data import DatasetFile
def test_can_crud_path():
"""
Tests that full get/set/delete functionality is
available for the path property
"""
path = "path"
d = DatasetFile(path)
assert d.path is path
d.path = path
assert d.path is path
del(d.path)
assert... |
167177 | import copy
import os
import torch
import torchvision
import warnings
import math
import utils.misc
import numpy as np
import os.path as osp
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import models.modified_resnet_cifar as modified_resnet_cifar
import models.modified_resnetmtl_cif... |
167178 | from typing import Dict, List
from pyhafas.profile.base.helper.date_time import BaseDateTimeHelper
from pyhafas.profile.base.helper.format_products_filter import \
BaseFormatProductsFilterHelper
from pyhafas.profile.base.helper.parse_leg import BaseParseLegHelper
from pyhafas.profile.base.helper.parse_lid import B... |
167236 | import logging
import sys
import sh
from kubeyard.commands.devel import BaseDevelCommand
logger = logging.getLogger(__name__)
class UpdateRequirementsCommand(BaseDevelCommand):
"""
Command can update requirements using `freeze_requirements` command in container.
Requirements: \n
- `freeze_requ... |
167244 | from typing import Optional
from tilecloud import BoundingPyramid, Tile
class InBoundingPyramid:
"""
Creates a filter that filters out tiles that are not in the specified bounding pyramid. When called the
filter returns ``None`` if the tile is not in the bounding pyramid.
bounding_pyramid:
... |
167256 | expected_output = {
"interface": {
"GigabitEthernet3.90": {
"interface": "GigabitEthernet3.90",
"neighbors": {
"FE80::5C00:40FF:FEFF:209": {
"age": "22",
"ip": "FE80::5C00:40FF:FEFF:209",
"link_layer_address"... |
167270 | import sys
import time
import argparse
import os
import warnings
import numpy as np
import torch
import torch.nn as nn
from collections import defaultdict
import pickle as pk
from torch.nn import Parameter
from layers import DNANodeRepModule, ConvNodeRepModule
from metrics import compute_mae, compute_mape, compute_ss... |
167312 | import paramiko, json, os
from kubernetes import client, config
from apps.common import static_value
from apps.common.utils import init_kubernetes
from apps.network_manager.api import NicApi
def get_master_server_info():
base_path = os.path.dirname(os.path.abspath(__file__))
with open(base_path+'/master_serv... |
167317 | import pytest
import globus_sdk
from tests.common import make_response
@pytest.fixture
def make_oauth_token_response():
"""
response with conveniently formatted names to help with iteration in tests
"""
def f(client=None):
return make_response(
response_class=globus_sdk.services.... |
167364 | from flask import Flask
app = Flask(__name__)
#app.config['CONFIG'] = None
from pbnh.app import views
|
167368 | from office365.runtime.client_value import ClientValue
class ChatMessageAttachment(ClientValue):
pass
|
167414 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginMan... |
167419 | import pandas as pd
waste_rates = pd.DataFrame({'High': [0, 0.1254, 0.1129, 0.1016, 0.0934, 0.0860, 0.0791, 0.0728, 0.0684, 0.0643, 0.0604,
0.0568, 0.0534, 0.0502, 0.0472, 0.0444, 0.0444, 0.0444, 0.0444, 0.0444, 0.0444],
'Medium': [0, 0.1777, 0.1599, 0.1... |
167425 | client_id="You need to fill this"
client_secret="You need to fill this"
user_agent="You need to fill this"
username="You need to fill this"
password="<PASSWORD>" |
167484 | import sys
import os
import torch
from torch import nn
sys.path.append(os.getcwd())
from unimodals.MVAE import MLPEncoder, TSEncoder, TSDecoder # noqa
from objective_functions.recon import elbo_loss, sigmloss1d # noqa
from training_structures.Supervised_Learning import train, test # noqa
from datasets.mimic.get_data i... |
167501 | import math
from collections import defaultdict
class IDFIndex(object):
finalized = False
def __init__(self):
self.idf_counts = defaultdict(int)
self.N = 0
def update(self, doc):
if self.finalized or not doc:
return
for feature, count in doc.iteritems():
... |
167502 | import unittest
from PEPit.examples.unconstrained_convex_minimization import wc_proximal_point
from PEPit.examples.composite_convex_minimization import wc_proximal_gradient
from PEPit.examples.unconstrained_convex_minimization import wc_gradient_exact_line_search
from PEPit.examples.unconstrained_convex_minimization i... |
167515 | import torch
import soft_renderer as sr
class NeuralRenderer(torch.nn.Module):
def __init__(self, img_size=256, camera_mode='look_at', orig_size=256, background=[0, 0, 0],
texture_type='surface', anti_aliasing=False, **kwargs):
super(NeuralRenderer, self).__init__()
self.camera_m... |
167528 | from __future__ import division
import sys
# set default encoding to utf-8
reload(sys)
sys.setdefaultencoding("utf-8")
|
167569 | import pyodbc
import pandas
# Define our Query to create the table.
create_table_query = """
-- Create the Table if it Does not exist.
IF Object_ID('youtube_videos') IS NULL
CREATE TABLE [sigma-coding].[dbo].[youtube_videos]
(
[video_id] NVARCHAR(MAX) NOT NULL,
[published_at] DATETIME NULL,
[channel_id] N... |
167592 | from mock import patch
import unittest
from esfdw.mapping_to_schema import generate_table_spec, generate_schema, TableSpec, ColumnSpec
class TestMappingToSchema(unittest.TestCase):
def test_generate_table_spec(self):
mapping = {
'index1': {
'mappings': {
'... |
167627 | import json
import os
import time
from datetime import datetime
def datetime_from_timestamp(unix_timestamp):
return datetime.fromtimestamp(int(unix_timestamp)).strftime("%Y-%m-%d %H:%M:%S")
def datetime_now():
return datetime_from_timestamp(time.time())
def load_json(file_name):
with open(file_name, "... |
167630 | def main():
import dtlpy as dl
project = dl.projects.get(project_name='Jungle')
dataset = project.datasets.get(dataset_name='Tigers')
converter = dl.Converter()
converter.convert_dataset(dataset=dataset, to_format='yolo',
local_path='home/yolo_annotations/tigers')... |
167643 | import numpy as np
import pdb
class ModelBranch:
def __init__(self, initialW, initialGrad):
print("initializing model")
self.chain = [[initialW, initialGrad]]
self.pendingGradients = []
self.gradientHistory = []
def updateModel(self):
### TODO:: Refactor out ###
... |
167649 | import os
import yaml
_RekallAPI = None
_RekallSessionAPI = None
def RekallAPI(current):
yaml_path = os.path.join(current.request.folder, "private", "api.yaml")
global _RekallAPI
if _RekallAPI is None:
_RekallAPI = {}
for desc in yaml.load(open(yaml_path).read()):
_RekallAPI[de... |
167656 | from magma import *
from mantle import *
from loam import Peripheral
#from .peripherals.fifo import FIFO
#from .peripherals.uart.tx import UARTTX
class USART(Peripheral):
name = 'usart'
IO = ["RX", In(Bit), "TX", Out(Bit)]
def __init__(self, fpga, name='usart0'):
super(USART,self).__init__(fpga, ... |
167667 | import numpy as np
from sklearn.utils import indexable
from sklearn.utils.validation import _num_samples
from sklearn.model_selection._split import _BaseKFold
from hypernets.utils import logging
logger = logging.get_logger(__name__)
class PrequentialSplit(_BaseKFold):
STRATEGY_PREQ_BLS = 'preq-bls'
STRATEGY_... |
167673 | from benchmark import *
import oneflow_benchmark
from flowvision.models.alexnet import alexnet
@oneflow_benchmark.ci_settings(compare={"median": "5%"})
def test_alexnet_batch_size1(benchmark, net=alexnet, input_shape=[1, 3, 224, 224]):
model, x, optimizer = fetch_args(net, input_shape)
benchmark(run, model, x... |
167674 | from datetime import datetime
import uuid
# Message class
class Message():
# Main initialiser
def __init__(self, title, body, from_id, from_name, to_id, to_name, id="", deleted=False, hidden_for_sender=False):
self.title = title
self.body = body
self.from_id = from_id
self.fro... |
167675 | from .forecaster import *
from .forecasterModel import *
from .cumulativeBoW import *
import sys
if 'torch' in sys.modules:
from .CRAFTModel import *
from .CRAFT import *
|
167742 | import random
from PIL import ImageOps, ImageEnhance, ImageFilter, Image
import torchvision.transforms as transforms
PARAMETER_MAX = 10 # What is the max 'level' a transform could be predicted
def int_parameter(level, maxval) -> int:
"""
A function to scale between zero to max val with casting to int
:p... |
167748 | from pygrank.algorithms.utils import MethodHasher, call, ensure_used_args, remove_used_args
from pygrank.core.signals import GraphSignal, to_signal, NodeRanking
from pygrank.core import backend, GraphSignalGraph, GraphSignalData
from typing import Union, Optional
class Postprocessor(NodeRanking):
def __init__(sel... |
167787 | import numpy as np
import random
from q1_softmax import softmax
from q2_sigmoid import sigmoid, sigmoid_grad
from q2_gradcheck import gradcheck_naive
def forward_backward_prop(data, labels, params, dimensions):
"""
Forward and backward propagation for a two-layer sigmoidal network
Compute the forwa... |
167794 | import numpy as np
import pykin.utils.transform_utils as t_utils
import pykin.utils.kin_utils as k_utils
import pykin.kinematics.jacobian as jac
from pykin.planners.planner import Planner
from pykin.utils.error_utils import OriValueError, CollisionError
from pykin.utils.kin_utils import ShellColors as sc, logging_ti... |
167799 | from time import sleep
from .core import Attempt, Question, TestCase
import pymongo
import random
def _attempt_checker(mongo_uri):
db = pymongo.MongoClient(mongo_uri)
db = db.openjudge
while True:
attempt = db.attempt_queue.find_one_and_delete({})
if attempt is None:
sleep(rand... |
167834 | from eager_core.engine_params import EngineParams
class GazeboEngine(EngineParams):
"""
Gazebo engine parameters for EAGER environments.
This class includes all settings available for the Gazebo physics engine.
:param world: A path to a Gazebo world (.world) file.
:param dt: The time step when :... |
167849 | import data_helper
import keras
import numpy as np
import defs
import precision_recall
import sys
import os
import shutil
import math
def sq_error(vector1, vector2):
if len(vector1) != len(vector2):
raise ValueError("vectors not of the same size")
return sum(math.pow(vector1[i] - vector2[i], 2) for i in range(... |
167864 | import ast
import logging
import six
import sys
TRUST_AST_TYPES = (ast.Call, ast.Module, ast.List, ast.Tuple, ast.Dict, ast.Name, ast.Num, ast.Str,
ast.Assign, ast.Load)
if sys.version_info[:2] == (3, 3):
TRUST_AST_TYPES = TRUST_AST_TYPES + (ast.Bytes,)
elif six.PY3:
TRUST_AST_TYPES = TRUS... |
167894 | from . import util, config
from datetime import date
import sys
import re
import requests
from pathlib import Path
import json
import boto3
import gzip
DefaultVersion = 'v2'
class StatIds:
Combined = 'combined'
MedianTripTimes = 'median-trip-times'
AllStatIds = [
StatIds.Combined,
StatIds.MedianTripT... |
167931 | from gzip import GzipFile
from exporters.readers import FSReader
from exporters.exceptions import ConfigurationError
from .utils import meta
import pytest
class FSReaderTest(object):
@classmethod
def setup_class(cls):
cls.options = {
'input': {
'dir': './tests/data/fs_re... |
167932 | import wikiquotes
import os
from time import sleep
from sys import argv
from sys import exit
from getpass import getpass
from random import randint
from PIL import Image, ImageDraw, ImageFont, ImageStat
wd = os.getcwd() # Get the working directory
def getInstagramFile(username):
"""
This function hand... |
167940 | import numpy as np
from configparser import SafeConfigParser
from pyfisher.lensInterface import lensNoise
import orphics.theory.gaussianCov as gcov
from orphics.theory.cosmology import Cosmology
import orphics.tools.io as io
cc = Cosmology(lmax=6000,pickling=True)
theory = cc.theory
# Read config
iniFile = "../pyfi... |
167996 | import subprocess
from os.path import join
from app import create_app
from flask import current_app
from flask.ext.script import Shell, Manager, Server
manager = Manager(create_app)
def _make_shell_context():
"""
Shell context: import helper objects here.
"""
return dict(app=current_app)
manager.ad... |
167997 | from yafs.action import generic_action
import logging
class my_custom_action(generic_action):
def __init__(self, *args, **kwargs):
super(my_custom_action, self).__init__(*args, **kwargs)
self.plates = {}
self.fees = {}
#mandatory function
def action(self,ma): #mobile_entity
... |
168002 | from __future__ import absolute_import
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from core.minisim.util.normalization import apply_normalization, get_state_statistics
from core.model import Model
from utils.... |
168007 | import argparse
from pathlib import Path
import tensorflow as tf
from keras import backend as K
from .network_definition import Colorization
from .training_utils import (
evaluation_pipeline,
checkpointing_system,
plot_evaluation,
metrics_system,
)
parser = argparse.ArgumentParser(description="Eval")... |
168027 | from pyradioconfig.parts.ocelot.calculators.calc_freq_offset_comp import CALC_Freq_Offset_Comp_ocelot
from pyradioconfig.parts.sol.calculators.calc_utilities import Calc_Utilities_Sol
class Calc_Freq_Offset_Comp_Sol(CALC_Freq_Offset_Comp_ocelot):
def calc_afc_scale_value(self, model):
# Overriding this fun... |
168031 | from traceback_with_variables import print_cur_tb # , format_cur_tb, iter_cur_tb_lines
def f(n):
print_cur_tb()
# cur_tb_str = format_cur_tb()
# cur_tb_lines = list(iter_cur_tb_lines())
return n + 1
def main():
f(10)
main()
|
168079 | import os
import sys
from pbstools import PythonJob
from shutil import copyfile
import datetime
import numpy as np
python_file = r"/home/jeromel/Documents/Projects/Deep2P/repos/deepinterpolation/examples/cluster_lib/generic_ephys_process_sync.py"
output_folder = "/allen/programs/braintv/workgroups/neuralcoding/Neurop... |
168097 | import numpy as np
from soco_openqa.soco_mrc.mrc_model import MrcModel
from collections import defaultdict
class Reader:
def __init__(self, model):
self.model_id = model
self.reader = MrcModel('us', n_gpu=1)
self.thresh = 0.8
def predict(self, query, top_passages):
batch ... |
168180 | import FWCore.ParameterSet.Config as cms
JetResolutionESProducer_AK4PFchs = cms.ESProducer("JetResolutionESProducer",
label = cms.string('AK4PFchs')
)
JetResolutionESProducer_SF_AK4PFchs = cms.ESProducer("JetResolutionScaleFactorESProducer",
label = cms.string('AK4PFchs')
)
|
168188 | import cv2
from geosolver.diagram.draw_on_image import draw_point, draw_instance, draw_label
from geosolver.ontology.ontology_semantics import evaluate
from geosolver.utils.prep import display_image
__author__ = 'minjoon'
class ImageSegment(object):
def __init__(self, segmented_image, sliced_image, binarized_se... |
168223 | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import gridspec
from kcsd import csd_profile as CSD
from kcsd import Validat... |
168229 | import factory
from faker import Faker
from src.association.tests.factories import ModelFactory
from src.customers.domain.entities import Customer
fake = Faker()
class CustomerFactory(ModelFactory):
class Meta:
model = Customer
user_id = factory.LazyAttribute(lambda _: fake.pyint(min_value=1, max_v... |
168320 | import neuralnet_pytorch.ext as ext
__all__ = ['batch_pairwise_dist']
batch_pairwise_dist = ext.bpd_forward
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.