id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9948842 | from collections import deque
import random
class Agent(object):
def __init__(self,
action_size=3,
max_length=1000, replay_prob=0.995, forget_rate=0.25):
self.action_size = action_size
self.forget_rate = forget_rate
self.replay_prob = replay_prob
... |
9948862 | from aws_cdk import (
aws_lambda as _lambda,
aws_lambda_event_sources as _event,
aws_dynamodb as dynamo_db,
aws_s3 as s3,
aws_s3_notifications as s3n,
aws_sqs as sqs,
aws_iam as iam,
aws_ec2 as ec2,
aws_ecs as ecs,
aws_logs as logs,
aws_events as events,
aws_events_target... |
9948869 | import torch
def unpack_batched_events(events, batch_indices):
"""
When returning events from a pytorch dataloader, it is often convenient when
batching, to place them into a contiguous 1x1xNx4 array, where N=length of all
B event arrays in the batch. This function unpacks the events into a Bx1xMx4 arr... |
9948944 | import FWCore.ParameterSet.Config as cms
conditionDumperInEdm = cms.EDProducer("ConditionDumperInEdm",
gtEvmDigisLabel = cms.InputTag("gtEvmDigis")
)
|
9948998 | import argparse
import base64
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
import json
from multiprocessing import Process
import numpy as np
import os
import queue
import random
import requests
import socket
import struct
from threading import Thread
import time
from clipper_admin.docke... |
9949006 | import luigi
import pandas as pd
from Data_Prep.task_read_raw import ReadRaw
# Generate base data
class GenerateBase(luigi.Task):
current_dir = luigi.Parameter()
config = luigi.DictParameter()
def requires(self):
return ReadRaw(self.current_dir, self.config)
def output(self):
... |
9949007 | import numpy as np
import keras
from keras import backend as K
from keras import layers
from keras.models import Model, Sequential
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
# Shape of MNIST images
image_shape = (28, 28, 1)
def create_encoder(latent_dim):
'''
Creates a convolutio... |
9949011 | from random import randint
import random
import string
def _gen(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def _genATstring():
length = randint(1,6)
stringa = "AT" + _gen(length) + '\r'
return stringa
def _genNumber():
if randint(0,1) == ... |
9949036 | import os
import csv
import shutil
from subprocess import call
from annogesiclib.seq_editer import SeqEditer
def wget(input_folder, ftp, files_type, log):
log.write("\t" + " ".join(["wget", "-cP", input_folder, ftp + "/*" + files_type]) + "\n")
os.system(" ".join(["wget", "-cP", input_folder, ftp + "/*" + fil... |
9949037 | from viewflow import flow
from viewflow.base import Flow, this
from viewflow.flow.views import CreateProcessView
from .models import SavableProcess
from .views import SavableProcessView
class SavableFlow(Flow):
process_class = SavableProcess
start = flow.Start(CreateProcessView, fields=[]).Next(this.savable_... |
9949088 | from tensorflow.keras import backend as K
abs_definitions = [
{'name': 'add_class',
'nargs': '+',
'type': int,
'help': 'flag to add abstention (per task)'},
{'name': 'alpha',
'nargs': '+',
'type': float,
'help': 'abstention penalty coefficient (per task)'},
{'name': 'min_acc',... |
9949118 | import csv
import io
from django.urls import reverse_lazy
from test_plus.test import TestCase
from company.factories import CompanyFactory
from pola.tests.test_views import PermissionMixin
from product.factories import ProductFactory
class TestHome(PermissionMixin, TestCase):
url = reverse_lazy('bi_export:top_c... |
9949132 | import logging
import voltron
from voltron.api import *
from scruffy.plugin import Plugin
log = logging.getLogger('api')
class APICommandRequest(APIRequest):
"""
API execute command request.
{
"type": "request",
"request": "command"
"data": {
"command": ... |
9949149 | import copy
import jinja2
import wtforms
from wtforms.fields.core import UnboundField
from wtforms.validators import Optional, InputRequired
from flask import render_template
from sqlalchemy.sql.elements import TextClause
class BaseWidget:
filterable = True
field = wtforms.StringField()
field_kwargs = {}... |
9949193 | from config import *
from ibm_datastage_api import DSAPI
dsapi = DSAPI()
hproj = None
hjob = None
try:
_, err = dsapi.DSLoadLibrary(API_LIB_FILE)
if err:
raise Exception("Loading the library failed: {}".format(err))
print("Setting the parameters to connect to DataStage server")
dsapi.DSSetSer... |
9949294 | import math
from typing import Sequence, Tuple
import numpy as np
from .math import vertices_matmul
from .shapes import Shape
from .skins import SilhouetteSkin
class PolyShape(Shape):
"""
PolyShape is a base class for any Shape made of segments and polygonal masks, such as
cubes, OBJ-based models, etc. ... |
9949307 | import trimesh
import numpy as np
import multiprocessing as mp
from multiprocessing import Pool
import glob
import os
import argparse
def create_voxel_off(path):
pc_path = path + '/voxelized_point_cloud_{}res_{}points.npz'.format(args.res, args.num_points)
off_path = path + '/voxelized_point_cloud_{}res_{}poi... |
9949328 | from __future__ import unicode_literals
import re
from django.db import models
from django.urls import reverse
from django.utils.safestring import mark_safe
from languages.fields import LanguageField
import markdown
from books.models import Book, Author, Section, SectionArtefact
class TermCategory(models.Model):
... |
9949349 | import re
from uptime import Uptime
def process_show_version(net_device):
'''
Process the show_version output for net_device
Assign the following attributes to the net_device object
hostname
device_type # router, switch, firewall, etc.
vendor
model
os_version
uptime ... |
9949366 | from streamlit_server_state.server_state import ServerState
from streamlit_server_state.server_state_lock import ServerStateLock
def test_lock_object_has_the_same_keys():
server_state = ServerState()
server_state_lock = ServerStateLock(server_state)
assert len(server_state_lock) == 0
assert "foo" not... |
9949373 | import io
import zipfile
def zip_in_memory(files):
# Zip all files together
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
for file_name, data in files:
zip_file.writestr(file_name, data.getvalue())
return zip_buffer |
9949379 | from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers, exceptions
from ..fields import UUIDField, BooleanField
from ..models import User_Group_Membership
class UpdateMembershipSerializer(serializers.Serializer):
membership_id = UUIDField(required=True)
group_admin = B... |
9949390 | from flask.cli import with_appcontext
from marshmallow import fields
from flexmeasures.data.models.data_sources import DataSource
from flexmeasures.data.schemas.utils import FMValidationError, MarshmallowClickMixin
class DataSourceIdField(fields.Int, MarshmallowClickMixin):
"""Field that deserializes to a Sensor... |
9949398 | def execute(
mp,
some_float_parameter,
some_string_parameter,
some_integer_parameter,
some_bool_parameter,
):
"""User defined process."""
assert some_integer_parameter == 12
assert some_float_parameter == 5.3
assert some_string_parameter == "string1"
assert some_bool_parameter is... |
9949440 | from django.conf.urls import url
import vpp.views
urlpatterns = [
url(r'^$', vpp.views.index, name='vpp'),
]
|
9949468 | def extractMahouKoukoku(item):
"""
# MahouKoukoku
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Shiro no Koukoku Monogatari ' in item['title']:
return buildReleaseMessageWithType(item, 'Shiro no Koukoku... |
9949490 | import datetime
from app.db.session import database
from app.models.note import Note
from app.schemas.note import NoteSchema
from app.models.user import User
async def post(payload: NoteSchema, owner_id: int):
query = "CALL insert_note(:title, :description, :owner_id, 0)" # noinspection
values = {"title": pa... |
9949539 | from __future__ import print_function, division
import math
import os
import numpy as np
import scipy
from .spectrogram import db_scale, positive_freq_magnitudes, \
select_positive_freq_fft, fftfreqs, normalized_window, scale_magnitudes
from .signal import SignalFrames
from .tuning import PitchQuantizer, Tuning
... |
9949541 | from typing import Dict, List
from mstrio.utils.dict_filter import filter_list_of_dicts
class MstrException(Exception):
"""Base class for exceptions returned by the MicroStrategy REST API.
Attributes:
code: Error code
message: Error message
ticket_id: MSTR Ticket ID
"""
def ... |
9949556 | import pytest
from celseq2.helper import md5sum
import HTSeq
def test_dummy_gtf(instance_dummy_gtf):
calc = md5sum(instance_dummy_gtf)
assert calc == '3e2a544354a222e381636999587fb7dd'
def test_dummy_fasta(instance_dummy_fasta):
calc = md5sum(instance_dummy_fasta)
assert calc == 'fe7e821e07b95b1ef4e... |
9949566 | import datetime
import os
import time
import pytz
from celery import shared_task
from django.conf import settings
from django.urls import reverse
from budget.models import Board
from budget.tasks.slack import DOMAIN, get_client
def format_developers(project):
if project.developers.count() == 0:
return '... |
9949570 | from pathlib import Path
import setuptools
CURRENT_DIR = Path(__file__).parent
setuptools.setup(
name="support_resistance_line",
version="0.0.7",
packages=setuptools.find_packages(),
python_requires=">=3.6",
description=(
"A well-tuned algorithm to generate & draw support/resistance line ... |
9949606 | import pytest
from mock import Mock, patch
from nefertari.view import BaseView
from nefertari.utils import dictset
from nefertari.view_helpers import ESAggregator
from nefertari.json_httpexceptions import JHTTPForbidden
class DemoView(BaseView):
""" BaseView inherits from OptionsViewMixin """
_json_encoder =... |
9949668 | import torch
import copy
import numpy as np
from config import opt, data
from utils import entropy
class TestModel():
def __init__(self):
self.cumulative_reward = 0
def reset(self):
pass
def forward(self, inp):
pass
def train_model(self, data, epochs):
pass
def v... |
9949686 | from __future__ import annotations
from typing import TYPE_CHECKING
import open3d as o3d
from pyntcloud import PyntCloud
if TYPE_CHECKING:
from pointcloudset import PointCloud
def from_open3d(open3d_data: o3d.open3d_pybind.geometry.PointCloud) -> dict:
"""Converts a open3d pointcloud to a PointCloud.
... |
9949705 | import logging
from django_nose import NoseTestSuiteRunner
class DisableLoggingNoseTestSuiteRunner(NoseTestSuiteRunner):
"""
Disable the test runner log level below `logging.CRITICAL`.
"""
def run_tests(self, *args, **kwargs):
# Disable logging below critical
logging.disable(logging.C... |
9949706 | import unittest
from typing import List
import flask_testing
import requests
from flask import Flask
from src.muse_as_service import MUSEClient
from src.muse_as_service.app import app
class TestAuth(flask_testing.TestCase):
"""
Class for testing authorization.
"""
ip = "localhost"
port = 5000
... |
9949713 | import torch
def compute_average_dice(prediction, target, num_classes,
excluded_class=-1, absent_value=0.0):
"""Computes average dice score between target and prediction
Parameters
----------
prediction : torch.Tensor or torch.autograd.Variable
Predicted segmentation map with den... |
9949743 | from models.model import input_dim, output_dim
from utilities.utilities import *
import random
# Load the data into
def load_data(data_path, nb_examples=None):
volumes_folder_path = data_path + "/volumes"
labels_folder_path = data_path + "/labels"
volumes_path = get_dir(volumes_folder_path)
labels_pa... |
9949772 | import numpy as np
# Facial landmark detection
import dlib
# Iris localisation
# from .phase_cong_3 import phase_congruency
from skimage.morphology import dilation
from skimage.morphology import disk
from skimage import feature
from skimage.transform import hough_circle, hough_circle_peaks
from skimage.draw import ci... |
9949830 | import os
import sys
import time
import subprocess
if __name__ == "__main__":
# detection
subprocess.call("CUDA_VISIBLE_DEVICES=0 python -u ./table_recognition/table_inference.py 8 0 0 &"
"CUDA_VISIBLE_DEVICES=1 python -u ./table_recognition/table_inference.py 8 1 0 &"
"... |
9949835 | import sys
import os.path
sys.path.append(os.path.abspath(os.pardir))
import disaggregator as da
import unittest
import pandas as pd
import numpy as np
class ApplianceSetTestCase(unittest.TestCase):
def setUp(self):
instances = []
for i in range(3):
index = pd.date_range('1/1/2013', pe... |
9949841 | import json
import fnmatch
import os
from conan.tools.files import CppPackage
from conans.util.files import save, load
class CMakeFileAPI(object):
"""
implements https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html
"""
CODEMODELV2 = "codemodel-v2"
SKIP_TARGETS = ["ZERO_CHECK", "ALL_BU... |
9949846 | import fbchat
def test_module_renaming():
assert fbchat.Message.__module__ == "fbchat"
assert fbchat.Group.__module__ == "fbchat"
assert fbchat.Event.__module__ == "fbchat"
assert fbchat.User.block.__module__ == "fbchat"
assert fbchat.Session.login.__func__.__module__ == "fbchat"
assert fbchat... |
9949865 | import pytest
from taskwarrior_syncall.types import TwRawItem
@pytest.fixture()
def tw_task(request: pytest.FixtureRequest) -> TwRawItem:
"""Fixture to parametrize on."""
param = request.param # type: ignore
return request.getfixturevalue(param)
@pytest.fixture()
def tw_simple_pending_task() -> TwRawI... |
9949975 | def test_generator_fails_before_yield():
a = 1 // 0
yield lambda: True
def test_generator_fails_during_iteration():
for i in [1, 2, 3, 0, 5, 6]:
a = 1 // i
yield lambda: True
def test_ok():
pass
class TestBuggyGenerators(object):
def test_generator_fails_before_yield(self):
... |
9949990 | import re
wiki_link_prefix = 'http://en.wikipedia.org/wiki/'
def read_csv_file(path):
data = {}
with open(path, 'r', encoding='utf8') as f:
for line in f:
comps = line.strip().split('\t')
doc_name = comps[0] + ' ' + comps[1]
mention = comps[2]
lctx = co... |
9950009 | import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from scipy.misc import imread, imsave, imrotate
from time import time
import geometry
import geometry.camera
import mesh
import mesh.vertices
import mesh.texture
import mesh.render
import mesh_cython
import mesh_cython.render
from __init__ impo... |
9950028 | import torch
from torch import nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class TreeDiffEncoder(nn.Module):
def __init__(self, graph_encoding_size, input_size, change_vector_size, operators,
operator_embedding, production_embedding, field_embedding, token_em... |
9950033 | from enum import Enum
from enum import auto
class EvaluationMetric:
def __init__(self,
accuracy: float,
recall: float,
precision: float) -> None:
self._accuracy = accuracy
self._recall = recall
self._precision = precision
@property
... |
9950066 | from .read import (read_embl,
read_fasta,
read_fastq,
read_nexus_seq,
read_swiss,
read_phylip,
read_clustal,
read_blast_xml,
read_phylip_relaxed,
rea... |
9950097 | import unittest
import numpy as np
import scipy.sparse as sp
from Orange.data import (
Table,
Domain,
DiscreteVariable,
ContinuousVariable,
StringVariable,
)
from Orange.preprocess.transformation import Identity, Transformation, Lookup
class TestTransformation(unittest.TestCase):
class Trans... |
9950124 | def _impl(ctx):
output_dir = ctx.actions.declare_directory("doxygen")
doxyfile = ctx.actions.declare_file("Doxyfile")
outs = [
output_dir,
ctx.actions.declare_file("doxygen/html/index.html"),
]
ctx.actions.expand_template(
template = ctx.file.doxyfile,
output = doxy... |
9950140 | from fastapi import APIRouter
from server.api.api_v1.endpoints import sessions, pipelines, websockets, rpc, operators
api_router = APIRouter()
api_router.include_router(sessions.router, prefix="/sessions", tags=["files"])
api_router.include_router(pipelines.router, prefix="/pipelines", tags=["pipelines"])
api_router... |
9950173 | from utils.analyzers.syntactic import parse as analize
from models.instructions.DML.select import Select
from models.instructions.DML.special_functions import format_df, format_table_list
from controllers.symbol_table import SymbolTable
from utils.reports.tchecker_report import TypeCheckerReport
from utils.reports.symb... |
9950179 | import numpy as np
def propagate(LHS, X, Y):
P = np.tensordot(LHS, X, axes=([0, ], [0, ]))
Q = np.tensordot(P, Y, axes=([0, 2], [0, 1]))
R = np.tensordot(Q, X, axes=([0, 3], [0, 1]))
return R
|
9950191 | from tir import Webapp
import unittest
class TMSA110(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGATMS','19/06/2019','T1','M SP 03 ','43')
inst.oHelper.Program('TMSA110')
def test_TMSA110_CT001(self):
self.oHelper.SetButton('Incluir')
s... |
9950199 | import sys
import csv
def main():
try:
box_w = float(input())
box_h = float(input())
box_d = float(input())
packages_filename = input()
box_dimensions = sorted((box_w, box_h, box_d))
packages = _load_packages(packages_filename)
for name, dimensions in pack... |
9950230 | from .box_iou_rotated import obb_overlaps
from .convex import convex_sort
from .fr import FeatureRefineModule
from .ml_nms_rotated import ml_nms_rotated
from .nms_rotated import obb_batched_nms, obb_nms, poly_nms
from .polygon_geo import polygon_iou
from .rbbox_geo import rbbox_iou
# yapf: disable
from .rnms import bat... |
9950270 | from addressesapp.models import Person
from rest_framework import serializers
class AddressesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Person
fields = ('id', 'name', 'mail')
|
9950273 | from .math_equivalence import is_equiv
import unittest
class TestIsEquiv(unittest.TestCase):
def test_fractions(self):
test_in = "\\tfrac{1}{2} + \\frac1{72}"
test_out = "\\\\frac{1}{2} + 2/3"
self.assertFalse(is_equiv(test_in, test_out))
def test_order(self):
test_in = "10, 4, -2"
test_out = "... |
9950275 | import logging
import logging.config
import logging.handlers
from path import Path
def init_logger(level='INFO', log_dir='./', log_name='main_logger', filename='main.log'):
logger = logging.getLogger(log_name)
fh = logging.handlers.RotatingFileHandler(
Path(log_dir) / filename, 'w', 20 * 1024 * 1024... |
9950421 | import struct
from ctypes import create_string_buffer
def add_tesla_crc(msg,msg_len):
"""Calculate CRC8 using 1D poly, FF start, FF end"""
crc_lookup = [0x00, 0x1D, 0x3A, 0x27, 0x74, 0x69, 0x4E, 0x53, 0xE8, 0xF5, 0xD2, 0xCF, 0x9C, 0x81, 0xA6, 0xBB,
0xCD, 0xD0, 0xF7, 0xEA, 0xB9, 0xA4, 0x83, 0x9E, 0x25, 0x38, 0x1F,... |
9950427 | from rest_framework import viewsets
from yawn.task.models import Task, Execution
from yawn.task.serializers import TaskDetailSerializer, ExecutionListSerializer
class TaskViewSet(viewsets.GenericViewSet,
viewsets.mixins.RetrieveModelMixin,
viewsets.mixins.UpdateModelMixin):
""... |
9950475 | import tensorflow as tf
import numpy as np
import re
try:
from .discriminator_gumbel_nce import model_fn_builder as discriminator
from .generator_gumbel import model_fn_builder as generator
from .token_discriminator_nce import discriminator_metric_train, discriminator_metric_eval
from .token_generator import gener... |
9950485 | from sm.browser.mz_search import create_mz_image
import numpy as np
def test_create_mz_image():
mz_peaks = np.array([[100, 1000, 0], [100, 1000, 1], [100, 1000, 2], [100, 1000, 2]])
coordinates = np.array([[0, 0], [1, 0], [2, 0]])
mz_image, alpha = create_mz_image(mz_peaks, coordinates)
assert alph... |
9950579 | import numpy as np
import numpy.ma as ma
from filters import get_filters
get_filters(globals()) # imports all filters at once
def comp_angle(blob): # compute and compare angles, a component of intra_blob
# compute angles:
dy__ = ma.array(blob.dert__[:, :, 1], mask=~blob.map)
dx__ = ma.array(blob.dert__... |
9950583 | from tests import analysis_code_list
def test_numeric_list_assign():
code = [
'a = [1, 2, 3, 4]'
]
assert analysis_code_list(code) == 'export a=(1 2 3 4)\n'
def test_mix_list_assign():
code = [
'a = ["1", "2", 1, 2]'
]
assert analysis_code_list(code) == 'export a=("1" "2" 1 ... |
9950590 | from iosfu.gui.core import GUIController
from iosfu.gui.components.base import Panel, Section
from iosfu.plugin.device_info.plugin import DeviceInfoPlugin
controller = GUIController()
class Main(Section):
name = 'Main'
plugin = DeviceInfoPlugin
template = 'main.jinja'
class VersionInfo(Section):
n... |
9950598 | import os
import sys
sys.path.append('../../')
import copy
import unittest
from batchcompute import CN_QINGDAO
from batchcompute.utils.jsonizable import Jsonizable
from batchcompute.utils.functions import (
import_json, import_httplib, iget, get_region, ConfigError, timediff,
)
json = import_json()
httplib = impo... |
9950635 | import os, json
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
"""Load contents of .json file into a JSON object"""
def loadJsonFile(filename):
try:
f = open(filename)
jsonObj = json.load(f)
f.close()
return jsonObj
except IOError:
print("- un... |
9950679 | import tkinter as tk
import os
from tkinter import messagebox
from img import Logo
from mysql import connect
import tkinter.ttk as ttk
'''
class NotebookSample(ttk.Frame):
def __init__(self, root):
super().__init__(root)
self.create_widgets()
self.pack()
def create_widgets(self):
... |
9950686 | from zalo.sdk import APIConfig
from zalo.sdk.ZaloBaseClient import ZaloBaseClient
class ZaloArticleClient(ZaloBaseClient):
def __init__(self, oa_info):
self.oa_info = oa_info
def get(self, url, data):
endpoint = "%s/%s/%s" % (APIConfig.DEFAULT_OA_API_BASE, APIConfig.DEFAULT_OA_API_VERSION, u... |
9950732 | from typing import List, Sequence
import torch
import numpy as np
Indices = torch.LongTensor
def update_values(dict_from, dict_to):
for key, value in dict_from.items():
if isinstance(value, dict):
update_values(dict_from[key], dict_to[key])
elif value is not None:
dict_to[... |
9950744 | from plugin.core.libraries.helpers.system import SystemHelper
def test_arm():
# ARMv5
assert SystemHelper.arm('armv5', 'sf') == 'armv5_sf'
assert SystemHelper.arm('armv5', 'hf') == 'armv5_hf'
# ARMv6
assert SystemHelper.arm('armv6', 'sf') == 'armv6_sf'
assert SystemHelper.arm('armv6', 'hf') =... |
9950800 | import argparse
import torch
import torch.nn.functional as F
from tqdm import tqdm
from efficientnet import models
from efficientnet.datasets.imagenet import ImageNetDataLoader
from efficientnet.metrics import Accuracy, Average
from efficientnet.models.efficientnet import params
def parse_args():
parser = argpa... |
9950811 | import requests
def key_Word():
response = requests.get(keyword_url)
return response.json()["data"]
if __name__ == '__main__':
for kw in key_Word():
print(kw)
|
9950830 | import numpy as np
from scipy import sparse
"""
Calculate spectral radius of whole weight matrix
"""
def getSpectralRadius(self, weights):
# Stack top and bottom row of weight matrix horizontally
top = sparse.hstack([weights.exex, weights.inex])
bottom = sparse.hstack([weights.exin, weights.inin])
# S... |
9950835 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="numerous-engine",
version="0.2",
author='<NAME>, EnergyMachines ApS',
author_email='<EMAIL>',
description="Numerous - an object-oriented modelling and simulation engine.",
long_descri... |
9950855 | import os
import yaml
import tensorflow as tf
TEXT_VECTORIAN_CONFIG_FILENAME = 'config.yml'
text_vectorian_config = None
DOWNLOAD_ROOT='.text_vectorian'
def get_package_directory():
package_directory = os.path.dirname(os.path.abspath(__file__))
return package_directory
def load_config():
config_filename... |
9950869 | import os
import setuptools
BASE_PATH = os.path.dirname(__file__)
CFG_PATH = os.path.join(BASE_PATH, "setup.cfg")
config = setuptools.config.read_configuration(CFG_PATH)
version = config["metadata"]["version"]
setuptools.setup(
name="dbnd-redshift",
package_dir={"": "src"},
install_requires=["psycopg2-... |
9950924 | n, m, c = map(int, raw_input().split())
def wrapped_index(index, size):
if index < 0:
return size -1
if index >= size:
return 0
else:
return index
grid = []
for i in range(n):
grid.append(list(raw_input().strip()))
start, period, final = 0, 0, -1
hashmap = {}
f... |
9951038 | from montepython.likelihood_class import Likelihood
import numpy as np
from math import log
import os
class WiggleZ_bao(Likelihood):
"""From 1401.0358v2"""
def __init__(self, path, data, command_line):
Likelihood.__init__(self, path, data, command_line)
measurements = np.loadtxt(os.path.joi... |
9951071 | from unittest import TestCase
from unittest.mock import patch
import numpy as np
import pandas as pd
from sdgym.synthesizers.utils import DiscretizeTransformer, Transformer
class TestTransformer(TestCase):
def test_get_metadata(self):
"""get_metadata returns information about the dataframe."""
... |
9951080 | import json
import argtyp
import char2image
import extenteten as ex
import extenteten.collections as collections
import numpy as np
import qnd
import qndex
import tensorflow as tf
from .ar2word2sent2doc import ar2word2sent2doc
from .char2word2sent2doc import add_flags as add_child_flags
from .font2char import font2ch... |
9951110 | import os
import torch
import torch.nn as nn
from torch.autograd import Variable
def get_outputs(model, instances, flow=False, use_cuda=False):
if flow:
frames = Variable(instances["frames"])
flow_x = Variable(instances["flow_x"])
flow_y = Variable(instances["flow_y"])
if use_cud... |
9951130 | import webcrystal
from webcrystal import _format_proxy_path as format_proxy_path
from webcrystal import _format_proxy_url as format_proxy_url
from collections import OrderedDict
import gzip
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from multiprocessing import Process
import os
im... |
9951131 | from datetime import datetime
from django.db import models
from DjangoUeditor.models import UEditorField
class CityInfo(models.Model):
"""
CityInfo 城市表
"""
name = models.CharField(max_length=20, verbose_name="城市名称")
add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
... |
9951166 | import os
from jumpscale.clients.stellar import TRANSACTION_FEES
from jumpscale.loader import j
BASE_CAPACITY = int(os.getenv("BASE_CAPACITY", 14))
def get_vdc_instance():
if not j.sals.vdc.list_all():
raise j.exceptions.Value(
"Billing service couldn't find any vdcs on this machine, Please ... |
9951176 | import argparse
import os
import torch
from helpers.training import load_checkpoint
from models.translate import seq2seq_translate
def run(config):
print(config)
print()
print()
print(f"Loading checkpoint: {config.cp}")
cp = load_checkpoint(config.cp)
src_file = config.src
_base, _file ... |
9951189 | import gc
import os, machine
from flashbdev import bdev
try:
if bdev:
os.mount(machine.SDCard(width=1), '/')
#os.mount(bdev, "/")
except OSError:
import inisetup
vfs = inisetup.setup()
gc.collect()
|
9951248 | from decimal import Decimal, ROUND_HALF_UP
def display_summary(loan, reference_date=None):
"""Display a legible summary of a loan.
Parameters
----------
loan : Loan, required
Loan to be displayed.
reference_date : date, optional
Date object with the date to consider as reference w... |
9951275 | from featureforge.feature import output_schema
@output_schema({str})
def bag_of_left_entity_IOB_chain(datapoint):
print (hash(datapoint))
eo = datapoint.left_entity_occurrence
return set()
def _bag_of_eo_IOB_chain(datapoint, eo):
tokens = datapoint.segment.tokens
eo_tokens = tokens[eo.segment_of... |
9951277 | from expert.src.model import Model
from tensorflow.keras.callbacks import CSVLogger, ReduceLROnPlateau, EarlyStopping
from expert.src.utils import read_genus_abu, read_labels, load_otlg, zero_weight_unk, parse_otlg, get_dmax
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.optimizers imp... |
9951284 | from pexpect import pxssh
import os
from secistsploit.core.exploit import *
from secistsploit.core.tcp.tcp_client import TCPClient
class Exploit(TCPClient):
__info__ = {
"name": "ssh_login",
"description": "ssh_login",
"authors": (
"jjiushi",
),
"references": (
... |
9951353 | from dash import html
import dash
dash.register_page(__name__, top_nav=True)
layout = html.Div("About page content")
|
9951365 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from mayavi import mlab
import time, sys
import scipy
from PIL import Image, ImageDraw
##################
# MAIN FUNCTIONS #
##################
def create_block_diagram(strat,dx,ve,xoffset,yoffset,scale,ci,strat_switch,contour_switch,bottom,topo_min... |
9951371 | import numpy as np
import random
import time
from auv_math import quat
import thruster_manager
import argparse # don't import auv_var_lib
from shm import gx4, kalman, motor_desires, desires, control_internal_wrench
import shm
import sys
import json
# next steps:
# measure and print out least squares error for inverse
... |
9951403 | import cv2
import numpy as np
help(cv2.resize)
ocv = cv2.imread('../im/EaiLU.png')
#ocv = cv2.resize(ocv, None, fx=2,fy=2)
mser = cv2.MSER_create()
gray = cv2.cvtColor(ocv, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
regions = mser.detectRegions(gray, None)
#print regions
for r in regions:
if cv2.contourAre... |
9951421 | import os
# Jira configuration loader
class JIRAConfig:
def get_jira_url(self):
jira_url = os.environ.get("JIRA_API")
return jira_url
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.