id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3260640 | import operator
import itertools
import tempfile
import StringIO
import networkx as nx
from networkx.drawing.nx_agraph import write_dot
from IPython.display import display_svg #pylint: disable=import-error
from pbsmrtpipe.external_tools import dot_file_to_svg, dot_file_to_png
def _to_tmp_file(suffix):
t = tempfi... |
3260644 | from nmtwizard.preprocess.operators import align_perplexity_filter
from nmtwizard.preprocess.operators import alignment
from nmtwizard.preprocess.operators import identity_filter
from nmtwizard.preprocess.operators import length_filter
from nmtwizard.preprocess.operators import noise
from nmtwizard.preprocess.operators... |
3260666 | import csv
import numpy as np
import pandas as pd
IPC=pd.read_csv("%IPC3.csv")
IPC=IPC.rename(index=str, columns={"Unnamed: 0": "Dates"})
i=1
index=i
while i<len(IPC.index):
diff=(IPC.ix[i]-IPC.ix[i-1])
if not diff[1:len(diff)].any():
IPC=IPC.drop(str(index))
else:
i=i+1
index=index+1
print(IPC)
IPC.... |
3260669 | import tensorflow as tf
import numpy as np
import kovasznay_flow_problem
import neural_networks
import matplotlib.pyplot as plt
from matplotlib import rc
import sys, getopt
# python3 fd_eval.py -u 2 -p 1 -f test_model/v_2_p_1_layer_sq_loss_8000_float_64 -x 151 -y 201
def main(argv):
try:
opts, args = getopt.getop... |
3260699 | from flask import flash
import pandas as pd
import numpy as np
from pricing_engine.engine import (fx_rate,
price_ondate, fx_price_ondate, realtime_price,
historical_prices)
from datetime import datetime, timedelta
from dateutil.relativedelta import r... |
3260721 | import mock
import os
import neo.libs.vm
import neo.libs.image
import neo.libs.network
from neo.libs import lambdafunc
from neo.libs import utils
class TestLambdafunc:
def test_get_flavor_file_exists(self, fs):
flavor_contents = """ data:
- SX48.8
- SX48.12
"""
temp = util... |
3260729 | import sys, os
import glob
sys.path.append(os.path.join(os.getenv('XChemExplorer_DIR'),'lib'))
import XChemDB
def parse_autofit_folder(sampleDir,compoundID):
filenames = ['best.pdb','ligand_fit_1.pdb']
pdbList = []
for files in glob.glob(os.path.join(sampleDir,'autofit_ligand',compoundID+'_*','*'... |
3260735 | try:
from binaryninja import *
except:
print ("[!!] Not running in Binary Ninja")
try:
import r2pipe
except:
print ("[!!] Not running in Radare2")
from .analysis_engine import *
class ilVar(object):
def __hash__(self):
return self.var.__hash__()
def __eq__(self, other):
return... |
3260743 | import os
import time
import torch
import argparse
import matplotlib.pyplot as plt
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data.dataloader import DataLoader
from som import SOM
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if __nam... |
3260749 | from .Routine import optimizations as routine_optimizations
from .FontFeatures import optimizations as overall_optimizations
import fontFeatures
class Optimizer:
def __init__(self, ff):
self.ff = ff
def optimize(self, level=1):
for r in self.ff.routines:
self.optimize_routine(r, l... |
3260751 | from flask_classy import FlaskView, route
from test_flask_bouncer.models import Article
from flask_bouncer import requires
from bouncer.constants import *
class ArticleView(FlaskView):
# Used by Bouncer to know what object you are locking down
# if not explictly set if will try to deduce it from the class na... |
3260762 | from autotabular.pipeline.components.base import AutotabularPreprocessingAlgorithm
from autotabular.pipeline.constants import DENSE, INPUT, SPARSE, UNSIGNED_DATA
from ConfigSpace.configuration_space import ConfigurationSpace
class Densifier(AutotabularPreprocessingAlgorithm):
def __init__(self, random_state=None... |
3260774 | from unittest import mock
import fhirpipe.load.fhirstore as fhirstore
@mock.patch("fhirpipe.load.fhirstore.get_fhirstore", return_value=mock.Mock())
def test_save_many(_):
fhirstore.save_many(
[
{"name": "instance1", "value": 1},
{"name": "instance2", "value": 2},
{"na... |
3260833 | import pdb
import numpy as np
from scipy.optimize import (
check_grad,
fmin_cg,
fmin_ncg,
fmin_bfgs,
)
from sklearn.base import (
BaseEstimator,
TransformerMixin,
)
from sklearn.preprocessing import (
StandardScaler,
)
def square_dist(x1, x2=None):
"""If x1 is NxD and x2 is MxD (de... |
3260873 | import math
from functools import lru_cache
class Solution:
def connectTwoGroups(self, cost: List[List[int]]) -> int:
size1, size2 = len(cost), len(cost[0])
minCost2 = [min(cost[i][j] for i in range(size1)) for j in range(size2)]
@lru_cache(None)
def dfs(start, mask):
if ... |
3260923 | from django.contrib import admin
from .models import *
# Register your models here.
@admin.register(QuickNotifications)
class QuickNotificationsAdmin(admin.ModelAdmin):
list_display = ("message","read_status","created_by","created_at","updated_at")
|
3261015 | from os.path import basename, dirname
import bw2data
from bw2data.parameters import DatabaseParameter, ProjectParameter
from bw2io import BW2Package
import brightway2 as bw
from lca_algebraic import loadParams, error
from lca_algebraic.params import _listParams
__all__ = ['export_db', 'import_db']
def param_data(p... |
3261045 | from datetime import date, datetime
from flask import Blueprint, render_template, abort
from flask_babel import _
from flask_login import current_user
from sqlalchemy import desc
from app import db, cache
from app.models.activity import Activity
from app.models.news import News
from app.models.page import Page, PageR... |
3261050 | from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action, throttle_classes
from rest_framework.response import Response
f... |
3261060 | from django.conf.urls import url
from . import views
urlpatterns = [
# Examples:
# url(r'^$', 'testprogress.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', views.package_list, name='package_list'),
url(r'^add/$', view... |
3261109 | import io
import os
import pickle
import numpy as np
import torch
from PIL import Image
from learn2learn.vision.datasets import TieredImagenet
class TieredImageNet(TieredImagenet):
def __init__(self, root, partition="train", mode='coarse', transform=None, target_transform=None, download=False):
self.root... |
3261127 | from process_images import crop_objects
input = r'C:\data\woodknots\board_images_set2'
output = r'C:\data\woodknots\set2_res'
crop_objects(input, output) |
3261203 | import uvicorn
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import os
from heritageconnector import datastore, logging
this_path = os.path.dirname(__file__)
logger = logging.get_logger(__name__)
app = FastAPI()
app.mount(
"/static"... |
3261210 | def extractDragomirCM(item):
"""
# DragomirCM
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if not postfix and ':' in item['title']:
postfix = item['title'].split(':')[-1]
if 'Magic Academy' in item['tags'... |
3261223 | import diffractsim
diffractsim.set_backend("CPU")
from diffractsim import MonochromaticField,ApertureFromImage, nm, mm, cm,um, CircularAperture
zi = 50*cm # distance from the image plane to the lens
z0 = 50*cm # distance from the lens to the current position
M = -zi/z0 # magnification factor
radius = 6*mm
NA = radius ... |
3261238 | from django.db.models import Count
from common.models import Officer
from mobile.utils.cache_helper import get_or_set
from mobile.utils.collection_helper import safe_get
class OfficerDistributionService(object):
@staticmethod
def calculate_distribution():
allegations_count_distribution = list(Officer... |
3261247 | from flask import jsonify
from dao import WheelDao
from utils.network.exc import NotFoundException
wheel_dao = WheelDao()
def get():
wheels = wheel_dao.get_all()
return jsonify([wheel.to_dict() for wheel in wheels]), 200
def get_by_id(id: int):
"""
:param id: ID of the item (in-game item ID).
"... |
3261365 | from django.db import models
class FeedTimetable(models.Model):
feed = models.ForeignKey('Feed')
timetable_url = models.URLField()
fetch_last_modified = models.CharField(max_length=50, blank=True, null=True)
last_processed_zip = models.CharField(max_length=50, blank=True, null=True)
active = model... |
3261390 | import sys
char_ = None
def readchar_():
global char_
if char_ == None:
char_ = sys.stdin.read(1)
return char_
def skipchar():
global char_
char_ = None
return
def readchar():
out = readchar_()
skipchar()
return out
def stdinsep():
while True:
c = readchar_()
... |
3261468 | import re
from typing import Union
from main_dec import main
from pfun import Effect, Try, curry, error, files, success
class MalformedTomlError(Exception):
pass
class NoVersionMatchError(Exception):
pass
def get_version(toml: str) -> Try[MalformedTomlError, str]:
match = re.search(r'version = \"([0... |
3261486 | import base64
import ujson as json
import numpy as np
import os
import mmap
import codecs
def gzip_str(str):
return codecs.encode(str.encode('utf-8'), 'zlib')
# return gzip.compress(str.encode('utf-8'))
def gunzip_str(bytes):
return codecs.decode(bytes, 'zlib').decode('utf-8')
# return gzip.decompre... |
3261499 | import hail as hl
from data_pipeline.data_types.locus import normalized_contig
from data_pipeline.data_types.variant import variant_id
FILTER_NAMES = hl.dict(
{"artifact_prone_site": "Artifact-prone site", "indel_stack": "Indel stack", "npg": "No passing genotype"}
)
def nullify_nan(value):
return hl.cond(... |
3261516 | import numpy as np
from matplotlib import pyplot as plt
import torch, argparse, imageio
def save2img_rgb(img_data, img_fn):
plt.figure(figsize=(img_data.shape[1]/10., img_data.shape[0]/10.))
plt.axes([0, 0, 1, 1])
plt.imshow(img_data, )
plt.savefig(img_fn, facecolor='black', edgecolor='black', dpi=10)
... |
3261552 | from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import time
size = 100
class Compass(QWidget):
north = QPolygon([
QPoint(7, 0),
QPoint(-7, 0),
QPoint(0, -80)
])
south = QPolygon([
QPoint(7, 0),
QPoint(-7, 0),
QPoint(0, 80)
])
def _... |
3261553 | import logging
import math
import random
import audio
import org.threejs as three
from controls import Keyboard, ControlAxis
from units import Ship, Asteroid, Bullet
from utils import wrap, now, FPSCounter, coroutine, clamp, set_limits
DEBUG = True
logger = logging.getLogger('root')
logger.addHandler(logg... |
3261622 | from typing import Dict, Generator, Iterable, List, Union
from alteia.apis.provider import FeaturesServiceAPI
from alteia.core.resources.resource import Resource, ResourcesWithTotal
from alteia.core.resources.utils import search_generator
from alteia.core.utils.typing import ResourceId, SomeResourceIds, SomeResources
... |
3261654 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from model.config import cfg, cfg_from_list, cfg_from_file
from frcnn_demo import frcnn_demo
from sacred import Experiment
import os
import os.path as osp
ex = Experiment()
@ex.config
de... |
3261669 | import pytest
# jax imports
import jax
import jax.numpy as jnp
# crs imports
import cr.nimble as cnb
from cr.sparse.dsp import *
atol = 1e-6
rtol = 1e-6
def test_dct1():
for n in [4,8,16]:
for i in range(n):
print(n, i)
y = cnb.vec_unit(n, i)
a = dct(y)
x ... |
3261677 | import rospy
import sys
import tf
import tf2_ros
import geometry_msgs.msg
if __name__ == '__main__':
if len(sys.argv) < 8:
rospy.logerr('Invalid number of parameters\nusage: '
'./static_turtle_tf2_broadcaster.py '
'child_frame_name x y z roll pitch yaw')
sy... |
3261711 | import tensorwatch as tw
import torchvision.models
model_names = ['alexnet', 'resnet18', 'resnet34', 'resnet101', 'densenet121']
for model_name in model_names:
model = getattr(torchvision.models, model_name)()
model_stats = tw.ModelStats(model, [1, 3, 224, 224], clone_model=False)
print(f'{model_name}: f... |
3261714 | from marshmallow import Schema, fields
class ItemSchema(Schema):
description = fields.Str()
quantity = fields.Int()
amount = fields.Int()
additional_data = fields.Str(dump_to="additionalData")
expire = fields.Int()
class TransactionCreateRequestSchema(Schema):
external_unique_number = fields.S... |
3261727 | from __future__ import division, print_function, absolute_import
import math
from datetime import datetime
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from . import IPlanner
from .explorers.discrete import DiscreteExplorer
from ..tools.log import Loggi... |
3261749 | import os
from typing import Optional
import grpc
from crawlab.auth_token import get_auth_token_interceptor
from crawlab.entity.address import new_address_from_string, Address
from crawlab.grpc.services.model_base_service_pb2_grpc import ModelBaseServiceStub
from crawlab.grpc.services.model_delegate_pb2_grpc import M... |
3261767 | import sys,os,argparse,time
import numpy as np
import torch
import utils
from datetime import datetime
tstart=time.time()
# Arguments
parser=argparse.ArgumentParser(description='xxx')
parser.add_argument('--seed', default=0, type=int, help='(default=%(default)d)')
parser.add_argument('--d... |
3261775 | import os
from datetime import datetime
import logging
import random
import numpy as np
import pdb
import torch
def seed_all_rng(seed=None):
"""
Set the random seed for the RNG in torch, numpy and python.
Args:
seed (int): if None, will use a strong random seed.
"""
logger = logging.getLo... |
3261818 | import ssl
import asyncio
import websockets
import os
from typing import Optional, Dict
from enum import IntEnum
from athanor.app import Service
from athanor.shared import PortalOutMessageType
from athanor.shared import (
ServerInMessageType,
ServerInMessage,
ConnectionOutMessage,
ConnectionOutMessage... |
3261819 | import torch
import torch.nn as nn
import torch.nn.functional as F
from Models.BiDAF.wrapper import LSTM, Linear
from Models.base_model import BaseModel
from setting_keywords import KeyWordSettings
import torch_utils
import numpy as np
class BiDAF(BaseModel):
"""
BiDAF model (mainly copied from https://github... |
3261825 | import os
import boto3
DEFAULT_REGION = 'us-west-2'
DEFAULT_CLUSTER = 'minecraft'
DEFAULT_SERVICE = 'minecraft-server'
REGION = os.environ.get('REGION', DEFAULT_REGION)
CLUSTER = os.environ.get('CLUSTER', DEFAULT_CLUSTER)
SERVICE = os.environ.get('SERVICE', DEFAULT_SERVICE)
if REGION is None or CLUSTER is None or SE... |
3261829 | from django.conf.urls import re_path
from .views import (
speaker_create,
speaker_create_token,
speaker_edit,
speaker_create_staff,
)
urlpatterns = [
re_path(r"^create/$", speaker_create, name="speaker_create"),
re_path(
r"^create/(\w+)/$", speaker_create_token, name="speaker_create_tok... |
3261845 | import sublime
import sublime_plugin
import json
import os
from .gotools_util import Buffers
from .gotools_util import GoBuffers
from .gotools_util import Logger
from .gotools_util import ToolRunner
from .gotools_settings import GoToolsSettings
class GotoolsSuggestions(sublime_plugin.EventListener):
CLASS_SYMBOLS =... |
3261858 | import csv
import json
import random
from typing import Dict, List, Optional, Tuple
import torch
from transformers.tokenization_utils import PreTrainedTokenizerBase
def load_json_data(path: str) -> Tuple[List[str], List[List[str]], List[str]]:
"""Load dialogue summarization dataset json files of https://aihub.or... |
3261892 | import logging
import mariadb
import mysql.connector
from mysql.connector import errorcode
from clp_py_utils.clp_config import Database
class SQL_Adapter:
def __init__(self, database_config: Database):
self.database_config = database_config
def create_mysql_connection(self) -> mysql.connector.MySQL... |
3261900 | from __future__ import print_function
import cv2
import PIL.Image
import numpy as np
import scipy.stats
import sys
import itertools
from line_intersection import *
np.set_printoptions(suppress=True, precision=2)
def scaleImageIfNeeded(img, max_width=1024, max_height=1024):
"""Scale image down to max_width / max_heig... |
3261902 | import os
import re
import json
import copy
import cgi
import random
import string
import pytest
import responses
from urlobject import URLObject
from nylas import APIClient
# pylint: disable=redefined-outer-name,too-many-lines
#### HANDLING PAGINATION ####
# Currently, the Nylas API handles pagination poorly: API re... |
3261993 | from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union
if TYPE_CHECKING:
from aiomysql import Connection as MySQLConnection
from aiosqlite import Connection as SQLiteConnection
from asyncpg import Connection as PostgreSQLConnection
from migri.elements import Query
from migri.utils import Echo
... |
3262010 | import re
import pytest
from scrapli.driver.core.arista_eos.base_driver import PRIVS
from scrapli.exceptions import ScrapliPrivilegeError, ScrapliValueError
@pytest.mark.parametrize(
"priv_pattern",
[
("exec", "localhost>"),
("exec", "localhost(something)>"),
("exec", "localhost(some... |
3262030 | import os, sys
import logging, traceback
grey = "\x1b[38;21m"
green = "\x1b[32;21m"
yellow = "\x1b[33;21m"
red = "\x1b[31;21m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
prefix = "[Atlas] "
class ColorFormatter(logging.Formatter):
def __init__(
self,
format="%(asctime)s - %(name)s - %(levelname)... |
3262060 | from setuptools import setup
name = 'module2'
__version__ = ''
exec(open('pack2/_version.py').read())
setup(name=name, version=__version__, packages=['pack2'])
|
3262066 | import unittest
from zen import *
class AllPairsUWShortestPathLength_TestCase(unittest.TestCase):
def test_apdp_undirected(self):
G = Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(2,4)
D = all_pairs_shortest_path_length_(G)
self.assertEqual(D[0,0],0)
self.assertEqual(D[0,1],1)
self.asser... |
3262183 | import os
import sys
import shutil
import warnings
import pickle
from collections import OrderedDict
import torch
from tensorboardX import SummaryWriter
def set_tb_logger(log_dir, exp_name, resume):
""" Set up tensorboard logger"""
log_dir = log_dir + '/' + exp_name
# remove previous log with the same ... |
3262229 | import asyncio
import json
import pytest
from signalwire.tests import AsyncMock
async def _fire(calling, notification):
calling.notification_handler(notification)
@pytest.mark.asyncio
async def test_wait_for_ringing(relay_call):
relay_call.calling.client.execute = AsyncMock()
payload = json.loads('{"event_type"... |
3262235 | import clify
import argparse
import numpy as np
from dps.config import DEFAULT_CONFIG
from dps.projects.nips_2018 import envs
from dps.projects.nips_2018.algs import yolo_math_config as alg_config
parser = argparse.ArgumentParser()
parser.add_argument("kind", choices="long med".split())
parser.add_argument("size", ... |
3262283 | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="paragon",
version="1.0.0",
author="<NAME>",
author_email="<EMAIL>",
description=("A tiny command line benchmarking utility"),
long_descri... |
3262290 | from json import loads
from unittest.mock import patch
from django.shortcuts import resolve_url
from django.test import TestCase
from model_bakery import baker as mommy
from model_mommy.recipe import Recipe
from pyjobs.api.views import JobResource
from pyjobs.core.models import *
from pyjobs.api.models import ApiKey
... |
3262335 | import json
import pytest
from django.contrib.auth.models import Group
from guardian.shortcuts import assign_perm
from rest_framework.test import APIClient, APITestCase
from config.settings import base
from metaci.api import urls
from metaci.conftest import (
BranchFactory,
BuildFactory,
BuildFlowFactory,... |
3262343 | from ctypes import HRESULT, POINTER
from ctypes.wintypes import DWORD, LPCWSTR, LPWSTR, UINT
from comtypes import COMMETHOD, GUID, IUnknown
from .depend import IPropertyStore
class IMMDevice(IUnknown):
_iid_ = GUID('{D666063F-1587-4E43-81F1-B948E807363F}')
_methods_ = (
# HRESULT Activate(
#... |
3262355 | import logging
import multiprocessing
import unicodedata
from argparse import Namespace
from contextlib import closing
from itertools import chain, repeat
from multiprocessing.pool import Pool
from tqdm import tqdm
from transformers.tokenization_roberta import RobertaTokenizer
logger = logging.getLogger(__name__)
c... |
3262375 | import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
# Convert the data to tidy format
def convert_data(df, col_name, col_nn, col_arima, col_avg):
column_names = ['Week', 'Model', col_name]
graph_df = pd.DataFrame(columns=column_names)
for... |
3262382 | from __future__ import absolute_import
input_name = '../examples/diffusion/poisson_neumann.py'
output_name = 'test_poisson_neumann.vtk'
from tests_basic import TestInput
class Test(TestInput):
pass
|
3262395 | import time
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import TimeoutException
def kill_virtual_display(self, display):
'''Kills virtual display created by ``pyvirtualdisplay.Display()``
Args:
display (pyvirtualdisplay.Display): display to k... |
3262429 | from .movie_dict import *
from .database import *
from .dialog_manager import *
from .dict_reader import *
|
3262432 | import sys
import os
import numpy as np
sys.path.append(os.path.abspath('../'))
from utils.probability_utils import Hujie_uncertainty_reader as unc_reader
from utils.kitti_utils import save_kitti_format
from utils.calibration import Calibration
from utils.simple_stats import get_dirs
data_dir = '/mnt/d/Berkel... |
3262475 | from __future__ import annotations
import ast
from functools import partial
from typing import Sequence
from flake8_pie.base import Error
def _has_dataclass_like_body(body: Sequence[ast.stmt]) -> bool:
"""
Has at least one dataclass like assignment stmt and doesn't have any
methods besides __init__.
... |
3262477 | import numpy as np
from scipy.special import roots_legendre
class Contour():
def __init__(self, emin, emax=0.0):
self.emin=emin
self.emax=emax
def build_path_semicircle(self, npoints, endpoint=True):
R= (self.emax-self.emin)/2.0
R0= (self.emin+self.emax)/2.0
phi=np.lins... |
3262491 | from rest_pandas import (
PandasView, PandasUnstackedSerializer, PandasScatterSerializer,
PandasBoxplotSerializer,
)
from .serializers import EventResultSerializer
from .filters import ChartFilterBackend
import swapper
EventResult = swapper.load_model('results', 'EventResult')
class ChartView(PandasView):
... |
3262510 | from io import StringIO
from contextlib import redirect_stdout, redirect_stderr
import pandas as pd
from seq2science.util import dense_samples
with open(str(snakemake.log), "w") as f:
with redirect_stdout(f), redirect_stderr(f):
counts = pd.read_table(snakemake.input[0], comment="#", index_col=0)
... |
3262533 | def rank(names, weights, n):
if not names:
return 'No participants'
scores = []
for i, (name, weight) in enumerate(zip(names.split(','), weights), 1):
current_rank = sum(1 + ord(a) - 64 for a in name.upper()) * weight
scores.append((current_rank, name))
else:
if n > i:
... |
3262541 | import sys
import os
import unittest
import numpy as np
from astropy.coordinates import SkyCoord
from astropy import units as u
import MulensModel as mm
SAMPLE_FILE_01 = os.path.join(
mm.DATA_PATH, "photometry_files", "OB08092", "phot_ob08092_O4.dat")
def test_file_read():
"""read sample file and check if... |
3262554 | import pytest, pandas
from peopleanalyticsdata.peopleanalyticsdata import list_sets, charity_donation, employee_survey, health_insurance, job_retention, managers, politics_survey, salespeople, soccer, sociological_data, speed_dating, ugtests, employee_performance, learning, graduates, promotion, recruiting
def test_s... |
3262598 | from spacy.matcher import Matcher, PhraseMatcher
from .regex_matcher import RegexMatcher
from .base_rule import BaseRule
from spacy.tokens import Span
class MedspacyMatcher:
"""MedspacyMatcher is a class which combines spaCy's Matcher and PhraseMatcher classes
along with medspaCy's RegexMatcher and acts as o... |
3262628 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import pytest
import numpy as np
@pytest.fixture(scope="session", autouse=True)
def depth():
return np.arange(10)
@pytest.fixture(scope='session')
def pseudo_las_file(tmpdir_factory):
fn = tmpdir_fac... |
3262645 | for testcase in range(int(input())):
n,p = list(map(int, input().strip().split()))
i = 0
i = (n//2)+1
x = n%i
count = 0
if(n==p):
for j in range(x+1,p+1):
y = x%j
for k in range(y+1,p+1):
count += 1
#print((i,j,k),(n%i%j%k%n))
print(count)
elif(p>n):
oldi = i
co... |
3262658 | from .artifact.base import ArtifactRepository
from .dataset.base import DatasetRepository
from .metadata.base import MetadataRepository
__all__ = ['ArtifactRepository', 'MetadataRepository', 'DatasetRepository']
|
3262664 | import argparse
from model import GIN
parser = argparse.ArgumentParser(description='Artificial data experiments (2d data embedded in 10d) with GIN.')
parser.add_argument('--n_clusters', type=int, default=5,
help='Number of components in gaussian mixture (default 5)')
parser.add_argument('--n_data_p... |
3262674 | import quickproxy
import os
import fnmatch
import devdns
from tornado import ioloop
from copy import copy
__all__ = ['run', 'configure']
routes = []
def split_host(host):
name = ''
port = None
parts = host.split(':')
if len(parts) > 1:
name = parts[0]
try:
port = int(parts[-1]... |
3262742 | import json
import igraph as ig
class PgParser(object):
def __init__(self):
pass
def parse(self, pg_json):
# re-id the graph since igraph only support continous indexing from 0-N
self.re_id_(pg_json)
edges = []
for e in pg_json["edges"]:
edges.append( (e[... |
3262781 | import unittest
from ee_extra import translate
class Test(unittest.TestCase):
"""Tests translate package"""
def test_plus_sign01(self):
"""Test translation of plus sign"""
text = """
// Create arbitrary constant images.
var constant1 = ee.Image(1);
var constant2 = ee.... |
3262787 | import torch
import torch.nn as nn
from .module import Features
from .task import Locate_Entity
from .dataset import text2bert
class Net(nn.Module):
def __init__(self,
vocab_size,
embedding_dim=256,
num_layers=3,
hidden_dim=256,
... |
3262807 | import factory.fuzzy
from protocols.util.dependency_manager import VERSION_300
from protocols.reports_3_0_0 import (
CancerParticipant,
CancerSample,
ReportedVariantCancer,
ReportEventCancer,
Actions,
CancerInterpretationRequest,
VersionControl,
CancerDemographics,
ConsentStatus,
... |
3262831 | import torch
import torch.nn as nn
import pandas as pd
from torch.distributions.normal import Normal
from scipy.stats import multivariate_normal
from debug import ipsh
class VAE(nn.Module):
def __init__(self, encoder_layer_sizes, latent_size, decoder_layer_sizes,
conditional=False, attr_type=Fal... |
3262855 | import os
import pytest
import fiona
from click.testing import CliRunner
from fiona.fio.main import main_group
def create_sample_data(filename, driver, **extra_meta):
meta = {
'driver': driver,
'schema': {
'geometry': 'Point',
'properties': {}
}
}
meta.update... |
3262884 | from app import cli
from app import auth
from app import vars
from app import events
from app.filesystem import cfg
def client():
if(auth.token(cfg['token'])):
auth.loop.create_task(vars.client.start(cfg['token']))
else:
cli.tokenError('client')
exit() |
3262909 | import sys
import torchpruner
import torchpruner.model_tools as model_tools
import torchvision
import torch
import torch.nn as nn
# model creator, the input shape, prune_modules
models = {
# "faster_rcnn": (torchvision.models.detection.fasterrcnn_resnet50_fpn,(1,3,300,400),
# [('self.backbone.body.l... |
3262910 | import pandas as pd
import numpy as np
import json
import glob
from IPython import embed
import sys
from collections import defaultdict
import collections
def highlight_best_with_std(df, larger_is_better_dict, top=2):
""" actually operates on dataframes
here, takes df with mean (to determine best), and o... |
3262915 | import numpy as np
import scipy.sparse as sparse
from tqdm import tqdm
def compute_normals(vertices, faces):
"""
Compute normals of a triangular mesh
Parameters
-----------------------------
vertices : (n,3) array of vertices coordinates
faces : (m,3) array of vertex indices defining face... |
3262920 | from django.conf import settings
from django.core.checks import Error, Tags, register
def register_checks():
register(Tags.compatibility)(check_requirements)
def check_requirements(app_configs, **kwargs):
errors = []
if getattr(settings, 'NEXUS_SKIP_INSTALLED_APPS_REQUIREMENTS', False):
reqs = ... |
3262924 | import argparse
import json
import os
import sys
_PRESET_EXTENSIONS = (".json",)
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
class SettingsLoader(object):
"""
SettingsLoader class.
SettingsLoader loads BuildMigrator settings from presets.
BuildMigrator settings is a dictionary of argu... |
3263019 | from .base import ObjectBase
from .list import ObjectList
class Customer(ObjectBase):
@classmethod
def get_resource_class(cls, client):
from ..resources.customers import Customers
return Customers(client)
@property
def id(self):
return self._get_property("id")
@property
... |
3263041 | import unittest
from gouda.strategies.roi.rect import Coordinates, Point, Rect
class TestCoordinates(unittest.TestCase):
def test_comparison(self):
self.assertEqual(Coordinates(1, 2, 3, 4), Coordinates(1, 2, 3, 4))
self.assertNotEqual(Coordinates(1, 2, 3, 4), Coordinates(-1, 2, 3, 4))
class Tes... |
3263074 | def minPlatform(n, arr, dep):
arr.sort()
dep.sort()
plat_needed = 1
result = 1
i = 1
j = 0
while (i < n and j < n):
if (arr[i] <= dep[j]):
plat_needed+= 1
i+= 1
elif (arr[i] > dep[j]):
plat_needed-= 1
j+= 1
if (plat_need... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.