id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3383131 | from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse
class Brands(Client):
"""
Use the Amazon Advertising API for Sponsored Brands for campaign, ad group, keyword, negative keyword, drafts, Stores, landing pages, and Brands management operations. For more information about Sponsored Bran... |
3383146 | from markdown import markdown
from markdown_checklist.extension import ChecklistExtension
def test_checklists():
source = """
Hello World
===========
* [ ] foo
* [x] bar
* [ ] baz
lorem ipsum
""".strip()
html = markdown(source)
assert html == """
<h1>Hello World</h1>
<ul>
<li>[ ] foo</li>
<li>[x] ... |
3383178 | import functools
import numpy as np
import re
import dataclasses
# ------------------------------------------ Assertions
def assert_true(value: bool, desc: str = ""):
if not value:
msg = "Validation error"
if desc:
msg += ": %s." % desc
raise ValueError(msg)
def assert_not_non... |
3383186 | import numpy as np
import torch
import torch.nn as nn
from dimenet.modules.envelope import Envelope
class BesselBasisLayer(nn.Module):
def __init__(self, num_radial, cutoff, envelope_exponent=5):
super(BesselBasisLayer, self).__init__()
self.num_radial = num_radial
self.cutoff = cutoff
... |
3383208 | import numpy as np
import argparse
import pickle
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import pdb
from matplotlib.backends.backend_pdf import PdfPages
from collections import OrderedDict
parser = argparse.ArgumentParser(descriptio... |
3383247 | from o3seespy.command.nd_material.base_material import NDMaterialBase
class CycLiqCP(NDMaterialBase):
"""
The CycLiqCP NDMaterial Class
This command is used to construct a multi-dimensional material object that that follows the constitutive behavior of
a cyclic elastoplasticity model for large po... |
3383312 | from ..MainBase import Sql_User as Sql
#-------------------------------------------------------------------------- AFK
def Show_User_AFKs(User_id : int , main:int):
row=Sql('SELECT times FROM AFK WHERE user_id=:user AND main=:main',{'user':int(User_id), 'main':int(main)})
row= row
try:
ret... |
3383411 | import unittest
import numpy as np
from openmdao.main.api import Assembly, Component, set_as_top
from openmdao.main.datatypes.api import Array, Float
class AComp(Component):
arr_in = Array(np.array(2.0), iotype='in', units='ft')
arr_out = Array(np.array(2.0), iotype='out', units='ft')
arr_nounit_in = Ar... |
3383472 | import requests
from . import exceptions as E
def call(method, url, **kwargs):
""" Attachs the kwargs into the headers, sends the request to the Ford API's
and handles all error cases.
Args:
method (str): HTTP method
url (str): url of the request
**kwargs: parameters for the r... |
3383535 | r"""
Wrappers
========
.. autosummary::
:nosignatures:
coax.wrappers.TrainMonitor
coax.wrappers.FrameStacking
coax.wrappers.BoxActionsToReals
coax.wrappers.BoxActionsToDiscrete
coax.wrappers.MetaPolicyEnv
----
OpenAI gym provides a nice modular interface to extend existing environments
using... |
3383573 | import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
import csv
import math
import os
# from mpl_toolkits.basemap import Basemap
style.use('ggplot')
# style.use('fivethirtyeight')
# plt.close('all')
def read_results(filename):
x = []
y = []
with open(filename, 'r'... |
3383580 | import math
import torch
from torch.optim import Optimizer
def get_lr(group, step):
lr, warmup, train_steps = group['lr'], group['warmup'], group['train_steps']
if step < warmup:
return lr * (train_steps - step) / train_steps
return lr * step / warmup
class AdamWeightDecayOptimizer(Optimizer):... |
3383582 | from lake.models.input_addr_ctrl_model import InputAddrCtrlModel
from lake.modules.input_addr_ctrl import InputAddrCtrl
from lake.passes.passes import lift_config_reg
import _kratos
import magma as m
from magma import *
from lake.utils.util import *
import fault
import tempfile
import kratos as k
import random as rand
... |
3383584 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Mul(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x1,x2):
diffY = x2.size()[2] - x1.size()[2]
diffX = x2.size()[3] - x1.size()[3]
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
... |
3383621 | import unittest
import bpy
from mathutils import (
Vector,
Color,
)
from blendergltf import utils
def extract_from_mesh(name):
mesh = bpy.data.meshes[name]
return utils.mesh.extract_attributes(mesh)
class TestMeshUtils(unittest.TestCase):
def test_extract_attributes_basic(self):
attrs =... |
3383645 | from pathlib import Path
import csv
class WALS(dict):
wals_file = Path(__file__).parent / Path("data/wals/language.csv")
def __init__(self, wals_file=None, key="iso_code"):
if wals_file:
self.wals_file = wals_file
self.key = key
self._load()
def _load(self):
w... |
3383678 | from hwt.hdl.constants import DIRECTION
from hwt.interfaces.std import VectSignal, Signal
from hwt.synthesizer.param import Param
from hwtLib.amba.axi3Lite import Axi3Lite_addr, Axi3Lite, Axi3Lite_r, Axi3Lite_b,\
IP_Axi3Lite
from hwtLib.amba.axi_intf_common import AxiMap, Axi_id, Axi_hs, Axi_strb
from hwtLib.amba.a... |
3383704 | import os
import re
from anasymod.sim.sim import Simulator
from anasymod.util import call
class IcarusSimulator(Simulator):
def compile(self):
# build up the simulation command
cmd = [self.cfg.icarus_config.iverilog, '-g2012', '-o', self.cfg.icarus_config.output_file_path, '-s',
sel... |
3383740 | from tornado import gen
from microproxy.tornado_ext.tcpserver import TCPServer
from microproxy.layer import manager as layer_manager
from microproxy.context import LayerContext
from microproxy.utils import curr_loop
from microproxy.log import ProxyLogger
logger = ProxyLogger.get_logger(__name__)
class ProxyServer(T... |
3383747 | import bz2
import json
import os
import tempfile
from rlo import analytics
from rlo.expression import Expression
def test_analytics_to_list():
with analytics.LogEventsToList() as m:
analytics.event("foo", num=3)
with analytics.Scope(repetition=2):
analytics.event("foo", num=4)
... |
3383772 | import os
import pickle
import argparse
import math
import numpy as np
import pandas as pd
import torch
from torch import nn
from pyro.infer.util import torch_item
from pyro.contrib.util import lexpand, rexpand
from torch.distributions.utils import broadcast_all
from pyro.poutine.util import prune_subsample_sites
imp... |
3383820 | class Solution(object):
def preorder(self, root):
ret, q = [], collections.deque([root])
while any(q):
node = q.popleft()
ret.append(node.val)
for child in node.children[::-1]:
if child: q.appendleft(child)
return ret |
3383825 | from collections.abc import Sequence
from typing import Union
import typing
from torch import Tensor
from examples.data_utils import get_mnist_data
from deepstochlog.context import ContextualizedTerm, Context
from deepstochlog.term import Term, List
def calculate_number_from_digits(digit_tensors: typing.Tuple[int, ... |
3383841 | del_items(0x80121A34)
SetType(0x80121A34, "void PresOnlyTestRoutine__Fv()")
del_items(0x80121A5C)
SetType(0x80121A5C, "void FeInitBuffer__Fv()")
del_items(0x80121A84)
SetType(0x80121A84, "void FeAddEntry__Fii8TXT_JUSTiP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, int Str, struct FeTable *MenuPtr, struct CFont *Fon... |
3383847 | from rest_framework import serializers
from django.conf import settings
from dailymed.models import Set, Spl, Product, InactiveIngredient
from dailymed.models import Package, RxNorm
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
exclude = ('product', )
class Rx... |
3383866 | import dragonfly as df
from srabuilder import rules
import title_menu, menu_utils, server, df_utils, game, container_menu, objective, server, constants
CARPENTER_MENU = 'carpenterMenu'
async def get_carpenter_menu():
return await menu_utils.get_active_menu(CARPENTER_MENU)
async def click_button(name):
menu =... |
3383911 | import sublime
import re
import subprocess
from .utils import find_working_dir
from .settings import ride_settings
ANSI_ESCAPE = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
message_shown = [False]
def R(script=None, file=None, args=None, stdin_text=None,
slave=True, quiet=True, working_dir=None):
cmd =... |
3383924 | import json
import typing as t
from collections import OrderedDict
from copy import deepcopy
class ExceptionWithCode(Exception):
"""
Error class constructed with some assumptions:
* human-readable description of the error should be computed as late as possible (not earlier
than on the presentation ... |
3383930 | from django.test import RequestFactory
from manager.api.views.docs import schema_view
def run(to):
response = schema_view(RequestFactory().get("/api/schema"))
response.render()
with open(to, "wb") as file:
file.write(response.content)
|
3383934 | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from task_manager.classes import CeleryQueue
queue_default = CeleryQueue(
name='default', label=_('Default'), is_default_queue=True
)
queue_tools = CeleryQueue(name='tools', label=_('Tools'))
queue_co... |
3383960 | from os import listdir
from os.path import isfile, join
from flask import Blueprint, jsonify
from app.utilities.schema import load_schema_from_params
schema_blueprint = Blueprint('schema', __name__)
@schema_blueprint.route('/schemas/<eq_id>/<form_type>', methods=['GET'])
def get_schema_json(eq_id, form_type):
t... |
3384000 | import os
from dataclasses import dataclass
from typing import List
from .korpora import Korpus, KorpusData, SentencePairKorpusData
from .utils import fetch, default_korpora_path, load_text, check_exists
KOREAN_HATE_SPEECH_FETCH_INFORMATION = [
{
'url': 'https://raw.githubusercontent.com/kocohub/korean-h... |
3384066 | import requests
import pytest
import asyncio
from urllib.parse import urlparse
from pytest_httpserver import HTTPServer
from rssant_common.helper import aiohttp_client_session
from rssant_common.dns_service import DNSService, DNS_SERVICE, PrivateAddressError
def _requests_session():
dns_service = DNSService.crea... |
3384074 | import argparse, primer, sys, util
# Remove primer from the beginning of every sequence
def parse_args():
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-f', default='', help='Input FASTA file')
parser.add_argument('-q', default='', help='Input FASTQ file'... |
3384111 | from os import listdir, chdir
from os.path import dirname, abspath, isfile, join
from subprocess import call
import sys
def run_python( file ):
run_cmd( "python3 " + file )
def run_cmd( cmdline, expected_ret_code=0 ):
if expected_ret_code:
print ( "\033[90mRunning: '%s' \t(expecting %s ret code)\033[... |
3384127 | import time
from pyb import Pin, Timer
# 50kHz pin6 timer2 channel1
light = Timer(2, freq=50000).channel(1, Timer.PWM, pin=Pin("P6"))
light.pulse_width_percent(100) # adjust light 0~100
while (True):
time.sleep_ms(1000)
|
3384150 | import boto3
from flask import current_app as app
from flask import Blueprint
from flask import render_template
from .query_dao import QueryDao
from .athena_summary_provider import AthenaSummaryProvider
base_path = '/athena_usage'
tab_name = 'Athena Usage'
plugin = Blueprint('athena_usage', __name__, template_folde... |
3384183 | import logging
from confluent_kafka import Consumer
import json
logging.basicConfig(format='%(asctime)s::%(process)d::%(levelname)s::%(message)s', level=logging.INFO, datefmt='%d-%b-%y %H:%M:%S')
class CustomKafkaConsumer:
def __init__(self):
self.output_map = dict()
self.topic_name = "metrics3"
... |
3384200 | import numpy as np
import torch
from diffrend.torch.utils import tch_var_f
def perspective_NO_params(fovy, aspect, near, far):
"""Perspective projection matrix parameters for transforming to a normalized cube between Negative one to One (NO)
:param fovy: field of view in the y-axis
:param aspect: aspect r... |
3384279 | from __future__ import print_function
import numpy as np
import os
import random
import time
from navrep.models.tcn import reset_graph, default_hps, MDNTCN
hps = default_hps()
# hps.batch_size = 100
# hps.max_seq_len = 1000
N_EPOCHS = 10000
_Z = 32
# hps = hps._replace(learning_rate=0.001)
dataset_folder = os.path.... |
3384297 | from binance import Client
from portfolio_management.binance_api import get_kline_dataframe
def test_get_kline_dataframe():
symbol = "ETHBTC"
interval = Client.KLINE_INTERVAL_30MINUTE
start = "2017-11-12"
end = "2017-11-14"
df = get_kline_dataframe(symbol=symbol, interval=interval, start=start, en... |
3384299 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
from six.moves import xrange
def generate_random_df(n_seqs=5,
max_seq_length=10,
unique_times=True,
... |
3384303 | from __future__ import unicode_literals
import django
from django.test import TestCase
from scheduler.sync.job_type_manager import JobTypeManager
class TestJobTypeManager(TestCase):
fixtures = ['basic_system_job_types.json']
def setUp(self):
django.setup()
def test_successful_update_and_creat... |
3384317 | from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.utils.callback_data import CallbackData
admin_callback = CallbackData('act', 'name')
help_callback = CallbackData('act', 'name')
close_callback = CallbackData("act", "name")
main_markup = InlineKeyboardMarkup(row_width=2)
help_info = In... |
3384329 | from pumapy.utilities.workspace import Workspace
from pumapy.physicsmodels.boundary_conditions import ConductivityBC
from pumapy.physicsmodels.linear_solvers import PropertySolver
import numpy as np
class Conductivity(PropertySolver):
def __init__(self, workspace, cond_map, direction, side_bc, prescribed_bc, tol... |
3384342 | import komand
from .schema import AddMemberToChannelInput, AddMemberToChannelOutput, Input, Output, Component
# Custom imports below
from icon_microsoft_teams.util.teams_utils import get_channels_from_microsoft
from icon_microsoft_teams.util.azure_ad_utils import (
get_user_info,
get_group_id_from_name,
ad... |
3384369 | from bitmovin.errors import MissingArgumentError
from bitmovin.resources.models import PlainTextID3Tag as PlainTextID3TagResource
from .generic_id3_tag_service import GenericID3TagService
class PlainTextID3(GenericID3TagService):
def __init__(self, http_client, muxing_type_url):
if not muxing_type_url:
... |
3384387 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.contrib.learn.python.learn as learn
import csv
import json
import math
import random
random.seed()
def read_data(path):
df = pd.read_csv('data/type-inference+vars.csv')
label_names = [c for c in df... |
3384402 | import matplotlib.pyplot as plt
import argparse
import math
import glob
import numpy as np
import sys
import os
import torch
from torchvision.utils import save_image
from tqdm import tqdm
from tl2.launch.launch_utils import update_parser_defaults_from_yaml, global_cfg
import curriculums
device = torch.device('cuda... |
3384409 | import copy
import ctypes
import functools
import numpy
import cepton_sdk.common.c
import cepton_util.common
_all_builder = cepton_util.common.AllBuilder(__name__)
from cepton_util.common import AllBuilder, SimpleTimer # noqa isort:skip
def static_vars(**kwargs):
"""Add static variables to function.
"""
... |
3384412 | from multiprocessing import freeze_support
from Recognize.Canny import Canny
if __name__ == '__main__':
freeze_support()
x = Canny()
while True:
x.next_image()
# digimage = np.zeros((10, 10, 1), np.uint8)
# x.saveDigits(digimage, [1, 2, 3])
|
3384425 | import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.path
plt.ion()
import pybie2d
"""
Demonstrate how to use the pybie2d package to solve an interior Stokes problem
On a complicated domain using a global quadrature
This example demonstrates how to do this entirely using low-l... |
3384427 | import os
# For reading, visualizing, and preprocessing data
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from pytorch_toolbelt.utils import fs
from sklearn.decomposition import PCA
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import StandardScaler
fr... |
3384450 | import pytest
def test_prepare_fit(sed_data=None, prefit_jet=None, plot=True,sed_number=1):
from jetset.jet_model import Jet
if sed_data is None:
from .test_data import test_data_loader
sed_data = test_data_loader(plot=plot, sed_number=sed_number)
if prefit_jet is None:
from .tes... |
3384474 | import logging
from django.contrib.auth.models import User
from django.db import models
logger = logging.getLogger(__name__)
class CoreModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class MovieSubtitle(CoreModel):
full_path = models.CharF... |
3384475 | from insights.parsers.ls_disk import LsDisk
from insights.tests import context_wrap
LS_DISK = """
/dev/disk/by-path:
total 0
drwxr-xr-x. 2 0 0 160 Sep 19 10:15 .
drwxr-xr-x. 5 0 0 100 Sep 19 10:15 ..
lrwxrwxrwx. 1 0 0 9 Sep 19 10:15 pci-0000:00:01.1-scsi-1:0:0:0 -> ../../sr0
lrwxrwxrwx. 1 0 0 9 Sep 19 10:15 pci-00... |
3384481 | from __future__ import unicode_literals
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
CypherBinder = KeyBindingManager()
@CypherBinder.registry.add_binding("{")
def curly_left(event):
b = event.cli.current_buffer
b.insert_text("{")
b.insert_text("}", move_... |
3384512 | from datetime import datetime, timedelta
from functools import partial
from matilda.fundamental_analysis.supporting_metrics import *
from matilda.fundamental_analysis.financial_statements import *
def cost_of_preferred_stock(stock, date=datetime.now(), lookback_period=timedelta(days=0), period: str = 'FY'):
prefe... |
3384534 | data = (
'ggyeols', # 0x00
'ggyeolt', # 0x01
'ggyeolp', # 0x02
'ggyeolh', # 0x03
'ggyeom', # 0x04
'ggyeob', # 0x05
'ggyeobs', # 0x06
'ggyeos', # 0x07
'ggyeoss', # 0x08
'ggyeong', # 0x09
'ggyeoj', # 0x0a
'ggyeoc', # 0x0b
'ggyeok', # 0x0c
'ggyeot', # 0x0d
'ggyeop',... |
3384587 | import numpy as np
import tensorflow as tf
from tefla.core.special_layers import group_norm
class TestGroupNorm(tf.test.TestCase):
def testGroupNorm(self):
x = np.random.rand(5, 7, 3, 16)
with self.test_session() as session:
y = group_norm(tf.constant(x, dtype=tf.float32))
session.run(tf.global... |
3384600 | import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import sys
from scapy.all import *
if len(sys.argv) !=4:
print "usage: %s target startport endport" % (sys.argv[0])
sys.exit(0)
target = str(sys.argv[1])
startport = int(sys.argv[2])
endport = int(sys.argv[3])
print "Scanning "+target... |
3384603 | from marshmallow import fields
from flask_marshmallow import Marshmallow
from hobbit_core.schemas import PagedSchema
ma = Marshmallow()
class UserSchema(ma.SQLAlchemyAutoSchema): # type: ignore
class Meta:
from .models import OtherUser
model = OtherUser
class PagedUserSchema(PagedSchema):
... |
3384640 | import random
import unittest
from talkgenerator.schema.slide_topic_generators import SideTrackingTopicGenerator
class SlideTopicGeneratorsTest(unittest.TestCase):
def setUp(self) -> None:
random.seed(123)
def test_conceptnet_sidetracking_standard(self):
generator = SideTrackingTopicGenerato... |
3384652 | import sys
from math import hypot
import json
from vectorMap import VectorMap
from const import CONST
from pprint import PrettyPrinter
pp = PrettyPrinter(indent=2).pprint
ARROW_NAME_SEPARATER = "/"
class MapAuthoring(object):
def __init__(self, vectorMap):
self.__vectorMap = vectorMap
self.__view... |
3384673 | import logging
from warnings import warn
from typing import Dict, Union, Tuple, NamedTuple, Optional, TypeVar
from typing_extensions import final, Final
from numbers import Number
import typing
from lomentum.types import (
ContextDict, Symbol, RoutesDictType)
from functools import partial
from contextlib import ... |
3384690 | import numpy as np
import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell
import sys
import time
from sklearn.metrics import f1_score
import random
class han(object):
'''
hierarchical attention network by yang et. al.
parameters:
- embedding_matrix: numpy array
nump... |
3384717 | import logging
from diana.dixel import Provenance
from datetime import datetime
def test_provenance():
fkey = b'<KEY>
p = Provenance(
institution="test_inst",
trial="test_proj",
original_study_dt=datetime(year=1900, month=1, day=1,
hour=0, minute=0,... |
3384730 | from functools import partial
from itertools import combinations
from operator import add, sub, and_, or_, invert
from typing import List, Iterable, Callable, Tuple, Dict, Iterator
def get_postexpr_dfs(nums: List[int],
uny_ops: Iterable[Callable[[int], int]], bin_ops: Iterable[Callable[[int, int]... |
3384748 | from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from ..constants import START_YEAR
from .models import (DynamicSaveInputs, DynamicBehaviorSaveInputs,
DynamicElasticitySaveInputs)
from ..taxbrain.helpers import (string_to_float_arr... |
3384770 | from util import *
send_gdb('b breakpoint')
expect_gdb('Breakpoint 1')
send_gdb('c')
expect_gdb('Breakpoint 1, breakpoint')
send_gdb('call check_pid()')
expect_gdb('SUCCESS')
send_gdb('c')
expect_gdb('Breakpoint 1, breakpoint')
send_gdb('call check_tid()')
expect_gdb('SUCCESS')
send_gdb('c')
expect_rr('EXIT-SUCCE... |
3384845 | from apps.analysis_and_training.main.statistics import calculate_statistics
def test_statistics_without_resolution_unresolved(
statistics, correct_result_statistics
):
result = calculate_statistics(
statistics, ["Comments", "Attachments", "Time to Resolve"]
)
assert result == correct_result_s... |
3384868 | import os
from optparse import make_option
from uliweb.core.commands import Command, get_input, get_answer
from uliweb.core.template import template_file
def camel_to_cap(s):
import re
return re.sub('^\w|_\w', lambda x:x.group()[-1].upper(), s)
class GenericCommand(Command):
name = 'generic'
... |
3384909 | from .weight_init import (
caffe2_xavier_init,
constant_init,
kaiming_init,
normal_init,
uniform_init,
xavier_init,
)
__all__ = [
"constant_init",
"xavier_init",
"normal_init",
"uniform_init",
"kaiming_init",
"caffe2_xavier_init",
]
|
3384911 | from typing import Union
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
User = get_user_model()
class UsernameOrEmailAuth(ModelBackend):
def authenticate(
self,
request,
login: Union[str, None] = None,
... |
3384929 | import unittest
from kbmodpy import kbmod as kb
class test_regions(unittest.TestCase):
def setUp(self):
# test pass thresholds
im = kb.layered_image("",171,111,5.0,25.0,0)
stack = kb.image_stack([im])
p = kb.psf(1.0)
self.search = kb.stack_search(stack, p)
max_img = im.get_scie... |
3384938 | from __future__ import division
from warnings import warn
import numpy as np
from scipy.sparse import csr_matrix
from pybasicbayes.util.general import objarray
from pylds.lds_messages_interface import info_E_step, info_sample, kalman_info_filter, kalman_filter, E_step
# TODO on instantiating, maybe gaussian states s... |
3384999 | import logging
import os
import re
import select
import sys
import zipfile
import warnings
# Setup Logging
logger = logging.getLogger(__name__)
if '--debug run' in ' '.join(sys.argv):
logger.setLevel(logging.DEBUG)
else:
# Ignore warnings from cryptography module
warnings.filterwarnings("ignore", category... |
3385002 | import sys, getopt, os
def camiToKrona(argv):
rankArr = ["superkingdom", "phylum", "class", "order", "family", "genus", "species", "strain", "dummy"]
camiOutput = ''
outFile = ''
try:
opts, args = getopt.getopt(argv, "i:o:", [])
except getopt.GetoptError:
print('-i <input> -o <output>')
for opt, arg in... |
3385031 | import os
from lft.app import Node
from lft.event import EventRegister
from lft.consensus.messages.data import Data
from lft.consensus.events import ReceiveVoteEvent, ReceiveDataEvent, BroadcastVoteEvent
class DoubleVoter(EventRegister):
def __init__(self, node: Node):
super().__init__(node.event_system.s... |
3385078 | from chalice import Chalice
import random
app = Chalice(app_name='clickstream-data')
@app.route('/user/{phoneNumber}', methods=['GET'])
def index(phoneNumber): # gives a phone number to user name mapping
userList = {
"anonymous": "",
"architectjobless": "+61428921911",
"mongoosespots": "+... |
3385089 | from jinja2 import Template
def render_template(template, context):
jinja_template = Template(template)
return jinja_template.render(**context)
|
3385120 | import unittest
from nalaf.structures.data import Dataset, Document, Part, Entity, Relation
from nalaf.learning.evaluators import Evaluator, MentionLevelEvaluator, DocumentLevelRelationEvaluator
from nalaf.preprocessing.spliters import NLTKSplitter
from nalaf.preprocessing.tokenizers import NLTK_TOKENIZER
STUB_E_ID_1... |
3385126 | import os
VERSION = "1.0"
MODEL_NAME = os.path.basename(os.path.dirname(__file__))
DOCKERHUB_REPO = f"danieldeutsch/{MODEL_NAME}"
DEFAULT_IMAGE = f"{DOCKERHUB_REPO}:{VERSION}"
AUTOMATICALLY_PUBLISH = True
from repro.models.chen2020.dataset_reader import Chen2020EvaluationDatasetReader
from repro.models.chen2020.model... |
3385168 | import argparse
import os
import pickle
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--prefix",
default='/checkpoint/siddk/debate/runs/dream/dream.bert_mc_gpt.bsz=32.lr=2.0e-05.f/oracle_outputs.d=I',
type=str,
help="The prefix for files to lo... |
3385265 | import compas_ags
from compas_ags.diagrams import FormDiagram
from compas_ags.diagrams import ForceDiagram
from compas_ags.ags import form_update_q_from_qind
from compas_ags.ags import force_update_from_form
from compas_ags.ags import form_update_from_force
from compas_ags.viewers import Viewer
def view_form_force(fo... |
3385298 | from lib.utils.base_utils import read_pickle
import numpy as np
def read_anns(ann_files):
anns = []
for ann_file in ann_files:
anns += read_pickle(ann_file)
return anns
def read_pose(rot_path, tra_path):
rot = np.loadtxt(rot_path, skiprows=1)
tra = np.loadtxt(tra_path, skiprows=1) / 100.
... |
3385324 | import numpy as np
from nose.tools import eq_, assert_raises
from gtfparse import (
parse_gtf,
parse_gtf_and_expand_attributes,
REQUIRED_COLUMNS,
ParsingError
)
from six import StringIO
gtf_text = """
# sample GTF data copied from:
# http://useast.ensembl.org/info/website/upload/gff.html?redirect=no
1\... |
3385360 | import sys
from importlib import import_module
from bumps.pymcfit import PyMCProblem
if len(sys.argv) != 2:
raise ValueError("Expected name of pymc file containing a model")
module =sys.argv[1]
__name__ = module.split('.')[-1]
model = import_module(module)
problem = PyMCProblem(model)
|
3385412 | import setuptools
def long_description():
with open('README.md', 'r') as file:
return file.read()
setuptools.setup(
name='stream-unzip',
version='0.0.69',
author='Department for International Trade',
author_email='<EMAIL>',
description='Python function to stream unzip all the files i... |
3385414 | from bs4 import BeautifulSoup
from utils.scraper import Scraper
class Tuebl(Scraper):
def __init__(self, base_dir, url_header, log_file):
super().__init__(log_file)
self._base_dir = base_dir
self._url_header = url_header
def get_latest(self):
"""
Parse `http://tuebl.ca... |
3385420 | def method1(l: list) -> list:
n = len(l)
for i in range(n - 1):
for j in range(0, n - i - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
return l
if __name__ == "__main__":
"""
l = [1, 3, 4, 7, 5, 9]
from timeit import timeit
timeit(lambda: meth... |
3385436 | import mfoo
import tfoo
def proxy_hello(q):
return mfoo.hello(q)
def proxy_say_hello(msg):
return tfoo.say_hello(msg)
|
3385468 | from bs4 import BeautifulSoup
import os
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
import urllib
import shutil
import psutil
from tqdm import tqdm
class TqdmUpTo(tqdm):
"""Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
def update_to(s... |
3385491 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import argparse
import re
import sys
import numpy as np
from scipy.sparse import hstack
from sklearn.feature_extraction import DictVectorizer
from custom_logistic import ... |
3385526 | import munch
try:
from unittest import mock
except ImportError:
import mock
import basecrm
from basecrm.test.testutils import BaseTestCase
from munch import munchify
class SyncServiceTests(BaseTestCase):
@property
def device_uuid(self):
return '6dadcec8-6e61-4691-b318-1aab27b8fecf'
def ... |
3385535 | from django.views.generic import DetailView, ListView
from ...models import Mentor
class MentorListView(ListView):
model = Mentor
def get_queryset(self):
return (
Mentor.objects.filter(
user__is_active=True,
is_active=True,
is_public=True,
... |
3385571 | import unittest
import numpy as np
import torch
from pytorch_adapt.validators import ErrorValidator, ScoreHistory
from pytorch_adapt.validators.utils import max_normalizer
class TestMaxNormalizer(unittest.TestCase):
def test_max_normalizer(self):
se = ScoreHistory(ErrorValidator(), normalizer=max_normal... |
3385687 | from typing import Optional, Tuple
from urllib.parse import urlsplit, parse_qsl
def session_established(session):
path: Optional[bytes] = None
for key, value in session.request_headers:
if key == b':path':
path = value
assert path is not None
qs = dict(parse_qsl(urlsplit(path).quer... |
3385701 | import cv2
img_path_0 = 'eagle_2018_09_05_18_40_13_657.jpg'
img_path_1 = 'eagle_2018_09_05_18_40_13_723.jpg'
img_path_2 = 'eagle_2018_09_05_18_40_13_790.jpg'
img_rgb_0 = cv2.imread(img_path_0, cv2.IMREAD_COLOR)
img_rgb_1 = cv2.imread(img_path_1, cv2.IMREAD_COLOR)
img_rgb_2 = cv2.imread(img_path_2, cv2.IMREAD_... |
3385719 | import torch
def extract_attn_data(edge_index_attn, weights_attn, dim=None, k=120):
edges = edge_index_attn.T
if not dim:
w = weights_attn.mean(dim=1)
else:
w = weights_attn[:, dim]
w = w.squeeze()
top_values, top_indices = torch.topk(w, k)
top_edges = edges[top_indices]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.