id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11560336 | from pointers import fopen, fprintf, fclose
file = fopen("/dev/null", "w")
fprintf(file, "hello world")
fclose(file)
|
11560358 | import os
import numpy as np
import pickle
import torch
from yacs.config import CfgNode
from .dataset import Dataset
from .utils import get_example
class BatchedImageDataset(Dataset):
def __init__(self,
cfg: CfgNode,
dataset_file: str,
img_dir: str,
... |
11560395 | import numpy as np
import matplotlib.pyplot as plt
from pybasicbayes.util.text import progprint_xrange
from pyhsmm.basic.distributions import PoissonDuration
import pyhsmm_spiketrains.models
reload(pyhsmm_spiketrains.models)
# Set the seed
seed = 0
print "setting seed to ", seed
np.random.seed(seed)
# Generate a sy... |
11560406 | import pandas as pd
import os
from tqdm.notebook import tqdm
# read csv
df = pd.read_csv('thaisum.csv', encoding='utf-8')
'''
Conditions
________________________
if type is not null
________________________
1. 'ทั่วไทย' = {'ภูมิภาค'}
2. 'การเมือง' = {'ความมั่นคง', 'เลือกตั้ง', }
3. 'สังคม'
4. 'กีฬา' = {'ฟุตบอลยุโ... |
11560411 | import requests
import json
import pandas as pd
def QA_fetch_get_future_domain():
"""
获取快期的主连代码
return [list]
"""
res = pd.DataFrame(json.loads(requests.get("https://openmd.shinnytech.com/t/md/symbols/latest.json").text)).T
return res.loc[res.ins_name.str.contains('主连')].underlying_symbol.app... |
11560414 | import os
import sys
import subprocess as sp
from shutil import rmtree
from subprocess import TimeoutExpired
import renv
import logging
logger = logging.getLogger(__name__)
def get_system_venv():
if os.name == "posix":
if sys.platform == "darwin":
renv.MacRenvBuilder()
elif "linux" in... |
11560423 | import gridfs
import pymongo
from . import message
class YahooBackupDB:
"""Interface to store Yahoo! Group messages to a MongoDB. Group data is stored in a database
whose name is the same as the group name. File data is stored in that database name plus `_gridfs`, where
the gridfs _id is teh same as the ... |
11560447 | import unittest
from unittest.mock import patch
from datetime import datetime
from calendar import is_weekday
class CalendarTests(unittest.TestCase):
@patch('calendar.my_datetime', autospec=True)
def test_sunday_is_not_weekday(self, datetime_mock):
sunday = datetime(year=2020, month=4, day=26)
... |
11560465 | from django.urls import path
from . import views
app_name = "management"
urlpatterns = [
path('submissions', views.SubmissionsView.as_view(), name="submissions"),
path('user_management', views.UserManagementView.as_view(), name="user_management")
]
|
11560499 | import re
from . import Tripcode
__all__ = ['Public']
class Public (Tripcode):
"""
Represents a regular tripcode.
"""
pattern = re.compile(r'^!([\w\.\/]+)')
def __str__ (self):
"""
Returns a string representation.
"""
return '!' + super(Public, self).__str__()
|
11560520 | import sys
import re
from setuptools.command.test import test as TestCommand
from setuptools import setup
from setuptools import find_packages
metadata = dict(
re.findall("__([a-z]+)__ = '([^']+)'", open('vanilla/meta.py').read()))
requirements = [
x.strip() for x
in open('requirements.txt').readlines()... |
11560602 | import brownie
from brownie import ZERO_ADDRESS
import pytest
TEST_HASH = "TEST"
PRICE = 100
@pytest.mark.parametrize("price", [0, 100, 1e18])
def test_purchase(alice, bob, market, token, token_id, price):
market.makeSellOffer(token_id, price, {"from": alice})
bob_initial_balance = bob.balance()
alice_i... |
11560610 | class FoundValue:
"""
A class containing a record of a prop key existing in both an original props file and a translated props file
"""
common_path: str
original_file: str
translated_file: str
key: str
orig_val: str
translated_val: str
def __init__(self, common_path, original_fi... |
11560617 | import numpy as np
from PIL import Image
def intensity(arr):
# calcluates intensity of a pixel from 0 to 9
mini = 999
maxi = 0
for i in range(len(arr)):
for j in range(len(arr[0])):
maxi = max(arr[i][j],maxi)
mini = min(arr[i][j],mini)
level = float(float(maxi-mini)/float(10));
brr = [[0]... |
11560632 | import torch
from ..nn import XLogic, Conv2Concepts
def prune_logic_layers(model: torch.nn.Module, current_epoch: int, prune_epoch: int,
fan_in: int = None, device: torch.device = torch.device('cpu')) -> torch.nn.Module:
"""
Prune the inputs of the model.
:param model: pytorch mode... |
11560641 | import os
import json
import argparse
import pytest
from maggot import Experiment
from maggot import Config
@pytest.fixture
def simple_dict_config():
config = dict(
a=10,
b=[1, 2, 3],
c="a"
)
return config
@pytest.fixture
def nested_dict_config(simple_dict_config):
confi... |
11560656 | from datetime import datetime, timedelta
import numpy as np
import numexpr as ne
from netCDF4 import Dataset
from scipy.interpolate import CubicSpline
from typhon.utils import Timer
import xarray as xr
from .common import NetCDF4, expects_file_info
from .testers import check_lat_lon
__all__ = [
'AVHRR_GAC_HDF',
... |
11560675 | import logging
def basicConfig():
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s',
datefmt='%Y%m%dT%H:%M:%S')
|
11560684 | import numpy as np
import pytest
import torch
from probflow.distributions import Poisson
tod = torch.distributions
def is_close(a, b, tol=1e-3):
return np.abs(a - b) < tol
def test_Poisson():
"""Tests Poisson distribution"""
# Create the distribution
dist = Poisson(3)
# Check default params
... |
11560754 | import numpy as np
import matplotlib.pyplot as plt
def main():
# plot results for each experiment type and capacity
save_path = './results'
dataset = 'cub200'
for experiment_type in ['iid', 'class_iid']:
for c in [2, 4, 8, 16]:
acc_name = 'acc_' + experiment_type + '_' + dataset + ... |
11560806 | import json
from ast import literal_eval
import pandas as pd
import re
import sys
import os
from flask import Blueprint
from flask import jsonify
from flask import request
from flask import current_app as app
import numpy as np
from utillities.exceptions import ExceptionHelpers
mod = Blueprint('combine_dataframe', __n... |
11560868 | import torch
import torch.nn as nn
from utils.custom_modules import CausalConv1d, DTLNSeparationCore
from utils.training_process import TrainingProcess
class DTLN(nn.Module):
""" Dual-Signal Transformation Long Short-Term Memory Network.
Based on the work presented by <NAME> et. al for the
DNS INTERSPEEC... |
11560908 | import sys
from tqdm import tqdm
import mxnet as mx
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluoncv.data import mscoco
from gluoncv.data.transforms.pose import (flip_heatmap,
heatmap_to_coord_alpha_pose)
from gluoncv.data.transforms.presets.alpha_pose impo... |
11560911 | from office365.runtime.client_value import ClientValue
class PageLinks(ClientValue):
"""Links for opening a OneNote page."""
def __init__(self, onenote_client_url=None, onenote_web_url=None):
"""
:param str onenote_client_url: Opens the page in the OneNote native client if it's installed.
... |
11560954 | import os
import sys
import shutil
from subprocess import call, DEVNULL
from annogesiclib.multiparser import Multiparser
from annogesiclib.converter import Converter
from annogesiclib.format_fixer import FormatFixer
from annogesiclib.helper import Helper
class RATT(object):
'''annotation transfer'''
def __in... |
11560964 | from __future__ import annotations
import numpy as np
import tensorflow as tf
from .base_environment import BaseEnvironment
from tfne.helper_functions import read_option_from_config
class XOREnvironment(BaseEnvironment):
"""
TFNE compatible environment for the XOR problem
"""
def __init__(self, wei... |
11560965 | from __future__ import division, print_function, absolute_import
import tensorflow as tf
import functools
import numpy as np
from selfsup.util import DummyDict
from selfsup import ops, caffe
from selfsup.moving_averages import ExponentialMovingAverageExtended
import sys
def _pretrained_resnet_conv_weights_initializer... |
11560968 | import ctypes
# dll = windll.LoadLibrary('lib/dllcore.dll')
dll=ctypes.CDLL('lib/server2.dll')
# print(dll)
# dll.HelloWorld('WDNMD')
# print(dll.printX())
# a=dll.Double(123)
# print(dll.printX())
#
# print(type(a))
# print(a)
dll.init()
dll.wait()
# buff=dll.returnBuff(buffer)
# print(buff) |
11560974 | import numpy as np
from src.layers.pooling import MaxPoolLayer
class TestMaxPoolLayer:
def test_forward_pass_single_channel_single_item(self):
# given
pool_size = (2, 2)
stride = 2
activation = np.array([[
[[1], [2], [2], [1]],
[[3], [4], [0], [0]],
... |
11560986 | from typing import List
from ._types import Options, Key, KeyResponse
from ._utils import _request
class Keys:
_root = "/projects"
def __init__(self, options: Options) -> None:
self.options = options
async def list(self, project_id: str) -> KeyResponse:
"""Retrieves all keys associated w... |
11561002 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import math
import scipy.stats as stats
from torch.autograd import Variable
pixel_mean = Variable(torch.FloatTensor(
[115.9839754, 126.63120922, 137.73309306]).view(1, 3, 1, 1))
eps_div = 1e-... |
11561011 | import pytest
from policyglass import Action, Condition, EffectiveCondition
def test_bad_intersection():
with pytest.raises(ValueError) as ex:
EffectiveCondition(
frozenset({Condition("aws:PrincipalOrgId", "StringNotEquals", ["o-123456"])}), frozenset()
).intersection(Action("S3:*"))
... |
11561029 | from logic_analyzer.screen import Screen
from logic_analyzer.timing_collector import TimingCollector
from logic_analyzer.text_loader import TextLoader
class ScreenRenderer:
def __init__(self):
self.signals = []
self.visible_signals = []
self.failed_signals = []
self.requested_signals = []
self.temp_visible... |
11561058 | from src.utils import pdump, pload, bmtv, bmtm
from src.lie_algebra import SO3
from termcolor import cprint
from torch.utils.data.dataset import Dataset
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
import torch
import sys
class BaseDataset(Dataset):
... |
11561059 | from pylearning.model.tensorflow_base import tensorflow_base
from pyspark.sql import SparkSession
from pyspark import SparkContext
import tensorflow as tf
from pyspark.sql.functions import col
class train_boston(tensorflow_base):
@staticmethod
def pre_train():
spark_context = SparkContext.getOrCreate(... |
11561093 | import os
import shutil
import tempfile
import unittest
import yaml
from krsh.cmd.group_create.cmd_pipeline import cmd_create_pipeline
class TestCommandCreatePipeline(unittest.TestCase):
def setUp(self):
self.sample_path = os.path.join(os.path.dirname(__file__), "../../samples")
def test_create_pip... |
11561107 | import torch
import torch.nn.functional as F
import numpy as np
import logging
from sklearn.metrics import recall_score
def test(step, dataset_test, filename, unk_class, G, C1, threshold):
G.eval()
C1.eval()
all_pred = []
all_gt = []
entropy_scores = []
prob_scores = np.zeros([dataset_test.da... |
11561152 | import json
import pytest
import responses
from satosa.backends.orcid import OrcidBackend
from satosa.context import Context
from satosa.internal import InternalData
from satosa.response import Response
from unittest.mock import Mock
from urllib.parse import urljoin, urlparse, parse_qsl
ORCID_PERSON_ID = "0000-0000-0... |
11561166 | import argparse
import os.path
import sys
import torch
def get_custom_op_library_path():
if sys.platform.startswith("win32"):
library_filename = "custom_ops.dll"
elif sys.platform.startswith("darwin"):
library_filename = "libcustom_ops.dylib"
else:
library_filename = "libcustom_op... |
11561222 | import os
import argparse
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import experiment_descriptor as ed
import misc
import util.io
root = misc.get_root()
def get_dist(exp_desc, average):
"""
Get the average distance from observed data in every round.
"""
if average == 'me... |
11561232 | import datetime
import io
import json
import logging
import os
import pathlib
import re
import sys
import urllib.parse as urlparse
import uuid
import sarif_om as om
from jschema_to_python.to_json import to_json
from reporter.sarif import render_html
import lib.config as config
import lib.csv_parser as csv_parser
impo... |
11561240 | import logging
import os
import sys
# pylint: disable=wrong-import-position
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from deep_qa import run_model_from_file, evaluate_model
from deep_qa.common.checks import ensure_pythonhashseed_set
logger = logging.getLogger(__name__) # pylint: disable=invalid... |
11561275 | from flask import Flask
app = Flask(__name__)
# root or index
@app.route('/')
def index():
return "You have made it to the Index of my machine!"
# sub directories
@app.route("/hello")
def hello():
return "Hello there!"
@app.route("/idemo/<int:ivar>")
@app.route("/demo/<ivar>")
def showtype(ivar):
print(... |
11561284 | import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("MOGUA_ROOT", "~/.mogua/mainnet"))).resolve()
|
11561287 | from functools import wraps
from flask import session
from .errors import AuthError
def require_session(f):
@wraps(f)
def inner(*args, **kargs):
user_id = session.get('user_id')
if user_id is None:
raise AuthError()
return f(*args, user_id=user_id, **kargs)
return inne... |
11561334 | try:
import ujson
def dump_json(x):
return ujson.dumps(x, ensure_ascii=False, escape_forward_slashes=False)
except ImportError:
import json
def dump_json(x):
return json.dumps(x, ensure_ascii=False)
|
11561366 | import wx
from wx import glcanvas
import sys
import math
import cad
import Mouse
import Key
from RefreshObserver import RefreshObserver
import copy
graphics_canvases = []
repaint_registered = False
def OnRepaint():
global graphics_canvases
for g in graphics_canvases:
g.Refresh()
cla... |
11561373 | from IPython.core.magic import (Magics, magics_class, line_magic,
cell_magic, line_cell_magic)
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy import create_engine
from sqlalchemy import... |
11561385 | from enum import Enum, unique
__all__ = [
'ImportStatus', 'STATUS_MESSAGE', 'get_row_error_message', 'Error', 'IMPORT_RENAME_ZH',
'IMPORT_ERROR_RENAME', 'EXPORT_RENAME_ZH'
]
@unique
class ImportStatus(Enum):
UPLOADED = 4001
READING = 4002
VALIDATING = 4003
IMPORTING = 4004
COMPLETED = 40... |
11561412 | from .common import *
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
SECURE_SSL_REDIRECT = config('SSL', default=True, cast=bool)
DEBUG_PROPAGATE_EXCEPTIONS = True
|
11561455 | from django.contrib import admin
from .models import DepTour
class ToursAdmin(admin.ModelAdmin):
fields = [
"name",
"confirmed",
"datetime",
"email",
"phone",
"comments",
"deprel_comments",
]
readonly_fields = ("name", "email", "phone", "comments")
... |
11561459 | import functools
import os
import time
import numpy as np
from tqdm import tqdm
from .custom import CustomDataset
from .registry import DATASETS
from .utils import (
OpenImagesDetectionChallengeEvaluator,
get_categories,
read_dets,
read_gts,
)
@DATASETS.register_module
class OpenImagesDataset(Custom... |
11561476 | def split_the_bill(x):
people = total = 0
for k, v in x.iteritems():
people += 1
total += v
average = total / float(people)
return {k: round(v - average, 2) for k, v in x.iteritems()}
|
11561484 | import torch
import numpy as np
class MCEM:
def __init__(self, Y, model, device, niter_MCEM=100, niter_MH=40,
burnin=30, var_MH=0.01, NMF_rank=8):
self.device = device
self.model = model
self.Y = Y
self.F, self.T = self.Y.shape
self.X =torch.from_numpy((np.abs(Y)... |
11561488 | import logging
from asynctnt import Iterator
from asynctnt import Response
from asynctnt.exceptions import TarantoolSchemaError
from tests import BaseTarantoolTestCase
from tests.util import get_complex_param
class SelectTestCase(BaseTarantoolTestCase):
LOGGING_LEVEL = logging.INFO
async def _fill_data(self... |
11561567 | from ..error import IdentifierError
from ..objects.customer import Customer
from .base import ResourceBase
class Customers(ResourceBase):
RESOURCE_ID_PREFIX = "cst_"
def get_resource_object(self, result):
return Customer(result, self.client)
def get(self, customer_id, **params):
if not c... |
11561586 | import asyncio
import pytest
import logging
from privex.helpers.exceptions import CacheNotFound
log = logging.getLogger(__name__)
try:
from privex.helpers.cache.asyncx import AsyncMemcachedCache
# r = AsyncRedisCache()
except ImportError:
pytest.skip(msg="Failed to import AsyncMemcachedCache (???)",... |
11561663 | from sllist import *
def test_push():
colors = SingleLinkedList()
colors.push("Pthalo Blue")
assert colors.count() == 1
colors.push("Ultramarine Blue")
assert colors.count() == 2
colors.push("Ultramarine Violet")
assert colors.count() == 3
def test_pop():
colors = SingleLinkedList()
... |
11561695 | import cv2
import numpy as np
from pytorch_toolbelt.utils.torch_utils import rgb_image_from_tensor, to_numpy
from retinopathy.dataset import UNLABELED_CLASS
from retinopathy.models.regression import regression_to_class
def draw_classification_predictions(input: dict,
output: dict,... |
11561720 | import os
from smartsim.settings import SbatchSettings, SrunSettings
# ------ Srun ------------------------------------------------
def test_srun_settings():
settings = SrunSettings("python")
settings.set_nodes(5)
settings.set_cpus_per_task(2)
settings.set_tasks(100)
settings.set_tasks_per_node(... |
11561740 | from binascii import hexlify, unhexlify
from secp256k1 import Secp256k1 as Secp256k1_base, Message, SECRET_KEY_SIZE
from secp256k1.key import SecretKey, PublicKey
from ._libsecp256k1 import ffi, lib
PEDERSEN_COMMITMENT_SIZE = 33
MAX_PROOF_SIZE = 675
PROOF_MSG_SIZE = 64
MAX_WIDTH = 1 << 20
# Pedersen Commitment xG+vH... |
11561758 | import logging
import os
import hashlib
from galaxy_importer import exceptions as exc
log = logging.getLogger(__name__)
def sha256sum_from_fo(fo):
block_size = 65536
sha256 = hashlib.sha256()
for block in iter(lambda: fo.read(block_size), b""):
sha256.update(block)
return sha256.hexdigest()... |
11561762 | from .canvas import CanvasPDK
class tfr_prim(CanvasPDK):
def __init__(self, *args, **kwargs):
super().__init__()
self.metadata = {'instances': []}
def generate(self, ports, netlist_parameters=None, layout_parameters=None, *args, **kwargs):
assert len(ports) == 2
b_idx = (4... |
11561797 | import os
import pytest
import shutil
import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql import DataFrame
from gensim.models import KeyedVectors
from gensim.models import Word2Vec as GensimW2V
from pyspark.ml.feature import Word2VecModel as SparkW2VModel
from node2vec.embedding import Node2VecBa... |
11561800 | import gzip
import os
import logging
from genomic_tools_lib import Utilities, Logging
from genomic_tools_lib.data_management import KeyedDataSource, TextFileTools
def _to_al(comps):
return "{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(*comps).encode()
def _to_gl(comps, format):
return format.format(*comps).encode()
... |
11561827 | import terrascript
import terrascript.provider
class TestVariable:
def __init__(self):
self.cfg = terrascript.Terrascript()
def test_one_variable(self):
v = terrascript.Variable("name", type="string", default="Hello World")
assert isinstance(v, terrascript.NamedBlock)
assert i... |
11561859 | from __future__ import print_function
import sys
import time
import json
import boto3
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from datetime import datetime
#from cufacesearch.common.conf_reader import ConfReader
from ..common.conf_reader import ConfReader
# Cannot be imported... |
11561861 | from opytimizer.optimizers.swarm import FSO
# One should declare a hyperparameters object based
# on the desired algorithm that will be used
params = {
'beta': 0.5
}
# Creates a FSO optimizer
o = FSO(params=params)
|
11561872 | class SourceCoordinate(object):
_immutable_fields_ = ['_start_line', '_start_column', '_char_idx']
def __init__(self, start_line, start_column, char_idx):
self._start_line = start_line
self._start_column = start_column
self._char_idx = char_idx
def get_start_line(self):
... |
11561876 | class Solution:
def countOrders(self, n: int) -> int:
MOD = 10 ** 9 + 7
result = 1
for i in range(2, n + 1):
result = result * (i * 2 - 1) * i % MOD
return result
|
11561878 | import os
import unittest
from programytest.client import TestClient
class ArrowUDCTestClient(TestClient):
def __init__(self):
TestClient.__init__(self)
def load_storage(self):
super(ArrowUDCTestClient, self).load_storage()
self.add_default_stores()
self.add_categories_store... |
11561962 | import argparse
def get():
parser = argparse.ArgumentParser()
parser.add_argument("-M",
"--model-file",
type=str,
default=None)
parser.add_argument("-d",
"--train-dataset",
type=str,
... |
11561975 | from django.apps import AppConfig
class DwitterConfig(AppConfig):
name = 'dwitter'
def ready(self):
# Register signals
import dwitter.signals # noqa: F401
|
11561988 | import numpy as np
from pyrr import Matrix44
import moderngl
from ported._example import Example
class InstancedCrates(Example):
'''
This example renders 32x32 crates.
For each crate the location is [x, y, sin(a * time + b)]
There are 1024 crates aligned in a grid.
'''
title = "In... |
11562007 | import os
import bs4
from bs4 import BeautifulSoup
from datauri import DataURI
class EmbeddableTag:
CSS = "css"
JS = "js"
IMAGE_PNG = "image_png"
IMAGE_SVG = "image_svg"
MAP = {
CSS: {"attr": "href", "type": "text/css"},
JS: {"attr": "src", "type": "text/javascript"},
IMA... |
11562010 | import unittest
import logging
import sys
from pprint import pprint
from checks import dns_resolution
from checks.config import Config
class TestDNSResolution(unittest.TestCase):
def runTest(self):
"""Resolves www.google.com"""
url = 'https://www.google.com/'
config = Config(urls=[url])
... |
11562034 | from django.test import TestCase
from django.urls import reverse
from core.models import RecordGroup, Job
from tests.utils import TestConfiguration, most_recent_global_message
class RecordGroupViewTestCase(TestCase):
def setUp(self) -> None:
self.config = TestConfiguration()
self.client.force_log... |
11562036 | class HashTable:
def __init__(self):
self.max = 10
self.arr = [[] for _ in range(self.max)]
def get_hash(self, key):
hash_value = 0
for char in key:
hash_value += ord(char)
return hash_value % self.max
def __getitem__(self, key):
hash_value = sel... |
11562091 | from unittest import TestCase
from signalflowgrapher.common.geometry import rotate, move, distance, collinear
import math
class TestGeometry(TestCase):
def test_full_rotate(self):
point = (10, 10)
origin = (0, 0)
(x, y) = rotate(origin, point, 2 * math.pi)
self.assertAlmostEqual(... |
11562106 | import torch.nn as nn
import torch.nn.functional as F
class SeparableConv2d(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, padding=1, dilation=1, bias=False, args=None):
super(SeparableConv2d, self).__init__()
self.args = args
self.conv1 = nn.Conv2d(inplanes, inpl... |
11562125 | import os, sys, subprocess, glob
import os.path as path
from shutil import copyfile
def copy_code(source_dir, dest_dir, exclude_dirs=[], exclude_files=[]):
"""
Copies code from source_dir to dest_dir. Excludes specified folders and files by substring-matching.
Parameters:
source_dir (string): loc... |
11562128 | import os
import sys
import time
import smbus
from imusensor.MPU9250 import MPU9250
address = 0x68
bus = smbus.SMBus(1)
imu = MPU9250.MPU9250(bus, address)
imu.begin()
# imu.caliberateGyro()
# imu.caliberateAccelerometer()
# or load your own caliberation file
#imu.loadCalibDataFromFile("/home/pi/calib_real_bolder.jso... |
11562158 | import os
import sys
import json
import pandas as pd
from pandas.io.json import json_normalize
from celery_connectors.utils import ev
from spylunking.log.setup_logging import console_logger
from network_pipeline.utils import ppj
from network_pipeline.utils import rnow
from network_pipeline.build_packet_key import build... |
11562174 | import itertools
import torch
import torch.nn.functional as F
import models.stn as stn
from util.tb_visualizer import TensorboardVisualizer
from . import networks
from .base_model import BaseModel
class NEMARModel(BaseModel):
"""
NeMAR: a neural multimodal adversarial image registration network.
This cl... |
11562182 | from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
maxim = SchLib(tool=SKIDL).add_parts(*[
Part(name='DS1267_DIP',dest=TEMPLATE,tool=SKIDL,keywords='Dual Digital Potentiometer Maxim',description='Dual Digital Potentiometer, Serial, 256 Steps, DIP-14',ref_prefix='U',num_units=1,fp... |
11562207 | import os
import sys
import argparse
import re
import xml.etree.ElementTree as xml_et
from xml.dom import minidom
assert sys.version_info >= (3, 5)
def scan_cpp(base_path, rel_project_path):
test_project_path = os.path.join(base_path, rel_project_path)
if not os.path.isdir(test_project_path):
print('... |
11562220 | from bokeh.embed import json_item
import json
import os
from random import choices
from string import ascii_letters
import streamlit.components.v1 as components
_RELEASE = True
if not _RELEASE:
_component_func = components.declare_component(
"streamlit_bokeh_events", url="http://localhost:3001",
)
el... |
11562241 | import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn.svm import SVC as svc
from sklearn.metrics import accuracy_score
import os
import sys
eps = sys.float_info.epsilon
training_data = pd.read_csv(os.getenv('TRAINING'), header=0)
tournament_data = pd.read_csv(os.getenv('TESTING'), h... |
11562285 | import numpy as np
import urllib2
import os
import scipy.io as spio
from functools import partial
import multiprocessing
import argparse
from PIL import Image
from StringIO import StringIO
import traceback
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
MAT_URL = 'http://vision.cs.princeton.edu/projects/2010/S... |
11562311 | import logging
import os
class ModelLogger:
"""A logger specific for the tasks of the ModelAdvancer"""
def __init__(self):
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
self.logger = logging.getLogger('simulation')
self.formatter = logging.Formatter('%(asctime)s - %(na... |
11562320 | import base64
import json
import os
import re
import requests
import shutil
import subprocess
import tempfile
def client_error(message):
print('Client error:', message)
return {
'statusCode': 400,
'headers': { 'Content-Type': 'application/json' },
'body': json.dumps({ 'error': message })
}
... |
11562321 | from detectron2.utils.visualizer import Visualizer, GenericMask, _create_text_labels, ColorMode, random_color, _SMALL_OBJECT_AREA_THRESH
import numpy as np
class SORVisualizer(Visualizer):
def __init__(self, image, metadata, instance_mode=ColorMode.IMAGE):
super(SORVisualizer, self).__init__(
... |
11562393 | import exceptions
import model
import dataclasses
import typing
import ujson
import http
@dataclasses.dataclass
class Model:
"""Represents a NeuroAI text generation model."""
identifier: str = "60ca2a1e54f6ecb69867c72c"
response_length: int = 200
remove_input: bool = False
temperature: float = 0.9... |
11562431 | import pickle
import codecs
def load_pickle(path):
with codecs.open(path, 'rb') as input_f:
return pickle.load(input_f)
|
11562442 | from .missing_element_base import MissingElementBase
from .missing_fieldset_entry import MissingFieldsetEntry
class MissingFieldset(MissingElementBase):
def __repr__(self):
if self._key:
return f"<class MissingFieldset key={self._key}>"
return '<class MissingFieldset>'
def entries... |
11562451 | import os
from setuptools import setup
here = lambda *a: os.path.join(os.path.dirname(__file__), *a)
# read the long description
with open(here('README.md'), 'r') as readme_file:
long_description = readme_file.read()
# read the requirements.txt
with open(here('requirements.txt'), 'r') as requirements_file:
... |
11562463 | from abc import ABC
from dataclasses import InitVar, dataclass, field
from typing import Dict, List, Set, Tuple, Union
import optuna
from typing_extensions import Final
from embeddings.hyperparameter_search.configspace import (
BaseConfigSpace,
Parameter,
SampledParameters,
)
from embeddings.hyperparamete... |
11562469 | from xenon.base.datatypes import Sweepable
from xenon.base.designsweeptypes import ExhaustiveSweep
from benchmarks import params
class Benchmark(Sweepable):
sweepable_params = [
params.cycle_time,
params.pipelining,
params.cache_size,
params.cache_assoc,
params.cache_hit_latency,
... |
11562472 | import json
import os
import sys
import argparse
from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
from shutil import copyfile
kernel_json = {
"argv":[sys.executable,"-m","seq_kernel", "-f", "{connection_file}"],
"display_name":"Seq",
"language":"... |
11562524 | import os
import numpy as np
import torch
import cv2
import argparse
import segmentation_models_pytorch as smp
from segmentation_models_pytorch.encoders import get_preprocessing_fn
import sys
sys.path.append('../Common')
from tool_clean import get_image_patch_deep, get_image_patch, check_is_image
# make step1 predic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.