id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1717694 | import sqlalchemy as sa
from sqlalchemy import ForeignKey
from mlcomp.db.models.base import Base
class Docker(Base):
__tablename__ = 'docker'
name = sa.Column(sa.String, primary_key=True)
computer = sa.Column(sa.String,
ForeignKey('computer.name'),
prima... |
1717698 | from TestAsynchSource import TestAsynchSource
from TestAsynchSink import TestAsynchSink
from TestMemory import TestMemory
|
1717705 | class Push():
def __init__(self, **kwargs):
self.author = kwargs.get('author')
self.content = kwargs.get('content')
self.datetime = kwargs.get('datetime')
self.push = kwargs.get('push')
def __str__(self):
return '<Push> %s %s' % (self.push, self.author)
class Post():
... |
1717718 | from __future__ import print_function
import collections
import os
import os.path
import shutil
from egnyte import exc, base, resources, audits, events
class EgnyteClient(base.Session):
"""Main client objects. This should be the only object you have to manually create in standard API use."""
@property
d... |
1717735 | from rick_roll_detector.image import verify_image
import cv2
# vid_cap has to be a cv2.VideoCapture()
def verify_video(vid_cap: cv2.VideoCapture) -> bool:
success, image = vid_cap.read()
while success:
success, image = vid_cap.read()
# If the video ended return false.
if not success:
... |
1717748 | from sklearn.ensemble import RandomForestClassifier
class AppScanner(object):
def __init__(self, threshold=0.9):
"""AppScanner object for recognising applications in network traffic.
This implementation uses a Single Large Random Forest.
Parameters
----------
... |
1717751 | import openpathsampling as paths
from openpathsampling.ensemble import EnsembleCache
def default_state_progress_report(n_steps, found_states, all_states,
timestep=None):
"""
Default progress reporter for VisitAllStatesEnsemble.
Note that it is assumed that all states have... |
1717781 | import numpy as np
from tqdm import tqdm
import torch
from torch.jit import load
from torch.utils.data import DataLoader, Dataset
from mlcomp.contrib.transform.tta import TtaWrap
def apply_activation(x, activation):
if not activation:
return x
if activation == 'sigmoid':
return torch.sigmoid... |
1717786 | import torch
from allennlp.common import Registrable, Params
from torch import nn
from torch.nn import functional as F
from transformers.models.t5.modeling_t5 import T5LayerNorm
from gpv2.utils import pytorch_utils
from gpv2.utils.to_params import to_params
class Layer(Registrable, nn.Module):
"""Generic class fo... |
1717810 | import json
from typing import List, Tuple
import pandas as pd
from gobbli.dataset.base import BaseDataset
from gobbli.util import download_archive
class MovieSummaryDataset(BaseDataset):
"""
gobbli Dataset for the CMU Movie Summary dataset, framed as a multilabel
classification problem predicting movie... |
1717846 | import copy
from oictest.prof_util import DISCOVER
from oictest.prof_util import REGISTER
from oictest.prof_util import RESPONSE
from oictest.prof_util import _update
__author__ = 'roland'
PMAP = {"C": "Basic",
"I": "Implicit (id_token)", "IT": "Implicit (id_token+token)",
"CI": "Hybrid (code+id_token... |
1717857 | import numpy as np
import tensorflow as tf
from embeddings import text_embeddings
from evaluation import appleveleval
from models import wordpair_model
from helpers import io_helper
from helpers import data_shaper
import random
import itertools
from ml import loss_functions
from ml import trainer
from evaluation import... |
1717902 | import pytest
def load_json_data(path):
import json
with open(path, 'r') as f:
return json.load(f)
TEST_VECTORS = [
('test_data/ca.json', 'test_data/ca_result.json'),
('test_data/messy.json', 'test_data/messy_result.json'),
]
@pytest.mark.parametrize("input, expected", TEST_VECTORS)
def t... |
1717925 | import common
import os
import sys
# Changes the current directory to the script directory so the virtual
# environment is created in a consistent place.
os.chdir(common.script_dir)
# Virtual environment exists.
if os.path.isdir ('venv/'):
print('Virtual environment already exists at venv/')
sys.exit(0)
com... |
1717965 | import sys
from pymldb import Connection
from rec.settings import HOST, PREFIX
if __name__ == '__main__':
if len(sys.argv) > 1:
whats = sys.argv[1:]
else:
whats = ['datasets', 'procedures', 'functions']
mldb = Connection(HOST)
prefix = PREFIX
for what in whats:
for x in ge... |
1717992 | import torch
from torch.optim.optimizer import Optimizer
class RiemannianOptimizer(Optimizer):
"""Riemannian stochastic gradient descent"""
def __init__(self, params, lr, param_names):
defaults = dict(lr=lr)
super(RiemannianOptimizer, self).__init__(params, defaults)
self.param_names ... |
1718015 | from typing import Any, Dict, List, Optional, Set, Union
from paralleldomain.decoding.cityscapes.common import CITYSCAPE_CLASSES, get_scene_path
from paralleldomain.decoding.cityscapes.frame_decoder import CityscapesFrameDecoder
from paralleldomain.decoding.cityscapes.sensor_decoder import CityscapesCameraSensorDecode... |
1718030 | from django.shortcuts import render
from django.db.models import Sum
from pdl.models import Proyecto
from pdl.models import Seguimientos
from stats.models import ComisionCount
from stats.models import Dispensed
from stats.models import WithDictamenButNotVoted
LEGISLATURE = 2016
def dame_sin_tramitar(numero_de_proy... |
1718066 | import ipywidgets as widgets
from IPython.display import clear_output
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from dtreeplt import dtreeplt
def view_interactive(feature_names, target_names, X, y, clf, eval, dis... |
1718085 | import pytest
from tests.functional.services.api.accounts.users import create_ft_account_user
from tests.functional.services.api.conftest import FT_ACCOUNT, USER_API_CONFS
from tests.functional.services.utils.http_utils import APIResponse, http_del
@pytest.mark.parametrize("api_conf", USER_API_CONFS)
class TestAdmin... |
1718104 | import torch
import torchvision
import pandas as pd
import numpy as np
def jaccard(y_true, y_pred):
""" Jaccard a.k.a IoU score for batch of images
"""
num = y_true.size(0)
eps = 1e-7
y_true_flat = y_true.view(num, -1)
y_pred_flat = y_pred.view(num, -1)
intersection = (y_true_fl... |
1718122 | from .config import SimpyderConfig
class Scheduler():
def __init__(self, spiders=[]):
super().__init__()
self.spiders = spiders
def run_spiders(self):
for each_spider in self.spiders:
each_spider.run()
|
1718129 | import torch
from scipy.stats import uniform, bernoulli
import numpy as np
def element_wise_sample_lambda(sampling, lambda_choices, encoding_mat, batch_size=128, probs=-1):
'''
Elementwise sample and encode lambda.
Args:
sampling: str. sample scheme.
lambda_choices: list of floats. Use... |
1718134 | from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if not nums:
return nums
n = len(nums)
res = []
tmp = [None for i in nums]
used = [0 for i in nums]
def permute_all(cur_idx):
if cur_idx == n:
... |
1718161 | import argparse
import importlib
import inspect
import os
import glob
from typing import Callable
from pydantic import BaseModel
class PlaybookDescription(BaseModel):
function_name: str
docs: str = None
src: str
src_file: str
action_params: dict = None
def get_function_params_class(func: Callabl... |
1718180 | from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from loader import data_loader
from parser import get_training_parser
from utils import *
from models import CausalMotionModel
from losses import criterion
from visualize import draw_image, draw_solo, draw_solo_all
def main(args):
# Set envi... |
1718188 | import argparse
import logging
import os
import sys
import time
from types import SimpleNamespace
import falcon
import lawrouge
import pandas
from falcon_cors import CORS
import json
import waitress
logging.basicConfig(level=logging.INFO, format='%(asctime)-18s %(message)s')
logger = logging.getLogger()
cors_allow_al... |
1718199 | import os
import cv2
from tqdm import tqdm
import argparse
def parsePaths(path):
name_parts=path.split('_')
mask_path = path.replace('composite_images','masks')
mask_path = mask_path.replace(('_'+name_parts[-1]),'.png')
target_path = path.replace('composite_images','real_images')
target_p... |
1718202 | import scipy.special as sp
import numpy as np
# Reference:
# [1] <NAME>, Stegun IA (1972) Handbook of Mathematical Functions with Formulas, Graphs,
# and Mathematical Tables. U.S. Department of Commerce, NIST
# generate tables 9.* starting at page 390 of [1]
def gentable(X):
# header
l = '%5s %18s %13s... |
1718226 | from __future__ import division
from __future__ import print_function
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=100, help='Number of epochs to train.')
parser.add_argument('--split',nargs='+', type=float, default=[0.9, 0.1, 0.], help="train, test, validation ... |
1718238 | import torch
import numpy as np
import TorchSUL.Model as M
class IntegrationNet(M.Model):
def initialize(self):
self.fc1 = M.Dense(512, activation=M.PARAM_GELU)
self.fc2 = M.Dense(512, activation=M.PARAM_GELU)
self.fc3 = M.Dense(512, activation=M.PARAM_GELU)
self.fc4 = M.Dense(2)
def forward(self, pts, d... |
1718243 | import os
import itertools
import io
import shutil
from kibitzr.compat import sh
from .utils import normalize_filename
def report_changes(conf, content):
return PageHistory(conf).report_changes(content)
class PageHistory(object):
"""
Single file changes history using git
"""
STORAGE_DIR = "pag... |
1718260 | import argparse
import os
import json
import faiss
import numpy as np
import pandas as pd
from data import create_multi_splits
from validate import L2norm
from validate import retrieve, KNN, score
# Training settings
parser = argparse.ArgumentParser(description='PyTorch SBIR')
parser.add_argument('--dir-path', type=s... |
1718278 | from datetime import datetime
from django_celery_beat.models import CrontabSchedule, PeriodicTask
from config import celery_app
from {{cookiecutter.project_slug}}.example_app.utils.crawl_earnings_whispers import CrawlEarningsWhispers
from {{cookiecutter.project_slug}}.example_app.utils.{{cookiecutter.project_slug}}_m... |
1718344 | import b3
# run all the children (regardless of status)
# return success if any child succeeds
# equvalent to logical OR
# added by <NAME> 06/2017
# Copyright 2017 University of Washington
# Developed by <NAME> <dianmuz at uw.edu> and
# <NAME> <blake at uw.edu>
# BioRobotics Lab, University of Washington
# Redistri... |
1718385 | from click.testing import CliRunner
from pybo.cli import cli, profile_update
def test_tok():
runner = CliRunner()
runner.invoke(cli, ["tok", "tests/resources/shelving/", "--tags", "pl"])
def test_extract_rules():
runner = CliRunner()
runner.invoke(cli, ["extract-rules", "tests/resources/step2/step2... |
1718402 | import logging
import asyncio
from aiohttp import web
from argparse import ArgumentParser
import os
import getpass
import Globals
from account import Account
import kademlia.network as kad
from rpc import RPCDispatcher
# from kademlia.network import Server
# import json
# import rlp
# from rlp.sedes import text, big_e... |
1718410 | import matplotlib.pyplot as plt
import numpy as np
from selfdrive.config import Conversions as CV
x = [0.0, 1.4082, 2.8031, 4.2266, 5.3827, 6.1656, 7.2478, 8.2831, 10.2447, 12.964, 15.423, 18.119, 20.117, 24.4661, 29.0581, 32.7101, 35.7633]
y = [0.218, 0.222, 0.233, 0.25, 0.273, 0.294, 0.337, 0.362, 0.38, 0.389, 0.398... |
1718421 | import pytest
from aiogram.dispatcher.filters.state import State, StatesGroup, any_state, default_state
class MyGroup(StatesGroup):
state = State()
state_1 = State()
state_2 = State()
class MySubGroup(StatesGroup):
sub_state = State()
sub_state_1 = State()
sub_state_2 = State... |
1718434 | import os
import sys
import json
import random
from random import choice
from jinja2 import Environment, select_autoescape, FileSystemLoader
TOPOLOGY_PATH = "MulVAL_P/"
GENERATION_TOPOLOGY_TEMPLATE = "topology_template.P"
GENERATION_TOPO_GEN_TEMPLATE = "topo_gen_template.P"
env = Environment(loader=FileSystemLoader('.... |
1718445 | import itertools
import os
import time
from datetime import datetime
import numpy as np
import torch
import torchvision.utils as vutils
import utils
from cyclegan import Generator as cycG
from cyclegan import Discriminator as cycD
def _weights_init(m):
classname = m.__class__.__name__
if classname.find('C... |
1718464 | import os
import energym
from energym.envs.env_fmu import EnvFMU
from energym.envs.utils.weather import EPW
from energym.envs.weather_names import WEATHERNAMES
class EnvEPlusFMU(EnvFMU):
"""Base class for EnergyPlus based FMU simulation models.
Subclasses EnvFMU and inherits its behavior. Defines EnergyPlus... |
1718485 | import numpy as np
# from svmlight_loader import load_svmlight_file, dump_svmlight_file
from sklearn.datasets import load_svmlight_file, dump_svmlight_file
import networkx as nx
import scipy
import pickle
import os
import os.path
from scipy.sparse import csr_matrix
def mkdir_if_not_exists(dir_path):
try:
... |
1718491 | class Solution(object):
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
# https://discuss.leetcode.com/topic/51131/space-o-mn-and-o-n-python-solutions
dp = [[0 for j in xrange(0, len(t) + 1)] for i in xrange(0, len(s) + 1)]
f... |
1718503 | from PIL import ImageFont, Image, ImageDraw
import numpy as np
import cv2
# bg_path = '/home/cwq/code/ocr_end2end/text_gen/bg/000000088218.jpg'
from gists.outline import draw_border_text
bg_path = '/home/cwq/code/text_renderer/data/bg/paper1.png'
font_path = '/home/cwq/code/ocr_end2end/text_gen/fonts/chn/msyh.ttc'
C... |
1718528 | import os
from ..log_utils import get_logger
MHWD_CONF_PATH = "/etc/X11/xorg.conf.d/90-mhwd.conf"
def remove_mhwd_conf():
logger = get_logger()
try:
os.remove(MHWD_CONF_PATH)
logger.info(
"Found MHWD-generated Xorg config file at %s. Removing.", MHWD_CONF_PATH)
except FileNo... |
1718553 | import cPickle
import json
import numpy as np
import pandas as pd
import time
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn import preprocessing
t = time.time()
#load paths for feature files
with open('SETTINGS.json') as f:
settings = json.load(f)
path_features=str(set... |
1718580 | from zipfile import ZipFile
from flask import request
from flask import Response
import json
import os
import shutil
import stat
import flask
import werkzeug
import logging
from datetime import datetime
from app.backend.api import app_flask
file_manager = flask.Blueprint('file_manager', __name__)
logger = logging.g... |
1718590 | n = int(raw_input())
data = [int(i) for i in raw_input().split()]
q = int(raw_input())
for i in xrange(q):
x = int(raw_input())
if x in data:
print data.index(x),
print len(data) - 1 - data[::-1].index(x)
else:
print -1,
print -1
|
1718610 | from django.urls import path
from . import views
urlpatterns = [
path('', views.technology_index, name='technology_index'),
path('search/', views.search_technology, name='search_technology'),
path('<int:pk>/', views.technology_detail, name='technology_detail'),
] |
1718627 | import secure_smtpd.config
from secure_smtpd.config import LOG_NAME
from .smtp_server import SMTPServer
|
1718643 | from __future__ import unicode_literals
from django.apps import AppConfig
class GeopageConfig(AppConfig):
name = 'geopage'
|
1718673 | import argparse
parser = argparse.ArgumentParser(description='LSTM CNN Classification')
parser.add_argument('--device', type=str, default='/gpu:0')
parser.add_argument('--logdir', type=str, default='logdir')
parser.add_argument('--epochs', type=int, default=40)
parser.add_argument('--batch_size', type=int, default=16... |
1718685 | import discord
import asyncio
import os
import math
import feedparser
import requests
import shlex
import database
import bom
import utils
from settings import *
from datetime import datetime, time, timezone
from random import choice
from discord.ext import commands
from discord.utils import get
import atexit
CURR... |
1718697 | from magma import *
from .ROM import ROMN
from .flatcascade import FlatCascade
__all__ = ['Decode']
def Decode(i, n, invert=False):
"""
Decode the n-bit number i.
@return: 1 if the n-bit input equals i
"""
if n <= 8:
i = 1 << i
if invert:
m = 1 << n
mask =... |
1718724 | from collections import defaultdict
from typing import Dict, Tuple, Iterable, List
import torch
from torch import Tensor
from deepstochlog.context import Context
from deepstochlog.network import NetworkStore
class RequiredEvaluation:
def __init__(self, context: Context, network_name: str, input_args: Tuple):
... |
1718749 | from __future__ import absolute_import, unicode_literals
from django.urls import re_path
from django.views.generic.base import TemplateView, RedirectView
from . import views
app_name = 'frontend'
urlpatterns = [
re_path(
r'^$',
view=TemplateView.as_view(template_name="frontend/index.html"),
... |
1718833 | import pytest
from hypothesis import given
from hypothesis.strategies import text
from graphein.rna.edges import (
add_all_dotbracket_edges,
add_base_pairing_interactions,
add_phosphodiester_bonds,
)
from graphein.rna.graphs import (
RNA_BASES,
SUPPORTED_DOTBRACKET_NOTATION,
construct_rna_graph... |
1718879 | from abc import ABC
from typing import Dict, Sequence, Optional, List, Any
from allenact.base_abstractions.experiment_config import ExperimentConfig
from allenact.base_abstractions.sensor import Sensor
class GymBaseConfig(ExperimentConfig, ABC):
SENSORS: Optional[Sequence[Sensor]] = None
def _get_sampler_a... |
1718913 | import json
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from solc import compile_files
from solc.utils.string import force_bytes
from web3.utils.validation import validate_address
from jobboard import utils
class MemberInterface:
def __init__(self, contract_addres... |
1718952 | from django.shortcuts import render
from .forms import SignupForm, CustomAuthenticationForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from .tokens impor... |
1718971 | test = {
'name': '',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> b_backwards
'.WH tsrif eht fo dne eht si sihT .atad ht1w krow ot elba eb ot tnatropm1 s1 t1 .X-ataD tuoba det1cxe os ma 1'
""",
'hidden': False,
'locked': Fal... |
1718989 | import threading
import time
def func_1():
while True:
print(f"[{threading.current_thread().name}] Printing this message every 2 seconds")
time.sleep(2)
# initiate the thread with daemon set to True
daemon_thread = threading.Thread(target=func_1, name="daemon-thread", daemon=True)
# or
# daemon_th... |
1719008 | from flat_topped_hex import *
from updown_tri import tri_center
import unittest
class TestFlatToppedHex(unittest.TestCase):
def test_rect1(self):
rect = (0, 0, 0, 3, 3, False, False)
self.assertListEqual(list(hex_rect(*rect)), [
(0, 0, 0),
(0, 1, -1),
(0, 2, -2)... |
1719016 | from operator import attrgetter
class Group:
"""
A group may consist of one or more students and has a
direct connection to a group on Canvas in which students
are either assigned or self select into groups through
the "people" page. In the case that students are not
assigned to a group, a ... |
1719028 | import sys
import pytest
needs_py37 = pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7+")
needs_py39 = pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9+")
needs_py310 = pytest.mark.skipif(
sys.version_info < (3, 10), reason="requires python3.10+"
)
|
1719044 | import argparse
import json
import os
import snpe
import qti.aisw.dlc_utils as dlc
parser = argparse.ArgumentParser(description='Write ppq qparams to snpe dlc')
parser.add_argument('--input_dlc_model', default='snpe_quantized.dlc', help='path to snpe quantized dlc model')
parser.add_argument('--output_dlc_model', defa... |
1719075 | def int_or_none(x):
try:
return int(x)
except ValueError:
return None
def frame_idxs_type(arg):
"""Create frame idxs type from a string passed as argument.
# Returns
slice or list of idxs
"""
if ":" in arg:
return slice(*list(map(int_or_none, arg.split(":")... |
1719089 | import json
import pytest
from idempotency_key.encoders import BasicKeyEncoder
from idempotency_key.exceptions import MissingIdempotencyKeyError
def test_basic_encoding():
class Request:
path_info = "/myURL/path/"
method = "POST"
body = json.dumps({"key": "value"}).encode("UTF-8")
r... |
1719097 | import argparse
import sys
print(sys.argv[1:])
parser = argparse.ArgumentParser()
parser.add_argument("--exit", type=int, default=0)
args, unparsed = parser.parse_known_args()
sys.exit(args.exit)
|
1719121 | from matplotlib import pyplot as plt
from skimage import data, io
from skimage.feature import corner_harris, corner_subpix, corner_peaks
img = io.imread('image.png')
coords = corner_peaks(corner_harris(image), min_distance=5)
coords_subpix = corner_subpix(image, coords, window_size=13)
fig, ax = plt.subplots()
ax.i... |
1719180 | import sublime
import sublime_plugin
import sys
import re
if sys.version_info >= (3,):
from urllib.error import URLError
else:
from urllib2 import URLError
from ..xcc import Xcc
from ..ml_utils import MlUtils
class RunFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
contents = self.view.substr(subl... |
1719194 | from typing import Set
import json
from qanta.datasets.abstract import AbstractDataset, TrainingData
class TriviaQADataset(AbstractDataset):
def __init__(self, answers: Set[str]):
super().__init__()
self.answers = answers
def training_data(self):
with open("data/external/unfiltered-we... |
1719217 | from pytest import mark, raises
from datetime import datetime as dt, timedelta as td
from olympusphotosync import utils
now = dt.now().replace(microsecond=0)
@mark.parametrize('spec,expect', [
('2017/11/20', dt(2017, 11, 20, 0, 0)),
('2017-11-20', dt(2017, 11, 20, 0, 0)),
('2017-10-29T... |
1719252 | from WebKit.HTTPServlet import HTTPServlet
class Forward1(HTTPServlet):
def respond(self, trans):
trans.application().forward(trans, 'Forward1Target' + trans.request().extraURLPath())
|
1719280 | from sqlalchemy.orm import Session
from redun import Scheduler, task
from redun.backends.db import Argument, CallNode, Execution
def test_record_args():
@task()
def task1(a, b):
return a + b
@task()
def task2(x):
return x
@task()
def main():
return task1(task2(2), ta... |
1719305 | from ares.defense.jpeg_compression import jpeg_compression
from ares.utils import get_res_path
import inception_v3
MODEL_PATH = get_res_path('./imagenet/inception_v3.ckpt')
def load(session):
model = InceptionV3Jpeg()
model.load(session, MODEL_PATH)
return model
@jpeg_compression(quality=75)
class In... |
1719382 | from __future__ import unicode_literals
import os
import time
import json
import logging
import requests
from nose.tools import assert_equals, assert_true, assert_is_not_none, assert_is_none, assert_false
RETRIES=100
TIMEOUT=3
def wait_for_automation_server():
logger.info('waiting for automation server')
co... |
1719390 | import os
import pytest
from freezegun import freeze_time
import numpy as np
# The line below is absolutely necessary. Fixtures are passed as arguments to test functions. That is why IDE could
# not recognized them.
from api.tests.utils.fixtures_tests import config_rollback_cameras, heatmap_simulation, config_rollback
... |
1719422 | from typing import Generator
import pytest
from graphdatascience.graph_data_science import GraphDataScience
from graphdatascience.query_runner.neo4j_query_runner import Neo4jQueryRunner
@pytest.fixture(autouse=True, scope="module")
def create_graph(runner: Neo4jQueryRunner) -> Generator[None, None, None]:
runne... |
1719425 | from fuzzconfig import FuzzConfig
import nonrouting
import fuzzloops
import re
cfg = FuzzConfig(job="LRAMINIT", device="LIFCL-40", sv="../shared/empty_40.v", tiles=["LRAM_CORE_R18C86:LRAM_INIT"])
def bin2dec(bits):
x = 0
for i, b in enumerate(bits):
if b:
x |= (1 << i)
return x
def ma... |
1719428 | from __future__ import annotations
import hashlib
import json
import logging
import pickle
from typing import Any, Dict, Generator, Optional
import pydantic
from pydantic import validator
import yaml
from turnips.model import ModelEnum
from turnips.meta import MetaModel
from turnips.multi import MultiModel, BumpMode... |
1719456 | from pyecore.ecore import EObject
from pygeppetto.visitors import Switch
def apply_single(eobject: EObject, fn, condition=lambda eobject: True):
for element in eobject.eAllContents():
if condition(element):
fn(element)
def apply(eobject: EObject, visitor: Switch):
visitor.do_switch(eobje... |
1719459 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.drivers import drivers
def test_drivers():
"""Test module drivers.py by downloading
drivers.csv and testing shape of
extracted data has 19... |
1719471 | from django.shortcuts import render
from hello.models import Counter
def say_hello(request):
counter = Counter.objects.first()
if counter == None:
counter = Counter(count=0)
counter.count = counter.count + 1
counter.save()
return render(request, "say_hello.html",
{'cou... |
1719488 | import torch, random
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from LibMTL.weighting.abstract_weighting import AbsWeighting
class PCGrad(AbsWeighting):
r"""Project Conflicting Gradients (PCGrad).
This method is proposed in `Gradient Surgery for Multi-Task Learning (NeurIPS ... |
1719502 | from unittest import TestCase
from unittest.mock import MagicMock
from iclientpy.codingui.distributedanalyst._aggregate import SummaryRegion, SummaryAnalystType, DistanceUnit, SummaryMesh
class AggregatePointsJobBuilderTest(TestCase):
def test_summary_mesh(self):
executor = MagicMock()
b... |
1719508 | from .asm import AsmFeature
from .cfg import CfgFeature
from .cg import CgFeature
from .data import DataFeature
from .functype import TypeFeature
class FeatureManager:
"""
new feature extraction module should be added here
"""
def __init__(self):
self.all_features = [
AsmFeature,
... |
1719511 | class Solution:
def compress(self, chars: List[str]) -> int:
count = start = 0
for i in range(len(chars)):
if i == len(chars) - 1 or chars[i] != chars[i + 1]:
chars[count] = chars[i]
count += 1
if i > start:
for c in str... |
1719514 | import argparse
import laspy
class lasview():
def __init__(self):
self.parse_args()
self.setup()
def parse_args(self):
parser =argparse.ArgumentParser(description = """Open a file in read mode and
print a simple description.""")
parser.ad... |
1719519 | from __future__ import absolute_import, division, print_function
import os
import os.path as osp
import pprint
import time
import numpy as np
import torch
import yaml
from torch.autograd import Variable
from torch.utils.data import DataLoader
from sacred import Experiment
from tracktor.config import get_output_dir
f... |
1719530 | import argparse
import os
import sys
import requests
import re
import json
TOKEN = None
BASE_URL = "https://slack.com/api/"
def get_channels():
url = BASE_URL + "channels.list"
params = {"token": TOKEN, "exclude_archived": 1}
r = requests.get(url, params=params)
r.raise_for_status()
return r.json(... |
1719538 | from logging import DEBUG
import pytest
import torch
from laia.common.arguments import OptimizerArgs, SchedulerArgs
from laia.dummies import DummyMNIST, DummyModel, DummyTrainer
from laia.engine import EngineModule
from laia.engine.engine_exception import EngineException
from laia.losses import CTCLoss
@pytest.mark... |
1719541 | from datetime import datetime
from dateutil.tz import tzlocal, tzutc
import pandas as pd
import numpy as np
from hdmf.backends.hdf5 import HDF5IO
from hdmf.common import DynamicTable
from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager
from pynwb.file import Subject
from pynwb.epoch import TimeIntervals
from... |
1719567 | import torch
import numpy as np
import copy
from torch.distributions.normal import Normal
from torch.distributions.cauchy import Cauchy
from .rk_parametric_order4stage4 import RKOrder4Stage4
from .rk_parametric_order3stage3 import RKOrder3Stage3
from .rk_parametric_order2stage2 import RKOrder2Stage2
from .euler impor... |
1719574 | from functools import partial
from graphql.utilities import build_schema
from graphql.validation.rules.unique_enum_value_names import UniqueEnumValueNamesRule
from .harness import assert_sdl_validation_errors
assert_errors = partial(assert_sdl_validation_errors, UniqueEnumValueNamesRule)
assert_valid = partial(asse... |
1719576 | import datetime
import os
import random
from vod_metadata import default_template_path
from vod_metadata.vodpackage import VodPackage
__all__ = ["generate_metadata"]
IMAGE_EXTENSIONS = [".bmp", ".jpg"]
def _check_for_ae(ae_type, movie_name, extensions):
ae_safe = ae_type.replace(' ', '_')
ae_paths = ['{}_{... |
1719609 | import random
import discord
from discord.ext import commands
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from loguru import logger
from cogs.utils.BookClub import BookClubModel
from .utils.checks import is_bot_owner_check
class BookClub(commands.Cog):
def __init__(self, bot):
self.bot =... |
1719639 | from django.http.response import Http404
from django.shortcuts import render,HttpResponse
import pickle
import pandas as pd
import sklearn
# Create your views here.
def home(request):
return render(request, 'home.html')
def predict(request):
with open("static/india_home_price_prediction.pickle", 'rb') as... |
1719703 | from algotrader.analyzer import Analyzer
from algotrader.trading.data_series import DataSeries
class DrawDownAnalyzer(Analyzer):
DrawDown = "DrawDown"
DrawDownPct = "DrawDown%"
HighEquity = "HighEquity"
LowEquity = "LowEquity"
CurrentRunUp = "CurrentRunUp"
CurrentDrawDown = "CurrentDrawDown"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.