id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11419397 | import datetime
import numpy as np
def seconds_to_time(seconds):
"""Convert seconds since midnight to a datetime.time"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return datetime.time(h, m, s)
def time_to_seconds(time):
"""Convert a datetime.time to seconds since midnight"""
if time is... |
11419456 | from ramda.tail import tail
from ramda.private.asserts import *
def tail_test():
assert_equal(tail([1, 2, 3]), [2, 3])
assert_equal(tail("abc"), "bc")
assert_equal(tail(""), "")
assert_equal(tail([]), [])
|
11419465 | from .algorithm import Algorithm, wrap_algorithm
from .io import disassemble_complex
from .filters import BoxcarFilter
from .utils import requires
try:
from . import _change
except ImportError:
_change = None
import numpy as np
import xarray as xr
__all__ = ['ChangeDetection', 'OmnibusTest', 'omnibus']
# --... |
11419466 | import os
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from projects.models import Project, ProjectLog
from .forms import ReportGeneratorForm
from .models import Report, ReportGenerator
from django.db.models import Q
from .hel... |
11419472 | from magma import *
IOBUF = DeclareCircuit("IOBUF", "T", In(Bit),
"I", In(Bit),
"IO", InOut(Bit),
"O", Out(Bit))
def IOB(**params):
iob = IOBUF(**params)
args = ["T", iob.T, "I", iob.I, "IO", iob.IO, "O", iob.O]
... |
11419599 | import pytest
import sys
import os
def test_using_numpy():
np = pytest.importorskip("numpy")
assert len(np.zeros(5)) == 5
@pytest.mark.skipif(sys.platform != 'win32', reason="windows only")
def test_windows():
assert os.path.exists('C:\\')
|
11419602 | import json
import os
import sys
import logging
import uuid
import datetime
from dateutil import parser as date_parse
from typing import List
from azure.core.paging import ItemPaged
from azure.keyvault.secrets import SecretClient
from azure.identity import ClientSecretCredential
from azure.graphrbac import GraphRbacMa... |
11419626 | import functools
from seq2annotation.utils import load_hook
from tokenizer_tools.tagset.converter.offset_to_biluo import offset_to_biluo
from tokenizer_tools.tagset.NER.BILUO import BILUOEncoderDecoder
def generator_func(data_generator_func, config, vocabulary_lookup, tag_lookup):
# load plugin
preprocess_ho... |
11419640 | from plenum.common.messages.node_messages import Batch, InstanceChange
def test_unpack_node_msg_with_str_as_msg_in_batch(create_node_and_not_start):
node = create_node_and_not_start
while node.nodeInBox:
node.nodeInBox.pop()
batch = Batch(['pi',
'{"op": "INSTANCE_CHANGE",'
... |
11419641 | import os
from collections import namedtuple
from .plugin_interface import TEST_FILE
PackageSpecification = namedtuple('PackageSpecification', ['parent_folder', 'package_name'])
ModuleSpecification = namedtuple('ModuleSpecification', ['parent_folder', 'module_name'])
def create_importer(folder, plugin_composite, ex... |
11419644 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import itertools
from ops import utils
from tensorflow.python.framework import ops as tf_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gradients_imp... |
11419646 | from loaders.data import Data
import utils.data_utils
import numpy as np
import logging
log = logging.getLogger('MultimodalPairedData')
class MultimodalPairedData(Data):
"""
Container for multimodal data of image pairs. These are concatenated at the channel dimension
"""
def __init__(self, images, mas... |
11419660 | import re
from terra_sdk.client.lcd import LCDClient
from terra_sdk.client.lcd.params import PaginationOptions
from terra_sdk.key.mnemonic import MnemonicKey
terra = LCDClient(
url="https://pisco-lcd.terra.dev/",
chain_id="pisco-1",
)
pagOpt = PaginationOptions(limit=1, count_total=True)
mk1 = MnemonicKey(
... |
11419675 | import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')
username = factory.LazyAttributeSequence(
lambda user, n: '{}{}_{}'.format(user.first_name, user.last_name, ... |
11419720 | import contextlib
import concurrent.futures
import os
import sys
import traceback
import typing
import itertools
from conducto.shared import (
async_utils,
client_utils,
types as t,
log,
)
import conducto
from . import dockerfile as dockerfile_mod, names
from conducto.shared import constants, imagepa... |
11419738 | from flask import request, url_for, redirect, abort, flash
from flask_login import login_required, current_user
from typing import List
from app import db
from app.main.views.utils import render_template_with_nav_info
from app.models import Corpus, User, Role, ControlLists, CorpusUser, ControlListsUser, WordToken
from... |
11419756 | import json
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
AWS_ACCESS_KEY = ''
AWS_SECRET_KEY = ''
AWS_REGION = '' #e.g. cn-northwest-1
#intance id and interface id e.g.{'id':'i-05b8bcda0f9e6aeee','server_interface':'eni-0937ac3ddbc376502'}
VSRX1 = {'id':'','server_interface... |
11419762 | import numpy as np
import pandas as pd
def create_drawdowns(pnl):
"""
Calculate the largest peak-to-trough drawdown of the PnL curve
as well as the duration of the drawdown. Requires that the
pnl_returns is a pandas Series.
Parameters:
pnl - A pandas Series representing period percentage ret... |
11419768 | from ..factory import Type
class supergroupMembersFilterSearch(Type):
query = None # type: "string"
|
11419786 | from array import array
import _util
def norm_square_array(vector):
norm = 0
for v in vector:
norm += v * v
return norm
def run_experiment(size, num_iter=3):
vector = array('l', range(size))
return _util.run(norm_square_array, vector, num_iter)
if __name__ == "__main__":
print run_ex... |
11419795 | import torch.nn as nn
from ..weights_init import weights_init_classifier, weights_init_kaiming
import copy
class PGFAReduction(nn.Module):
def __init__(self, cfg):
super(PGFAReduction, self).__init__()
self.cfg = cfg
global_block = [nn.Dropout(0.5)]
part_feat_block = [nn.Dropout(0... |
11419803 | class UnrecoverableException(Exception):
pass
class BaseBackend(object):
def __init__(self, app):
self.app = app
def create_job(self, job):
raise NotImplementedError
def sync_job(self, job):
raise NotImplementedError
def sync_step(self, step):
raise NotImplemente... |
11419804 | from .Layer import *
class Log(Layer):
def __init__(self, models, *args, **kwargs):
Layer.__init__(self, models, *args, **kwargs)
def reshape(self):
self.Y = np.zeros(self.X.shape)
def forward(self):
self.Y = np.log(self.X)
def backward(self):
self.dX = self.dY * (1.0 / ... |
11419807 | import numpy as np
import pytest
from kickscore.fitter import BatchFitter, RecursiveFitter
from kickscore.kernel import Matern32
from math import log, pi
KERNEL = Matern32(var=2.0, lscale=1.0)
# GPy code used to generate the ground-truth values.
#
# kernel = GPy.kern.Matern32(
# input_dim=1, varianc... |
11419828 | import json
from datetime import datetime
import pandas as pd
class WorkItem(object):
def __init__(self,
id,
title,
state,
type,
history,
date_created,
state_transitions=None,
c... |
11419830 | from imdb import IMDB
from pascal_voc import PascalVOC
from cityscape import CityScape
from coco import coco
|
11419888 | import os
import json
import responses
import re
import pytest
from fastapi.testclient import TestClient
from app import app
from idunn.api.directions import rate_limiter
from freezegun import freeze_time
from .utils import override_settings
@pytest.fixture
def mock_directions_car():
with override_settings(
... |
11419906 | import os
import numpy as np
import json
import cloudpickle as pickle
import logging
from pipeline_monitor import prometheus_monitor as monitor
from pipeline_logger import log
_logger = logging.getLogger('pipeline-logger')
_logger.setLevel(logging.INFO)
_logger_stream_handler = logging.StreamHandler()
_logger_stream_... |
11419910 | from prismriver.plugin.common import Plugin
from prismriver.struct import Song
class AlLyricsPlugin(Plugin):
ID = 'allyrics'
def __init__(self, config):
super(AlLyricsPlugin, self).__init__('AlLyrics.net', config)
def search_song(self, artist, title):
to_delete = ['!', '?', '.', ',', '('... |
11419964 | def powersetsum(arr, arr1, n):
if n == 0:
print(sum(arr1))
return
arr1.append(arr[n-1])
powersetsum(arr,arr1,n-1)
arr1.pop()
powersetsum(arr,arr1,n-1)
arr=[2, 3]
arr1 =[]
powersetsum(arr, arr1, len(arr)) |
11419980 | from ctypes import *
import time
import struct
class SFFMessage(Structure):
_fields_ = [("IDH", c_ubyte),
("IDL", c_ubyte),
("data", c_ubyte * 8),
("options", c_ubyte),
("DataLength", c_ubyte),
("TimeStamp", c_uint),
... |
11419983 | import pytest
import uvicore
from uvicore.typing import Dict, List
from uvicore.support.dumper import dump
# @pytest.mark.asyncio
# @pytest.fixture(scope="module")
# async def app1(app1):
# pass
@pytest.mark.asyncio
async def test1(app1):
"""Sync - String event, method handler, Dict payload"""
# Event ... |
11419984 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.twins_lungs import twins_lungs
def test_twins_lungs():
"""Test module twins_lungs.py by downloading
twins_lungs.csv and testing shape of
e... |
11419989 | import webapp2
import mimetypes
import os
import time
from datetime import datetime
import base64
_here = os.path.dirname(__file__)
USERNAME = 'foo'
PASSWORD = '<PASSWORD>'
def check_auth(auth):
encoded_auth = auth[1]
username_colon_pass = base64.b64decode(encoded_auth)
username, password = username_colon_pas... |
11419992 | import pylint_protobuf
from conftest import CheckerTestCase
class TestGroupFields(CheckerTestCase):
CHECKER_CLASS = pylint_protobuf.ProtobufDescriptorChecker
def test_nonrepeated_groups_are_like_nested_messages(self, proto_builder):
group_pb2 = proto_builder("""
message NonRepeatedGroup {... |
11420029 | from ... import base_optimizer as _base
class GradientDescent(_base.LineSearchOptimizer):
def __init__(self, f, grad, step_size, **kwargs):
super().__init__(f, grad, step_size, **kwargs)
def get_direction(self, x):
self._current_grad = self._grad(x)
return -self._current_grad
... |
11420054 | import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
Optional,
Type,
TypeVar,
Union,
overload,
)
from django.db.models.base import Model
from django.db.models.query import Prefetch
from typing_extensions import Self
from .utils.typing import TypeOrSe... |
11420124 | import os
from pathlib import Path
from unittest import TestCase
from pydbml import PyDBML
from pydbml.exceptions import ColumnNotFoundError
from pydbml.exceptions import TableNotFoundError
TEST_DATA_PATH = Path(os.path.abspath(__file__)).parent / 'test_data'
class TestParser(TestCase):
def setUp(self):
... |
11420198 | import torch
import torch.nn as nn
from torch.nn import init
import math
import numpy as np
from torch.nn.modules.module import Module
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
class deform_conv2d_naive(Module):
def __init__(self, in_channels, out_channels,
kernel_si... |
11420201 | import sys
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from argparse import ArgumentParser
from clair.utils import setup_environment
def plot_tensor(ofn, XArray):
plot = plt.figure(figsize=(15, 8))
plot_min = -30
plot_max = 30
plot_arr = [... |
11420232 | import logging
from abc import ABCMeta, abstractmethod
from typing import Any, Dict, Optional
import pytorch_lightning as pl
import torch
import torch.nn as nn
from omegaconf import DictConfig
from deep_table.nn.encoders.encoder import Encoder
logger = logging.getLogger(__name__)
class BaseModel(pl.LightningModule... |
11420262 | from contextlib import contextmanager
from selenium.common.exceptions import NoSuchWindowException
import nerodia
class AfterHooks(object):
"""
After hooks are blocks that run after certain browser events.
They are generally used to ensure application under test does not encounter
any error and are ... |
11420263 | from django.contrib import admin
# Register your models here.
from .models import Article
class ArticleAdmin(admin.ModelAdmin):
list_display = ["title", "slug", "is_published"]
raw_id_fields = ["user"]
list_filter = [
"publish_status",
"user_publish_timestamp",
"publish_timestamp"... |
11420268 | import asyncio
import ydb
import ydb.aio
import os
queries = [ # Tables description to create
"""
CREATE table `series` (
`series_id` Uint64,
`title` Utf8,
`series_info` Utf8,
`release_date` Date,
PRIMARY KEY (`series_id`)
)
""",
"""
CREATE table `seas... |
11420358 | from .automap import AutoMap
from .color import printc, highlight, colors
from .csvlogger import CSVLogger
from .online import OnlineStats, OnlineStatsMap
|
11420371 | def calculate_reward(self):
state_new = self.actionstate_curr['state']
terminate = False
is_pass = False
if state_new == self.invalid_state:
reward = float('-inf')
log_and_display('Penalty: Reached invalid state, terminating')
terminate = True
elif (ra.get_position(ra.cylin... |
11420378 | from .vg_caption_datamodule import VisualGenomeCaptionDataModule
from .f30k_caption_karpathy_datamodule import F30KCaptionKarpathyDataModule
from .coco_caption_karpathy_datamodule import CocoCaptionKarpathyDataModule
from .conceptual_caption_datamodule import ConceptualCaptionDataModule
from .sbu_datamodule import SBUC... |
11420416 | class Solution:
"""
@param: x: the base number
@param: n: the power number
@return: the result
"""
def myPow(self, x, n):
# write your code here
if (x == 0):
return 0
if (n == 0):
return 1
if (n == 1):
return x
if n <... |
11420509 | import numpy as np
import matplotlib.pyplot as plt
x = [50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
y_CNN_repro = [83.72, 79.49, 75.3, 71.42, 69.77, 66.51, 65.5, 63.41, 60.33, 59.73, 57.32]
y_CNN = [82, 80, 76, 71.5, 68.5, 66, 64.5, 62.5, 61, 58.5, 57.5]
y_NME_repro = [83.44, 79.16, 74.77, 69.94, 67.77, 64.32, 62.65... |
11420533 | import argparse
import os
import importlib
parser = argparse.ArgumentParser(description='Generate C files from ssot.')
parser.add_argument('module', help='the module to process')
parser.add_argument('cdir', help='the output C directory name')
parser.add_argument('hdir', help='the output header directory name')
args = ... |
11420568 | import qcfractal.interface as ptl
import json
import tarfile
# Build a client to the target server
client = ptl.FractalClient.from_file("localhost:7777")
# Unpack the data
with tarfile.open('stability_benchmark_inputs.tar.gz', 'r') as f:
td_inputs = json.load(f.extractfile('stability_benchmark_inputs.json'))
# F... |
11420583 | import numpy as np
import k3d
def generate():
np.random.seed(0)
x = np.random.randn(100,3).astype(np.float32)
plot = k3d.plot(name='points')
plt_points = k3d.points(positions=x, point_size=0.2, shader='3d')
plot += plt_points
plot.snapshot_type = 'inline'
return plot.get_snapshot()
|
11420615 | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
from graphviz import Digraph
df = pd.read_csv("datasets/flagssimilar.csv")
flags = pd.read_csv("datasets/countries.csv").split_columns('country', "|").explode('country').set_index('country')['flag']
g = Digraph('G', filename='cache/flagssimilar.gv', format... |
11420673 | import collections
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pathlib
from progress.bar import Bar
from rosbags import rosbag1
from rosbags.serde import ros1_to_cdr, deserialize_cdr
from typing import *
import warnings
from .base_dataset_generator import BaseDatasetGenerator
from src.en... |
11420681 | from .models import File
from .enums import Volume
def create_from_torrent(torrent):
"""
Creates file objects from transmission torrent object.
Returns list of file objects so we can use it for something
different purposes. For example: torrent.files.add(*files)
:param torrent: Transmission torre... |
11420724 | from multimetric.cls.base_calc import MetricBaseCalc
from multimetric.cls.metric.operators import MetricBaseOperator
from multimetric.cls.metric.operands import MetricBaseOperands
class MetricBaseCalcPylint(MetricBaseCalc):
METRIC_PYLINT = "pylint"
def __init__(self, args, **kwargs):
super().__init_... |
11420734 | from bluedot import BlueDot
from signal import pause
def bd1_pressed():
print("BlueDot 1 pressed")
def bd2_pressed():
print("BlueDot 2 pressed")
bd1 = BlueDot(port = 1)
bd2 = BlueDot(port = 2)
bd1.when_pressed = bd1_pressed
bd2.when_pressed = bd2_pressed
pause()
|
11420739 | import contextlib
import functools
import inspect
import multiprocessing as mp
import pickle
import sys
import threading
import time
import traceback
import types
from collections import defaultdict
from multiprocessing.pool import Pool
from multiprocessing.reduction import AbstractReducer
from queue import Empty
from ... |
11420787 | import requests
ROOT_URL = 'http://localhost:5000'
def test_status_codes():
pages = [
'', '/ja',
'/docs/manual', '/ja/docs/manual',
'/generator'
]
for p in pages:
res = requests.get(ROOT_URL + p)
assert res.status_code == 200
|
11420790 | from collections import defaultdict
from django import template
from ranking.models import Account
register = template.Library()
@register.simple_tag
def preload_statistics(statistics, resource):
ret = {}
members = []
for s in statistics:
if '_members' in s.addition:
members.extend(... |
11420793 | from os import getenv
from os.path import dirname, exists, join as join_path
import sys
config = {
'coauthors': {
'authors_file': join_path(dirname(__file__), 'authors.txt'),
'coauthors_git_msg_file': join_path(getenv('HOME'), '.coauthors.tmp'),
'domain': 'superhero.universe',
'hist... |
11420807 | import hashpumpy
import requests
import base64
# saved: seed=huhu&level=xiii => seed: huhu&level=xiii e530da3436a296a64c95851ba57e22b3
for key_length in range(16,17):
print(key_length)
saved,msg = hashpumpy.hashpump("e530da3436a296a64c95851ba57e22b3", "huhu", "&level=xiii", key_length)
cookies = {"hash":saved,"saved... |
11420849 | from django.http import HttpRequest, HttpResponse
from django.test import SimpleTestCase
from core.decorators import add_headers, akamai_no_store
def view(request, *args, **kwargs):
return HttpResponse("ok")
@akamai_no_store
def view_no_store(request, *args, **kwargs):
return HttpResponse("no store")
cla... |
11420851 | import os
import json
from time import strftime
from itertools import product, cycle
from collections import defaultdict, OrderedDict
import numpy as np
import h5py
from tqdm import tqdm
from keras.models import Model
from keras.layers import Input, Dense, Activation
from keras.initializers import RandomNormal, Random... |
11420876 | from distutils.core import setup
from distutils.extension import Extension
import multiprocessing
from Cython.Distutils import build_ext
from Cython.Build import cythonize
import numpy
import os
import glob
import re
import sys
class BuildError(Exception):
pass
if 'CC' in os.environ:
print("Using CC={}".form... |
11420886 | from typing import List, Tuple
from lib.utils.utils import DATETIME_TO_UTC
from lib.utils import json as ujson
from lib.metastore.base_metastore_loader import DataTable, DataColumn
from .sqlalchemy_metastore_loader import SqlAlchemyMetastoreLoader
class MysqlMetastoreLoader(SqlAlchemyMetastoreLoader):
def get_ta... |
11420897 | from marshmallow import Schema, fields
class Asset(Schema):
kind = fields.String(default='software-package')
md5_size = fields.Integer(default=10485760)
md5s = fields.List(fields.String())
url = fields.URL()
needs_shine = fields.Boolean()
class BundleItem(Schema):
bundle_identifier = fie... |
11420908 | import numpy as np
from PIL import Image # source: http://www.pythonware.com/library/pil/handbook/image.htm
from .logger import log
from .array_bit_plane import BitPlane
def load_image(infile, as_rgb):
get_im_mode = lambda is_rgb: 'RGB' if is_rgb else 'L'
return Image.open(infile).convert(get_im_mode(as_rgb))... |
11420995 | from .exceptions import *
from html import unescape
class HTTPClient:
"""A Proxy object for all API actions"""
def __init__(self, url, session, logged_in):
self.url = url
self.session = session
self.logged_in = logged_in
async def close(self):
"""Closes the aiohttp Sessio... |
11420999 | import numpy as np
import matplotlib.pyplot as plt
import cv2
# With jupyter notebook uncomment below line
# %matplotlib inline
# This plots figures inside the notebook
def plot_gray(input_image):
"""
plot grayscale image with no axis
"""
# plot grayscale image with gray colormap ... |
11421006 | r"""Utilities for the normal benchmark.
"""
import torch
from torch.distributions.normal import Normal
def Prior():
return Uniform(-5, 5)
def PriorExperiment():
return Uniform(-5, 5)
def Truth():
return torch.tensor([0]).float()
def log_likelihood(theta, x):
return Normal(theta, 1).log_prob(... |
11421025 | from setuptools import setup,find_packages
import os
import sys
import platform
setup(name='moha',
version='0.1',
description='A QM package',
url='http://github.com/fhqgfss/penta',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=find_packages(),
package_data={'moha': ... |
11421043 | import pymel.core as pm
import logging
log = logging.getLogger("ui")
class BaseTemplate(pm.ui.AETemplate):
def addControl(self, control, label=None, **kwargs):
pm.ui.AETemplate.addControl(self, control, label=label, **kwargs)
def beginLayout(self, name, collapse=True):
pm.ui.AETe... |
11421056 | from __future__ import division
import math
import torch
def get_points_from_angles(distance, elevation, azimuth, degrees=True):
if isinstance(distance, float) or isinstance(distance, int):
if degrees:
elevation = math.radians(elevation)
azimuth = math.radians(azimuth)
retu... |
11421072 | from markupsafe import escape
def run():
string = "<strong>Hello World!</strong>" * 1000
escape(string)
|
11421105 | import re
from django.core.validators import RegexValidator
youtube_validator = RegexValidator(
regex=(r"(^(?:https?:\/\/)?(?:www[.])?(?:youtube[.]com\/watch[?]v=|youtu[.]be\/))")
)
|
11421113 | import re, time
import database_auth
import archiveis
import datetime
def insere_um(tweet, db):
cursor = db.cursor()
try:
sql = "INSERT INTO `tweets_int`.`tweets` (`idTweets`, `plain_text`, `timestamp_tw`, `handle`, `retweets`, `favs`, `object`) " \
"VALUES (%s, %s, %s, %s, %s, %s, %s);... |
11421137 | from .helpers import (
create_resource, get_api_key, assert_correct_response,
assert_correct_validation_error, assert_missing_body
)
def test_bad_requests(module_client, module_db, fake_auth_from_oc, fake_algolia_save):
client = module_client
apikey = get_api_key(client)
bad_json = "{\"test\": \"... |
11421197 | import pytest
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import repeat, rearrange
from src.models.modules.masking import LengthMask, TriangularCausalMask
from src.models.attention.full_attention import FullAttention
from src.models.attention.sblocal_attention import S... |
11421202 | import itk
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
im=itk.imread('data/CBCT-TextureInput.png', itk.F)
sobel=itk.sobel_edge_detection_image_filter(im)
arr = itk.array_from_image(sobel)
plt.gray()
plt.imshow(arr)
plt.axis('off')
|
11421208 | import tensorflow as tf
def get_activation_fn(type='relu'):
"""
Return tensorflow activation function given string name.
Args:
type:
Returns:
"""
if type == 'relu':
return tf.nn.relu
elif type == 'elu':
return tf.nn.elu
elif type == 'tanh':
return tf.n... |
11421230 | PLANETS = ('Mercury', 'Venus', 'Earth', 'Mars',
'Jupiter', 'Saturn', 'Uranus', 'Neptune')
def get_planet_name(planet_id):
return PLANETS[planet_id - 1]
|
11421232 | class CaseData:
"""
A test case.
Attributes
----------
molecule : :class:`.Molecule`
The molecule to test.
atoms : :class:`tuple`
The correct atoms of the molecule.
"""
def __init__(self, molecule, atoms):
"""
Initialize a :class:`.CaseData` instance.
... |
11421239 | import pydiffvg
import torch
import skimage
import numpy as np
# Use GPU if available
pydiffvg.set_use_gpu(torch.cuda.is_available())
canvas_width, canvas_height = 256, 256
num_control_points = torch.tensor([2])
# points = torch.tensor([[120.0, 30.0], # base
# [150.0, 60.0], # control point
#... |
11421240 | from pyramid import tweens, httpexceptions
from briefmetrics.lib.exceptions import LoginRequired, APIError
def _dict_view_prefixed(d, prefix):
return {key[len(prefix):]: d[key] for key in d if key.startswith(prefix)}
def _setup_features(RequestCls, settings, prefix='features.'):
settings_features = _dict_v... |
11421248 | cpgf._import("cpgf", "builtin.debug");
device = None;
UseHighLevelShaders = False;
invWorld = None;
worldViewProj = None;
pos = None;
col = None;
world = None;
def overrideShaderCallBack(callback) :
def OnSetConstants(me, services, userData) :
global UseHighLevelShaders;
global device;
glob... |
11421264 | import asyncio
import re
import ujson
import unittest
import hummingbot.connector.derivative.dydx_perpetual.dydx_perpetual_constants as CONSTANTS
from aioresponses import aioresponses
from typing import Awaitable, Optional
from unittest.mock import AsyncMock, patch
from hummingbot.connector.derivative.dydx_perpetual... |
11421274 | try: from setuptools import setup
except: from distutils.core import setup
setup( long_description=open("README.rst").read(),
name="""PyGeoj""",
license="""MIT""",
author="""<NAME>""",
author_email="""<EMAIL>""",
py_modules=['pygeoj'],
url="""http://github.com/karimbahgat/PyGeoj""",
version="""1.0.0""",
keywo... |
11421295 | from django.core.exceptions import FieldDoesNotExist
from django.db.models.fields import NOT_PROVIDED
from django.utils.module_loading import import_string
from rest_framework import serializers, relations
from rest_framework.fields import empty
from inflector import Inflector
from .app_settings import settings
in... |
11421356 | import os
import torch, pdb
import logging
from glob import glob
from torch.autograd import Variable
# import spacy
from nltk.translate.bleu_score import corpus_bleu
from src.bleu import compute_bleu
import numpy as np
import json
from gensim import models
#import ipdb as pdb
from collections import OrderedDict
from... |
11421399 | import os
import sys
import re
with open("infovol.txt", "w+") as file:
profiles_list = []
try:
os.system(f"volatility_2.6_lin64_standalone -f {sys.argv[1]} imageinfo > infovol.txt")
except:
print("Maybe you forgot to export PATH to your Volatility")
sys.exit()
for line in file:
profiles = line
profile... |
11421410 | from __future__ import absolute_import
import logging
from . import BackendBase
from ..config import BASE_MODULE_SCHEMA
from ..exceptions import KeyNotFoundException
LOG = logging.getLogger(__name__)
REQUIREMENTS = ("python-etcd",)
CONFIG_SCHEMA = BASE_MODULE_SCHEMA.copy()
CONFIG_SCHEMA.update(
{
"hos... |
11421411 | import BaseHTTPServer
from Cookie import SimpleCookie
import base64
import time
import cgi
reply = "I got it!"
error = "bad data!"
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def error(self, message, status=400):
self.send_response(status)
self.wfile.write(message)
raise Exception('Error %s: %s' %... |
11421413 | import os
import time
import shutil
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import requests
from config import API_KEY, API_SECRET, GESTURE_PATH
input_dirname = os.path.abspath(os.path.dirname(__file__)) + '/input/'
return_gesture = 1
def batch_gestur... |
11421431 | import csv
import copy
import itertools
from dataclasses import dataclass, field
import numpy as np
from tqdm import tqdm
import time
import os
from samo.model import Network
@dataclass
class RuleBased:
network: Network
def update(self):
for partition in self.network.partitions:
for index... |
11421445 | from __future__ import print_function
import json
import logging
import os
import time
from unittest import TestCase
import requests
from repositorytools import cli
try:
import resource
except:
resource = None
MAX_MEMORY_USE_MB = 1
import config
GROUP = 'com.fooware'
ARTIFACT_LOCAL_PATH = 'test-1.0.txt'
M... |
11421455 | from setuptools import setup, Extension
setup(
name="methodfinder",
version="0.0.4",
description="For when you know some procedure must already exist, and you want to quickly find its name",
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/billsix/methodfinder",
keywords="m... |
11421460 | import aiohttp_jinja2
import jinja2
import logging
import os
import time
from .rpc_api import RpcApi
from aiohttp import web
class WebServer(web.Application):
def __init__(self, vmshepherd, config=None):
super().__init__()
self.port = config.get('listen_port', 8888)
allowed_methods = conf... |
11421493 | import math
import torch
import numpy as np
import torch.nn as nn
import scipy.stats as st
import torch.nn.functional as F
# kernel of TI
def get_kernel(kernlen=15, nsig=3):
x = np.linspace(-nsig, nsig, kernlen)
kern1d = st.norm.pdf(x)
kernel_raw = np.outer(kern1d, kern1d)
kernel = kernel_raw / kernel... |
11421494 | import cv2 as cv
class Timer:
def __init__(self):
self._tm = cv.TickMeter()
self._record = []
def start(self):
self._tm.start()
def stop(self):
self._tm.stop()
self._record.append(self._tm.getTimeMilli())
self._tm.reset()
def reset(self):
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.