id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1781382 | import pytest
import ray
import tensorflow as tf
from garage.envs import GymEnv
from garage.experiment import deterministic
from garage.np.baselines import LinearFeatureBaseline
from garage.sampler import LocalSampler, RaySampler
from garage.tf.algos import VPG
from garage.tf.plotter import Plotter
from garage.tf.poli... |
1781384 | import bpy
from .road import Road
from .road_props import RoadProperty
class BTOOLS_OT_add_road(bpy.types.Operator):
"""Create road"""
bl_idname = "btools.add_road"
bl_label = "Add Road"
bl_options = {"REGISTER", "UNDO", "PRESET"}
props: bpy.props.PointerProperty(type=RoadProperty)
@classm... |
1781405 | EXPOSABLE_FIELDS = [
'case_type',
'created_date',
'creator',
'id',
'moderator',
'requestor',
'updated_date',
]
|
1781406 | import json
import re
from pathlib import Path
from botoy import GroupMsg, S, jconfig, logger
from ..bot_Setu.database import getGroupConfig
from ..bot_Setu.model import GroupConfig
curFileDir = Path(__file__).absolute().parent # 当前文件路径
class CMD:
def __init__(self, ctx: GroupMsg):
self.ctx = ctx
... |
1781407 | import mock
import requests
from django.test import TestCase
from django.contrib.auth import get_user_model
from apps.newsletter.models import NewsletterSubscription
from django.conf import settings
from apps.newsletter.tasks import retry_mailing_list
User = get_user_model()
class CustomResponse:
def __init__(... |
1781424 | import numpy as np
import tensorflow as tf
from .Layer import Layer
class Conv2D(Layer):
def __init__(self,
input_dim=None,
kernel_size=(3, 3, 20),
strides=(1, 1),
padding='same',
initializer='glorot_uniform',
re... |
1781455 | import datetime
from datetime import datetime
# imports for discord api
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
from discord.ext.commands import CommandNotFound
from discord.ext import tasks
# extras
import asyncio
import requests
import json
import pytz
from p... |
1781472 | from secml.ml.scalers.tests import CScalerTestCases
from sklearn.preprocessing import Normalizer
from secml.ml.scalers import CScalerNorm
class TestCScalerNorm(CScalerTestCases):
"""Unittests for CScalerNorm."""
def test_forward(self):
"""Test for `.forward()` method."""
for norm_type in ["... |
1781480 | from testdata import FAMILYHISTORY_FILE
import argparse
import csv
class FamilyHistory:
"""Create instances of FamilyHistory and maintain FamilyHistory lists by patient ID"""
familyHistories = {} # Dictionary of FamilyHistory lists by patient ID
@classmethod
def load(cls):
"""Loads patient f... |
1781533 | try:
from marshmallow import __version_info__
is_marshmallow_3 = __version_info__[0] >= 3 # type: ignore
except ImportError: # pragma: no cover
is_marshmallow_3 = False
def marshmallow_load_data(schema, data):
if is_marshmallow_3:
return schema().load(data)
else: # pragma: no cover
... |
1781535 | import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'very-secret-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'intercom'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'... |
1781577 | import filecmp
import os
import tempfile
import pytest
import modelkit.assets.cli
from modelkit.assets.manager import AssetsManager, _success_file_path
from modelkit.assets.remote import StorageProvider
from tests.conftest import skip_unless
test_path = os.path.dirname(os.path.realpath(__file__))
def _perform_mng_... |
1781604 | from .optaplanner_java_interop import ensure_init, _add_shallow_copy_to_class, _generate_planning_entity_class, \
_generate_problem_fact_class, _generate_planning_solution_class, _generate_constraint_provider_class, get_class
from jpype import JImplements, JOverride
from typing import Union, List, Callable, Type, A... |
1781611 | import unittest
from cloudbridge.base import helpers as cb_helpers
from cloudbridge.interfaces.exceptions import InvalidParamException
class BaseHelpersTestCase(unittest.TestCase):
_multiprocess_can_split_ = True
def test_cleanup_action_body_has_no_exception(self):
invoke_order = [""]
def ... |
1781615 | from .source import Source # isort:skip
from .config import Config, load_config
from .group import Group
|
1781623 | from .models import Project, Site
from onadata.apps.fsforms.models import FieldSightXF
def get_form_answer(site_id, meta):
fxf = FieldSightXF.objects.filter(pk=int(meta.get('form_id', "0")))
if fxf:
sub = fxf[0].project_form_instances.filter(site_id=site_id).order_by('-instance_id')[:1]
if sub:... |
1781635 | def main(request, response):
content = u""
if b"my-custom-header" in request.GET:
val = request.GET.first(b"my-custom-header")
response.headers.set(b"My-Custom-Header", val)
return content
|
1781670 | import numpy as np
import cv2
from scipy.interpolate import interpn
from scipy.ndimage import zoom
import matplotlib as mpl
mpl.use("Agg")
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
def plot_heatmap_img(batch_segm... |
1781692 | from git import Git
from .base import BaseOperation
class Inspector(BaseOperation):
"""
Used to introspect a Git repository.
"""
def merged_refs(self, skip=[]):
"""
Returns a list of remote refs that have been merged into the master
branch.
The "master" branch may h... |
1781725 | import json
from unittest.mock import patch
from federation.hostmeta.fetchers import (
fetch_nodeinfo_document, fetch_nodeinfo2_document, fetch_statisticsjson_document, fetch_mastodon_document,
fetch_matrix_document)
from federation.tests.fixtures.hostmeta import NODEINFO_WELL_KNOWN_BUGGY, NODEINFO_WELL_KNOWN_... |
1781756 | from __future__ import division
import json
import os
import copy
import collections
import argparse
import csv
import neuroglancer
import neuroglancer.cli
import numpy as np
class State(object):
def __init__(self, path):
self.path = path
self.body_labels = collections.OrderedDict()
def loa... |
1781785 | import pyasdf
import glob
import os
'''
this script finds the station pairs with stacked cross-correaltion missing one or several components
'''
STACKDIR = '/Users/chengxin/Documents/Harvard/Kanto_basin/Mesonet_BW/STACK1'
ALLFILES = glob.glob(os.path.join(STACKDIR,'*/*.h5'))
nfiles = len(ALLFILES)
ncomp = 17 ... |
1781796 | import scrapy
import js2py
import logging
from . import util
# spider for dealer.com templated websites
class BimmerDealercomSpider(scrapy.Spider):
name = 'bimmer_dealercom'
dealers = [
{
"name": '<NAME>MW',
"url": 'https://www.paulmillerbmw.com/new-inventory/index.htm?model=X3... |
1781856 | from datetime import datetime, timedelta
from ebedke.utils.date import on_workdays
from ebedke.utils.text import pattern_slice
from ebedke.utils import facebook
from ebedke.pluginmanager import EbedkePlugin
FB_PAGE = "https://www.facebook.com/pg/shakeratocaffe/posts/"
FB_ID = "151093992248397"
def fb_filter(post, t... |
1781889 | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
import re
from webfriend.scripting.environment import Environment
from webfriend.scripting.scope import Scope
from webfriend.scripting.execute import execute_script
from prompt_toolkit import prompt
from prompt_too... |
1781904 | from django.apps import AppConfig
class Class23Config(AppConfig):
name = 'tutorials.class_23'
|
1781925 | import torch
import torch.nn as nn
from .Layers3D import *
class DepthRegressor3D(nn.Module):
"""docstring for DepthRegressor3D"""
def __init__(self, nChannels = 128, nRegModules = 2, nRegFrames = 8, nJoints = 16, temporal=-1):
super(DepthRegressor3D, self).__init__()
self.nChannels = nChannels
self.nRegModule... |
1781939 | import torch
from einops import rearrange
def batched_index_select(values: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
"""
Params:
values: (1 or n_hashes, batch, seqlen, dim)
indices: (n_hashes, batch, seqlen)
Return:
(n_hashes, batch, seqlen, dim)
"""
last_dim = ... |
1781944 | from django.contrib import admin
from .models import DeliveryOptions
admin.site.register(DeliveryOptions)
|
1781987 | import os
import pathlib
import re
from urllib.parse import unquote, urlparse
RE_PATH_ANCHOR = r"^file://([^/]+|/[A-Z]:)"
def normalized_uri(root_dir):
"""Attempt to make an LSP rootUri from a ContentsManager root_dir
Special care must be taken around windows paths: the canonical form of
windows drives ... |
1781990 | from pygears.conf import reg
from pygears.core.intf import IntfOperPlugin
async def qiter(intf):
while True:
data = await intf.pull()
yield data
intf.ack()
if all(data.eot):
break
class gather:
def __init__(self, *din):
self.din = din
async def __a... |
1782031 | from ecommercetools.reports.reports import customers_report
from ecommercetools.reports.reports import transactions_report
|
1782041 | import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
X = np.loadtxt("embeddings");
# print(X[0])
labels = []
with open('labels') as output:
for line in output:
labels.append(line.split('resource/')[1].strip())
tsne = TSNE(n_components=2, random_state=0)
Y = tsne.fit_transform(X[:300... |
1782053 | from itertools import combinations
from math import cos, e, log, pi, sin, sqrt, tan
def prod_maker(lst, f):
hmm = [round(a) for a in lst if isinstance(a, (float, int))]
result = set()
print lst
print hmm
for a in xrange(2, len(hmm) + 1):
for b in combinations(hmm, a):
current =... |
1782079 | import matplotlib
matplotlib.use('Agg')
import PID
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline
P = 1.4
I = 1
D = 0.001
pid = PID.PID(P, I, D)
pid.SetPoint = 0.0
pid.setSampleTime(0.25) # a second
total_sampling = 100
sampling_i = 0
measurement = 0
feedback = ... |
1782081 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class deeplabv3plus(nn.Module):
def __init__(self, n_classes=21):
super(deeplabv3plus, self).__init__()
# Atrous Conv
self.xception_features = Xception()
# ASPP
rates = [1, 6, 12, 18]
... |
1782111 | from ReClassMap import *
r = Map("./MyClasses.reclass")
C = r.Class(name="Foo0")
C[0x00] = Int64(name="Bar0")
C[0x08] = Int32(name="Bar1")
C[0x0C] = Int16(name="Bar2")
C[0x0E] = Int8(name="Bar3")
C[0x0F] = Int8(name="Bar4")
C[0x20] = Pointer(classname="Foo1",name="pFoo1")
C = r.Class(name="Foo1")
C[0x00... |
1782136 | from __future__ import unicode_literals
import logging
from django.contrib import messages
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect
from django.utils.encoding import... |
1782162 | from .user_mode import UserModeDataset
from .user_mode_img import UserModeImgDataset
from .user_profile_mode import UserProfileModeDataset
|
1782178 | import typing as t
from enum import Enum
from functools import partial
from pathlib import Path
from .ini import load_ini_from_filepath
from .json import load_json_from_filepath
from .yaml import load_yaml_from_filepath
def load_from_filepath(filepath: t.Union[str, Path]) -> t.Any:
path = Path(filepath)
loa... |
1782180 | from src.data.orthofoto.other.user_agent import UserAgent
def test_user_agent_random():
user_agent = UserAgent()
assert len(user_agent.random) > 0
|
1782199 | import os
from datetime import datetime
from tqdm import tqdm
import pickle
import json
import numpy as np
import torch
def conceptgraph2id(
root='../data/conceptgraphEmbedding/TransE_l2_concetgraph_2/',
name1='entities', name2='relations', format=".tsv"):
'''
加载 conceptgraph中实体和关系及其对应的id
... |
1782247 | from datetime import datetime
import json
import six
import pytest
from urlobject import URLObject
from nylas.client.restful_models import Message
from nylas.utils import timestamp_from_dt
import pytz
@pytest.mark.usefixtures("mock_messages")
def test_messages(api_client):
message = api_client.messages.first()
... |
1782264 | import math
import numpy as np
# Data size variables
layer_counts = [2, 4]
char_counts = [1024, 4096]
text_input = "lstm_full.txt"
# Read from the full text file
def read_full_text(fn, char_count):
full_text_file = open(text_input, encoding="utf8")
full_text = full_text_file.read(char_count)
full_text_f... |
1782318 | import datetime
import uuid
import pytest
pytest.register_assert_rewrite("python_proto.tests.helpers")
from hypothesis import given
from hypothesis import strategies as st
from python_proto.common import Duration, Timestamp, Uuid
from python_proto.tests.helpers import check_encode_decode_invariant
from python_proto.... |
1782359 | import ocean
A = ocean.asTensor([1,2,3])
print(ocean.gpu[1](A))
print(ocean.gpu[1](A.storage))
print(ocean.gpu[0]([[1,2,3],[4,5,6.]]))
|
1782360 | import argparse
from gscripts.qtools import Submitter
class CommandLine(object):
def __init__(self, inOpts=None):
self.parser = parser = argparse.ArgumentParser(
description='Submit a job to the cluster which concatenates your '
'miso summary files together and creates... |
1782369 | from celery import Celery
import subprocess
from subprocess import Popen, PIPE
from flansible import api, app, celery, task_timeout
@celery.task(bind=True, soft_time_limit=task_timeout, time_limit=(task_timeout+10))
def do_long_running_task(self, cmd, type='Ansible'):
with app.app_context():
has... |
1782391 | results = { 1 :
[
[u"... is as sweet as can be. Perhaps sweeter than the cookies or ice cream.Here's the lowdown: Giant ice cream cookie <b>sandwiches</b> for super cheap. The flavor permutations are basically endless. I had snickerdoodle with cookies and cream ice ..."],
[u"... best BBQ Chicken pizza I have ever h... |
1782395 | from enum import Enum
class ConsensusStatus(Enum):
SUCCESS = 0
FAIL = 1
SKIP_ALLREDUCE = -1
class ConsensusMode(Enum):
PASSIVE = 0
ACTIVE = 1
|
1782397 | from os import path
class SettingObject:
TEMPLATE = path.realpath(path.dirname(__file__) + '/../..')
CONFIG_FILE = path.realpath(path.dirname(__file__) + '/../fixtures/cookiecutterrc')
def __init__(self, extra_context=None, output_dir=u'.', config_file=CONFIG_FILE):
self.template = SettingObject.T... |
1782423 | import numpy as np
from math import floor
def computeSecondOrderPolynomialFitting(x, dt, window_length):
assert dt > 0.0, "dt must be positive"
assert len(x.shape) == 2, "x must be a matrix"
assert window_length > 2, "window length must be at least 3"
assert window_length % 2 == 1, "window length must... |
1782493 | import logging
__author__ = '<EMAIL>'
logger_name = "glados_migration_log"
logger_format = "%(levelname)s:%(message)s"
mig_log = None
def setup_migration_logging(level=logging.INFO):
global logger_name
global logger_format
global mig_log
# Disables elastic search logging for false positive errors
... |
1782508 | import sys
class Logger(object):
""" Logger class. Writes errors and info to the cmd line. """
def __init__(self, verbose=False):
"""
Initialize a logger object.
Args:
verbose (boolean): If True, the logger will print all status
u... |
1782519 | from ara.settings import REDIS_HOST
CACHEOPS_REDIS = {
'host': REDIS_HOST,
'port': 6379,
'db': 1,
}
CACHEOPS = {
'core.Board': {'ops': {'get', 'fetch'}, 'timeout': 60*60},
'core.Topic': {'ops': {'get', 'fetch'}, 'timeout': 60*60},
'auth.User': {'ops': {'get'}, 'timeout': 60*10},
}
|
1782536 | from metagrok import np_json as json
from metagrok.fileio import to_fd
def load(fd_or_name):
return list(stream(fd_or_name))
def stream(fd_or_name):
with to_fd(fd_or_name) as fd:
for line in fd:
yield json.loads(line.strip())
def dump(fd_or_name, itr, dumps = json.dumps):
with to_fd(fd_or_name, 'w') ... |
1782543 | import os
import requests
from requests.auth import HTTPBasicAuth
import json
from pprint import pprint
import yaml
def import_variables_from_file():
my_variables_file=open('variables.yml', 'r')
my_variables_in_string=my_variables_file.read()
my_variables_in_yaml=yaml.load(my_variables_in_string)
my_va... |
1782572 | from . import constraint
from typing import List
class CartesianProduct(constraint.Constraint):
def __init__(self, segments: List[int], constraints: List[constraint.Constraint]):
"""
Construct a Cartesian product of constraints by providing a list of sets
and their dimensions as follows: ... |
1782577 | import collections
import contextlib
import glob
import os
import subprocess
import sys
import wave
import sox
import webrtcvad
from ekstep_data_pipelines.common.utils import get_logger
Logger = get_logger("Chunking Util")
class ChunkingConversionUtil:
re_chunking_aggressiveness = 3
@staticmethod
def g... |
1782587 | import errno
import os
import re
import shutil
import zipfile
from distutils import log
from distutils.errors import (
DistutilsInternalError,
DistutilsOptionError,
DistutilsSetupError,
)
from lambda_pkg_resources import LAMBDA_EXCLUDES, DistInstaller, ExcludesWorkingSet
from pkg_resources import WorkingSe... |
1782599 | import collections.abc
from types import SimpleNamespace, MappingProxyType
class _BaseSimpleNamespace(SimpleNamespace):
# Common methods for record and namespace
__slots__ = ()
_meta = property(lambda self: Meta(self))
def __repr__(self):
items = sorted(self.__dict__.items(), key=lambda x: x... |
1782620 | from ipyannotations import base
from unittest.mock import MagicMock
import ipywidgets
import pytest
ENTER_KEYUP = {"type": "keyup", "key": "Enter"}
ENTER_KEYDOWN = {"type": "keydown", "key": "Enter"}
BACKSPACE_KEYDOWN = {"type": "keyup", "key": "Backspace"}
class TestWidget(base.LabellingWidgetMixin, ipywidgets.VBo... |
1782622 | import geosoft.gxpy as gxpy
gxc = gxpy.gx.GXpy()
with gxpy.grid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid:
print('coordinate_system: ', grid.coordinate_system)
for x, y, z, v in grid:
if v is not None:
print(x, y, z, v)
|
1782642 | import shm
import numpy as np
from auv_math import quat
from control import vehicle
from control.thrusters import thrusters
from control.util import DOFSet
class ThrusterManager(object):
"""
Thruster Manager is an aide to the controller and simulator for
handling thrusters and other control related... |
1782655 | import asyncio
import functools
import sys
from greenlet import greenlet, getcurrent
class GreenletBridge:
def __init__(self):
self.bridge_greenlet = None
def run(self):
async def async_run():
gl = getcurrent().parent
coro = gl.switch()
while gl and coro !=... |
1782657 | import unittest
import os
from blotter import marketdata
from pandas.util.testing import assert_frame_equal
import pandas as pd
class TestMarketData(unittest.TestCase):
def assertDictOfFrames(self, dict1):
for key in dict1:
try:
assert isinstance(dict1[key], pd.DataFrame)
... |
1782667 | import os
import shutil
import json
import unittest
from lxml import etree
# import xml.etree.ElementTree as ET
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
MADE_DIR = os.path.join(DATA_DIR, "made")
import blockmodel
from blockmodel import BlockModel
def data_path(pth):
return os.path.join(DATA_DI... |
1782709 | import os
import json
from Interface import projectmgr
def getFileData(filePath):
data = ""
if os.path.exists(filePath):
with open(filePath, "r") as text_file:
data = text_file.read()
return data
def getJsonData(filePath):
data = {}
if os.path.exists(filePath):
with ope... |
1782740 | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import MinLengthValidator, MaxLengthValidator
from django_registration import validators
from django_registration.forms import RegistrationForm
class CustomRegistrat... |
1782814 | from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField, CompoundField
from sevenbridges.models.compound.jobs.job_instance_disk import Disk
class Instance(Resource):
"""
Instance resource contains information regarding the instance
on which the job was executed.
... |
1782864 | import FWCore.ParameterSet.Config as cms
l1RctValidation = cms.EDAnalyzer("L1RCTRelValAnalyzer",
rctRegionsLabel = cms.InputTag("rctDigis"),
rctEmCandsLabel = cms.InputTag("rctDigis")
)
|
1782866 | import pytest
@pytest.mark.django_db
async def test_get_template_by_name(app, aiohttp_client):
await aiohttp_client(app)
template_name = 'AccountActivation'
template = await app.m.email_template.get_by_name(template_name)
assert template is not None
@pytest.mark.django_db
async def test_get_translat... |
1782869 | from __future__ import print_function
from unittest import TestCase
from indexdigest.linters.linter_0164_empty_database import check_empty_database
from indexdigest.test import DatabaseTestMixin
class TestLinter(TestCase, DatabaseTestMixin):
def test_empty_database(self):
reports = list(check_empty_dat... |
1782884 | import mimic3benchmark.mimic3csv
import mimic3benchmark.subject
import mimic3benchmark.preprocessing
import mimic3benchmark.util
|
1782975 | import sys
sys.path.append('.')
import cfg
import async_session
while True:
sess = async_session.AsyncSession(cfg.timeout_read)
sess.open_session()
with sess.clone_session(community='woho') as priv_sess:
to_set = {
async_session.oid_str_to_tuple('1.3.6.1.2.1.1.6.0'): ('f', 's')
... |
1783003 | from ccsds.model.TCChannelCoding import CLTUEncoder
from ccsds.model.TCDataLinkPacket import TCDataLinkPacket, ControlCommandFlag, SegmentHeaderSequenceFlags
def test_tc_channel_coding_tc_datalink_packets():
"""
Test TC Channel Encoder encoding a datalink packet
:return:
"""
spacecraft_id = 1000
... |
1783019 | import requests
from bs4 import BeautifulSoup
page_result = requests.get('https://www.imdb.com/news/top?ref_=nv_nw_tp')
parse_obj = BeautifulSoup(page_result.content, 'html.parser')
top_news = parse_obj.find(class_='news-article__content')
top_news_a_content = top_news.find_all('a')
print(top_news_a_content)
|
1783022 | description = 'Instrument aperture'
group = 'lowlevel'
devices = dict(
aperture = device('nicos.devices.generic.ManualSwitch',
description = 'Instrument aperture L/D',
states = (185, 300, 700),
fmtstr = '%d',
),
)
|
1783042 | import hashlib
import struct
def sha1_hash32(data):
"""A 32-bit hash function based on SHA1.
Args:
data (bytes): the data to generate 32-bit integer hash from.
Returns:
int: an integer hash value that can be encoded using 32 bits.
"""
return struct.unpack('<I', hashlib.sha1(data).... |
1783056 | import os
import logging
import json
import urllib2
import datetime
import itertools
from ckan.common import _, c, request
from ckan.lib import helpers, i18n
from ckan.logic import get_action
from ckan import model
from ckan.plugins import toolkit
from ckanext.scheming.helpers import lang
from pylons import config
from... |
1783075 | from __future__ import unicode_literals
import logging
from mopidy import backend
from mopidy.models import Playlist
logger = logging.getLogger(__name__)
class SubsonicPlaylistsProvider(backend.PlaylistsProvider):
def __init__(self, *args, **kwargs):
super(SubsonicPlaylistsProvider, self).__init__(*arg... |
1783090 | import json
from enum import Enum
from functools import partial
from pickle import HIGHEST_PROTOCOL, dumps, loads
from typing import Any, Optional
try:
from redis import Redis
except ImportError:
Redis = None # type: ignore
try:
from aioredis import Redis as AioRedis
except ImportError:
AioRedis = No... |
1783112 | from operator import add
import numpy as np
import scipy.linalg as ln
import scipy.sparse as sp
# from pyspark import AccumulatorParam
from sklearn.decomposition import TruncatedSVD
from sklearn.utils.extmath import safe_sparse_dot
from ..base import SparkBroadcasterMixin
from ..rdd import DictRDD
from ..utils.valida... |
1783121 | from __future__ import absolute_import
import cv2
import numpy as np
import torch
import numbers
import torch
def real(img):
return img[..., 0]
def imag(img):
return img[..., 1]
def conj(img):
img = img.copy()
img[..., 1] = -img[..., 1]
return img
def fft2(img):
img = np.float32(img)
... |
1783136 | from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import json
import sys
from pathlib import Path
from io import StringIO
PREFIX = """
## Document Status
Work in Progress
## Well known API endpoints
This document summar... |
1783168 | from sixtypical.ast import Program
from sixtypical.model import RoutineType, VectorType
def find_routines_matching_type(program, type_):
"""Return the subset of routines of the program whose value
may be assigned to a location of the given type_ (typically
a vector)."""
return [r for r in program.rout... |
1783171 | import sys
# this script makes it possible to describe a model in one argument.
default_target = 'model=LGBM_feat=lgbmBest_categoricalThreVal=10000_validation=subm_params=-,gbdt,0.45,0.04,188,7,auc,20,5,0,70,76,binary,0,0,32.0,1.0,200000,1,0'
target = ''
def get_opt(name,default=None):
global target
if targe... |
1783178 | from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
app = QCoreApplication([])
for camera_info in QCameraInfo.availableCameras():
print('Camera: ', camera_info.deviceName())
camera = QCamera(camera_info)
r = QMediaRecorder(camera)
print('\tAudio Codecs: ', r.supportedAudioCodecs())
print('... |
1783291 | from setuptools import setup, find_packages
import sys
setup(name='qmap',
packages=[package for package in find_packages() if package.startswith('qmap')],
description="qmap",
author="<NAME>",
url='https://github.com/fabiopardo/qmap',
author_email="<EMAIL>",
version="0.1")
|
1783337 | import sys
sys.path.append("../")
import argparse
import math
import os
from ray import tune
from tqdm import tqdm
from beta_rec.core.train_engine import TrainEngine
from beta_rec.models.tvbr import TVBREngine
from beta_rec.utils.constants import MAX_N_UPDATE
from beta_rec.utils.monitor import Monitor
def parse_a... |
1783339 | import logging
import logger
import atexit
dataFd = None
errorFd = None
def writeToFile(session, container):
global dataFd, errorFd
try:
if (not session.failed) and (session.dataContainer.title is not None):
if dataFd is None:
dataFd = open('output.txt', 'w')
da... |
1783421 | from loader.redis import Redis
def running_jobs_count():
redis = Redis()
job_list_from_redis = redis.connect.lrange("running_jobs", 0, -1)
count = len(job_list_from_redis)
if count > 0:
return count
return None |
1783435 | from __future__ import print_function
import argparse
import os
import tensorflow as tf
import numpy as np
import time
from dataloader.load_SceneFlow import DataLoaderSceneFlow
from models.model import *
import cv2
#设置输入的参数
parser = argparse.ArgumentParser(description='PSMNet')
parser.add_argument('--maxdisp', type=i... |
1783444 | from __future__ import unicode_literals
class MogwaiException(Exception):
""" Generic Base Exception for Mogwai Library """
pass
class MogwaiConnectionError(MogwaiException):
""" Problem connecting with Titan """
pass
class MogwaiGraphMissingError(MogwaiException):
""" Graph with specified nam... |
1783449 | import os
import shutil
import unittest
import tempfile
import struct
from pyoram.storage.block_storage import \
BlockStorageTypeFactory
from pyoram.storage.block_storage_file import \
BlockStorageFile
from pyoram.storage.block_storage_mmap import \
BlockStorageMMap
from pyoram.storage.block_storage_ram ... |
1783453 | import torch
import pyro
from pyro.infer.util import torch_item
class OED:
def __init__(self, model, optim, loss, **kwargs):
self.model = model
self.optim = optim
self.loss = loss
super().__init__(**kwargs)
if not isinstance(optim, pyro.optim.PyroOptim):
raise... |
1783525 | from __future__ import print_function, division
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
from .vampnet import VampnetTools
from .utils import batch_pdist_pbc
def plot_timescales(predictions, lags, n_splits,
split_axis=0, time_unit_in_ns=1.):
"""
Plot ... |
1783528 | import os
from itertools import zip_longest
from pathlib import Path
from gopro_overlay import geo
from gopro_overlay.dimensions import Dimension
from gopro_overlay.ffmpeg import MetaMeta
from gopro_overlay.font import load_font
from gopro_overlay.framemeta import framemeta_from_datafile
from gopro_overlay.geo import ... |
1783697 | import logging
import flask_login
import mediacloud.error
from flask import jsonify, request
from operator import itemgetter
import server.views.apicache as shared_apicache
import server.views.topics.apicache as apicache
from server import app, mc, executor
from server.auth import user_mediacloud_key, user_mediacloud_... |
1783756 | def build_metric_learner_from_variant(variant, env, evaluation_data):
sampler_params = variant['sampler_params']
metric_learner_params = variant['metric_learner_params']
metric_learner_params.update({
'observation_shape': env.observation_space.shape,
'max_distance': sampler_params['kwargs'][... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.