id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4856526 | import torch
from .base import *
from .pack import *
import numpy as np
from torch.utils.cpp_extension import load
from pathlib import Path
this_dir = Path(__file__).parent
myln_cpp = load(name="lrln_cpp", sources=[this_dir / "lrln.cpp", this_dir / "lrln.cu"], extra_cflags=['-std=c++17'])
# TODO - 1) recompute using ... |
4856527 | import cv2
import numpy as np
img1 = cv2.imread('aa.jpg')
img2 = cv2.imread('bc.jpg')
import cv2
img = cv2.imread('aa.jpg')
height, width, channels = img.shape
print (height, width, channels)
r = 500.0 / img.shape[1]
dim = (500, int(img.shape[0] * r))
resized = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
... |
4856530 | import pygame as pg
import numpy as np
from numba import njit
def main():
pg.init()
pg.mixer.init()
(step, step2, swoosh, hurt, deadmonster, hitmonster,
hitmonster2, healthup, died, won, music) = load_sounds()
stepdelay = pg.time.get_ticks()/200
stepdelay2 = stepdelay
screen = p... |
4856555 | AUTHENTICATION_BACKENDS = (
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.vk.VKOAuth2',
'social_core.backends.facebook.FacebookAppOAuth2',
'social_core.backends.facebook.FacebookOAuth2',
# Django
'rest_framework_social_oauth2.b... |
4856560 | import time
import traceback
from collections import namedtuple, OrderedDict
from io import BytesIO
from lxml import etree as etree_
from .. import pysoap
from ..namespaces import Prefix_Namespace as Prefix
from ..namespaces import msgTag, domTag, s12Tag, wsxTag, wseTag, dpwsTag, mdpwsTag, nsmap
from .. impor... |
4856579 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
l1tdttpg = DQMEDAnalyzer('L1TDTTPG',
disableROOToutput = cms.untracked.bool(True),
dttpgSource = cms.InputTag("muonDTDigis"),
verbose = cms.untracked.bool(False),
DQMStore = cms.untracked.bool(True)
)
|
4856589 | from typing import List
from botbuilder.core import (
ActivityHandler,
BotFrameworkAdapter,
ConversationState,
UserState,
MessageFactory,
TurnContext,
)
from botbuilder.dialogs import DialogState
from botframework.connector.auth import MicrosoftAppCredentials
from config import DefaultConfig
f... |
4856654 | from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Address
class AddressSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(queryset=User.objects.all(),
slug_field='username')
class Meta:
... |
4856655 | from pathlib import Path
import pytest
from darwin.importer.formats.pascalvoc import parse_file
def describe_parse_file():
@pytest.fixture
def annotation_path(tmp_path: Path):
path = tmp_path / "annotation.xml"
yield path
path.unlink()
def it_returns_none_if_path_suffix_is_not_xm... |
4856688 | import re
import pickle
import os
import json
from unittest.mock import Mock
import requests
ABSPATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
def abspath(path):
return os.path.join(ABSPATH, path)
def prepare_request(*args, **kwargs):
r = requests.Request(*args, **kwargs)
s = re... |
4856763 | import subprocess
from PyQt5 import QtWidgets
from rujaion import util
class TestDialog(QtWidgets.QDialog):
def __init__(self, *args, compiled_file: str, settings):
super().__init__(*args)
self.console = self.parent().console
self.compiled_file = compiled_file
# self.is_interacti... |
4856825 | from typing import Optional, Union
import numpy as np
from .utils import StochasticArm
class GaussianArm(StochasticArm):
"""Gaussian arm
Arm with rewards generated from a Gaussian distribution.
:param float mu: mean of rewards
:param float std: standard deviation of rewards
:param Optional[str] name: al... |
4856857 | import logging
import distutils.util
from protocols import reports_4_0_0 as reports_4_0_0
from protocols import reports_5_0_0 as reports_5_0_0
from protocols.migration.base_migration import BaseMigrateReports400And500
from protocols.migration.base_migration import MigrationError
from protocols.migration import Migrate... |
4856874 | import torch
import torch.nn as nn
from .. import functional as pwF
class SequenceDenseCNN(nn.Module):
"""
Dense CNN for sequences (https://arxiv.org/abs/1808.07383).
"""
def __init__(self,
input_size,
projection_layer_size=150,
kernel_heights=(3, 5... |
4856902 | import os
import tqdm
import argparse
from typing import List
from .utils import random_filename
from tokenizers import Tokenizer, models, decoders
from tokenizers.trainers import WordPieceTrainer
from tokenizers.normalizers import BertNormalizer
from tokenizers.pre_tokenizers import BertPreTokenizer
def _split_subse... |
4856904 | import gym
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
class InteractionMixin:
INTERACTION_OPTS = ('elementwise_quadratic', 'full_quadratic')
@property
def input_dim(self):
if not hasattr(self, '_input_dim'):
if not... |
4856943 | from ..base import ShopifyResource
import base64
class Asset(ShopifyResource):
_primary_key = "key"
_prefix_source = "/themes/$theme_id/"
@classmethod
def _prefix(cls, options={}):
theme_id = options.get("theme_id")
if theme_id:
return "%s/themes/%s" % (cls.site, theme_id)... |
4856950 | import pytest
from datetime import datetime
from .fixtures import *
from pam.variables import END_OF_DAY
def test_home_education_home_fill_activity(person_home_education_home):
person = person_home_education_home
p_idx, s_idx = person.remove_activity(2)
assert person.fill_plan(p_idx, s_idx)
assert p... |
4856993 | import expression
import pandas as pd
from expression import pipe
from expression.collections import seq, Seq
from ib_insync.objects import Position, PortfolioItem
from ib_insync.contract import Contract
from ib_insync.order import Trade, Order, OrderStatus
from trader.common.logging_helper import setup_logging
from tr... |
4856995 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Author(models.Model):
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last name')... |
4857000 | import unittest
from dynd import nd, ndt
import math
class TestBasics(unittest.TestCase):
def test_null_array(self):
a = nd.array()
self.assertEqual(str(a), "nd.array()")
self.assertEqual(repr(a), "nd.array()")
self.assertRaises(AttributeError, lambda: a.real)
self.assertRa... |
4857031 | import numbers
import numpy as np
import scipy.sparse as sp
from copy import deepcopy
from joblib import Parallel, effective_n_jobs # , delayed
from sklearn.dummy import DummyClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.base import is_regr... |
4857046 | from pupa.scrape import Scraper
from pupa.scrape.helpers import Legislator, Organization
class PersonScraper(Scraper):
def get_people(self):
# committee
tech = Organization('Technology', classification='committee')
tech.add_post('Chairman', 'chairman')
tech.add_source('https://exa... |
4857075 | from datetime import datetime
import os
from importlib import reload
from os import environ
from typing import Tuple, Optional, AsyncGenerator
import pytest
import aiofiles
from async_generator import asynccontextmanager
from Cryptodome.PublicKey import RSA
import jwthenticator.utils
from jwthenticator import consts
... |
4857081 | from collections import defaultdict
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if k == 0:
return 0
positions = defaultdict(list)
charset = set()
_maxle... |
4857118 | import json
import multiprocessing
import os
import shutil
import socket
from argparse import ArgumentParser, Namespace
from pprint import pprint
from glow_pytorch.glow.utils import calc_jerk, get_longest_history
import numpy as np
import optuna
import pytorch_lightning as pl
import torch
import yaml
from jsmin import... |
4857140 | import os
import sys
import tensorflow as tf
import numpy as np
import math
import matplotlib as mlp
import copy
import random
import tqdm
BASEDIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, BASEDIR)
from Dataset.load import Load
from Parser_.parser import model_parser
from Dataset.save_resul... |
4857143 | from abc import ABC, abstractmethod
from slick_dnn import variable
class Context:
"""
This class is for storing information for back propagation.
Autograd uses this class instead of using self to allow constructions::
relu = ReLU()
b = relu(a)
c = relu(b)
Tha... |
4857161 | import sqlite3
import numpy
import scipy.sparse
from django.test import SimpleTestCase
from matrixstore.serializer import serialize, serialize_compressed, deserialize
class TestSerializer(SimpleTestCase):
def test_simple_serialisation(self):
obj = {"hello": 123}
self.assertEqual(deserialize(ser... |
4857265 | import cctk
import unittest
import numpy as np
import cctk.quasiclassical as qc
if __name__ == '__main__':
unittest.main()
class TestFrequencies(unittest.TestCase):
def test_read(self):
path = "test/static/methane_normal.out"
file = cctk.GaussianFile.read_file(path)
mol = file.get_mo... |
4857284 | from __future__ import unicode_literals, division, print_function, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object, range, next
import logging
import pickle as pkl
import re
import unicodedata
from copy import deepcopy
import numpy as np
from scipy.spar... |
4857299 | import logging
import os
import shlex
import sys
from chiptools.wrappers.simulator import Simulator
from chiptools.common.filetypes import FileType
from chiptools.common import utils
log = logging.getLogger(__name__)
class Vivado(Simulator):
name = 'vivado'
if sys.platform == 'win32':
platform_suf... |
4857361 | def _empty_rule_impl(ctx):
return [
DefaultInfo(),
]
_empty_rule = rule(
_empty_rule_impl,
attrs = {
},
)
OVERRIDE_RULE_NAME = "package_lint_config"
def package_lint_config(linters):
"""Register the given linters for the current bazel package.
This is expected to be near the top ... |
4857403 | import framework.util as util
from main.data import IN_PAPER_NAMES, VA, BE5, SHORT_COLUMNS
import datetime
import pandas as pd
df=util.load_tsv('results.tsv')
df=df[VA+BE5]
df.rename(index=IN_PAPER_NAMES, inplace=True)
df.rename(index=str, columns=SHORT_COLUMNS, inplace=True)
#reoder index
df=df.reindex([value fo... |
4857421 | import collections
import logging
import uuid
from contextlib import contextmanager
import requests
from kinto_http import utils
from kinto_http.session import create_session, Session
from kinto_http.batch import BatchSession
from kinto_http.exceptions import (
BucketNotFound,
CollectionNotFound,
KintoExce... |
4857434 | import os,sys
#add library to the system path
lib_path = os.path.abspath(os.path.join('lib'))
sys.path.append(lib_path)
lib_path = os.path.abspath(os.path.join('tools'))
sys.path.append(lib_path)
import numpy as np
import cv2
from fast_rcnn.config import cfg
from utils.transform import calib_to_P,computeCorner... |
4857448 | import typing
from starlette import authentication as auth
from starlette.requests import HTTPConnection
from .base.backends import AuthBackend
from .datatypes import AuthResult
class MultiAuth(AuthBackend):
def __init__(self, backends: typing.List[AuthBackend]):
self.backends = backends
async def ... |
4857466 | from .. import vk
from .utils import check_ctypes_members
from ctypes import byref
from enum import IntFlag
class BufferUsageFlags(IntFlag):
TransferSrc = vk.BUFFER_USAGE_TRANSFER_SRC_BIT
TransferDst = vk.BUFFER_USAGE_TRANSFER_DST_BIT
UniformTexelBuffer = vk.BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT
Stora... |
4857470 | import argparse
parser = argparse.ArgumentParser(description='Fast Neural Style')
parser.add_argument('--epoches', default=2, type=int)
parser.add_argument('--lr', default=0.001, type=float)
parser.add_argument('--style_image', default='images/wave.jpg', type=str)
parser.add_argument('--batch_size', default=4, type=int... |
4857477 | from enum import Enum
class MeepleType(Enum):
NORMAL = "normal"
ABBOT = "abbot"
FARMER = "farmer"
BIG = "big"
BIG_FARMER = "big_farmer"
def to_json(self):
return self.value
def __str__(self):
return self.value
|
4857484 | import os
import sys
from django.core.wsgi import get_wsgi_application
PROJECT_DIR = os.path.abspath(__file__)
sys.path.append(PROJECT_DIR)
os.environ["DJANGO_SETTINGS_MODULE"] = "jobsp.settings_server"
application = get_wsgi_application()
|
4857496 | import os
import numpy as np
from neuraxle.base import ExecutionContext
from neuraxle.hyperparams.distributions import Boolean
from neuraxle.hyperparams.space import HyperparameterSpace, HyperparameterSamples
from neuraxle.pipeline import Pipeline
from neuraxle.steps.loop import StepClonerForEachDataInput
from neurax... |
4857505 | import pytest
import cPickle
def test_stack_underflow():
with pytest.raises(cPickle.UnpicklingError):
cPickle.loads("a string")
def test_bad_key():
with pytest.raises(cPickle.UnpicklingError) as excinfo:
cPickle.loads("v")
assert str(excinfo.value) == "invalid load key, 'v'."
def test_fin... |
4857544 | from shared_config import *
word_size = 32
num_words = 32
words_per_row = 1
local_array_size = 31
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True
|
4857547 | from sqlobject import dbconnection
from sqlobject import classregistry
from sqlobject import events
from sqlobject import sqlbuilder
from sqlobject.col import StringCol, ForeignKey
from sqlobject.main import sqlmeta, SQLObject, SelectResults, \
makeProperties, unmakeProperties, getterName, setterName
import iteratio... |
4857564 | import os
from argparse import Namespace
from tqdm import tqdm
import time
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader
import sys
sys.path.append(".")
sys.path.append("..")
from configs import data_configs
from datasets.inference_dataset import InferenceDataset
from e... |
4857643 | from ._version import get_version
from .cmd import cmd_loop
from .context import Context
from .datacontainer import Statistics
from .server.app import run_server
__version__ = get_version()
__all__ = [__version__, cmd_loop, Context, run_server, Statistics]
|
4857808 | import sys
import os
from github import Github
foldername = str(sys.argv[1])
path = str(sys.argv[2])
ide = str(sys.argv[3]).lower()
username = str(sys.argv[4])
g = Github("username", "password")
user = g.get_user()
login = user.login
repo = user.create_repo(foldername)
commands = [f'echo "# {repo.name}... |
4857809 | import os
from ..base_artifact_stats_collector import BaseArtifactStatsCollector
class CompileTimeCollector(BaseArtifactStatsCollector):
"""
Collect the compilation time required for NoisePage.
Notes
-----
This doesn't actually compile NoisePage at all. It just reads a file
which is assumed ... |
4857818 | import numpy as np
from paderbox.transform.module_stft import stft
from paderbox.transform.module_fbank import logfbank
from paderbox.array import segment_axis
import scipy.signal
from scipy.fftpack import dct
def mfcc(time_signal, sample_rate=16000,
window_length=400, stft_shift=160, numcep=13,
num... |
4857880 | from pymtl import *
from lizard.util.rtl.interface import UseInterface
from lizard.core.rtl.backend.multiply import MultDropController
from lizard.core.rtl.messages import MFunc, MVariant, DispatchMsg, ExecuteMsg, MMsg
from lizard.util.rtl.pipeline_stage import PipelineStageInterface, gen_valid_value_manager
from lizar... |
4857884 | import os
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
def addText(pixmap, w, h, name):
painter = QtGui.QPainter(pixmap)
font = QtGui.QFont("Roboto")
font.setPointSize(36)
position = QtCore.QRect(0, 0, w, h)
painter.setFont(font)
p... |
4857932 | import math
import numpy as np
from numpy.linalg import norm
from ..meshio import form_mesh
from ..misc import Quaternion
def generate_cylinder(p0, p1, r0, r1, num_segments=16):
""" Generate cylinder (or `conical frustum`_ to be precise).
Args:
p0 (``np.ndarray``): Bottom center.
p1... |
4857991 | import os
from typing import Dict, List
from datasets import Dataset
from utils.file import load_json
from utils.nlp import (
download_and_load_dataset,
normalize_text,
prepare_answer_extraction_samples,
prepare_qa_sample,
prepare_qg_samples,
)
# former url train data was unfit for (pyarrow) data... |
4858008 | from os import path
import bcolz
import numpy as np
def get_val_pair(folder_path, name):
samples = bcolz.carray(rootdir=path.join(folder_path, name), mode="r")
issame = np.load(path.join(folder_path, "{}_list.npy".format(name)))
return samples, issame
|
4858026 | from modules.deltavae.encoder_decoder_architectures.decoder import decoder_parent
import keras.layers, keras.models
import numpy as np
import tensorflow as tf
class DecoderDense(decoder_parent.Decoder):
def __init__(self, input_shape,
dense_units_list=[64], batch_normalization = True, decoder_ou... |
4858041 | from modulated_deform_conv import *
batch=1
cpudata=torch.ones(batch,1,5,5,requires_grad=True)
# data=torch.ones(batch,1,5,5,device='cuda',requires_grad=True)
data=cpudata.cuda()
offset=torch.zeros(batch,18,5,5,device='cuda',requires_grad=True)
mask=torch.ones(batch,9,5,5,device='cuda',requires_grad=True)
weight=torch.... |
4858057 | class Help(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Help"
self.description = "Help description for WhiteboxTools"
self.category = "About WhiteboxTools"
self.canRunInBackground = False
def getParameterInfo(self... |
4858091 | import sys
import numpy as np
import scipy.ndimage as nd
from scipy.cluster.vq import vq
from scipy.misc import imsave
def crayola_9():
"""
Palette of the first 8 crayola colors + white
"""
palette = []
palette.append([0,0,0])
palette.append([31, 117, 254])
palette.append([180, 103, 77])
... |
4858092 | import taichi as ti
import taichi_glsl as ts
from .AbstractProjectionSolver import ProjectionSolver
from utils import Float
# ref1 : https://www.cs.cornell.edu/~bindel/class/cs5220-s10/slides/lec14.pdf
# ref2 : https://github.com/ShaneFX/GAMES201/blob/330d9c75cacfad6901605d3f589eea11954d9a93/HW01/Smoke3d/smoke_3D.py
... |
4858101 | from django.urls import reverse_lazy
from django.views.generic.edit import UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import redirect
from forums.forms import UserProfileForm
from forums.models import UserProfile
class UserProfileUpdate(LoginRequire... |
4858136 | from .assemblydoc import AssemblyDoc
from .com import COM
from .drawingdoc import DrawingDoc
from .enums.enum_types import DocumentTypes
from .partdoc import PartDoc
class Doc:
class __Doc:
def __init__(self, system_object=None):
self.system_object = system_object
del self
... |
4858139 | from flask import Flask
from flask_script import Manager, Server
from App import create_app
app = create_app()
manager = Manager(app=app)
manager.add_command('runserver', Server(use_debugger=False))
if __name__ == '__main__':
# app.run(debug=False, host='0.0.0.0', port=10091)
manager.run() |
4858142 | import sys
import brian2
import numpy as np
# Run tests for float32 and float64
success = [brian2.test(long_tests=True, test_standalone='cpp_standalone', float_dtype=np.float32),
brian2.test(long_tests=True, test_standalone='cpp_standalone', float_dtype=np.float64)]
result = ['Tests for {} dtype: {}'.form... |
4858170 | from unittest import mock
from django.test import TestCase, RequestFactory
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.test.utils import override_settings
from django.urls import reverse
from mapentity.factories import SuperUserFactory
from mapentity.registry import... |
4858177 | import logging
class Publisher:
"""
A base Publisher class to contain the common functionality
of adding, removing, and notifying observers
"""
def __init__(self):
self.observers = []
self.logger = logging.getLogger('opsgenie_sdk')
def subscribe(self, observer):
if ob... |
4858205 | from quex.frs_py.file_in import error_msg
import quex.core_engine.state_machine.parallelize as parallelize
from quex.core_engine.generator.action_info import PatternActionInfo
import quex.core_engine.state_machine.nfa_to_dfa as nfa_to_dfa
import quex.core_engine.state_machine.hopcrof... |
4858243 | import unittest
from unittest.mock import Mock
from sshkernel.kernel import SSHKernel
from sshkernel.magics.magics import SSHKernelMagics
from sshkernel.magics.magics import expand_parameters
from sshkernel.magics.magics import validate_value_string
from paramiko import AuthenticationException
class MagicTest(unitt... |
4858252 | from counterfit_connection import CounterFitConnection
CounterFitConnection.init('127.0.0.1', 5000)
import time
from counterfit_shims_seeed_python_dht import DHT
sensor = DHT("11", 5)
while True:
_, temp = sensor.read()
print(f'Temperature {temp}°C')
time.sleep(10) |
4858255 | from __future__ import division
# Python Built-Ins:
import gzip
import os
import shutil
import subprocess
import tarfile
import time
from typing import Optional
# External Dependencies:
import numpy as np
from sklearn import preprocessing
import torchtext
def wait_for_file_stable(path: str, stable_secs: int=60, pol... |
4858300 | from . import views
from django.urls import path, re_path
app_name = 'downloads'
urlpatterns = [
re_path(r'latest/python2/?$', views.DownloadLatestPython2.as_view(), name='download_latest_python2'),
re_path(r'latest/python3/?$', views.DownloadLatestPython3.as_view(), name='download_latest_python3'),
path('... |
4858312 | import sys
import glob
import numpy
from PIL import Image
import cv2
tp = 0
fp = 0
fn = 0
obj_tp = 0
obj_fp = 0
obj_fn = 0
min_cluster = 10
max_cluster = 1000
for folder in sys.argv[1:]:
for testfile in glob.glob('%s/prediction*.png' % folder):
annotation = numpy.array(Image.open(testfile.replace('predict... |
4858414 | import FWCore.ParameterSet.Config as cms
stripCPEESProducer = cms.ESProducer("StripCPEESProducer",
ComponentName = cms.string('stripCPE'),
ComponentType = cms.string('SimpleStripCPE'),
parameters = cms.PSet()... |
4858415 | import numpy as np
import math
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight):
"""
Crops a rectangle by the specified number of pixels on each side.
The input rectangle and return value are both a tuple of (x,y,w,h).
"""
# Unpack the rectangle
x, y, w, h = rect
# Crop by the speci... |
4858419 | from bulbs.model import Node
from bulbs.property import String
class Idea(Node):
element_type = "idea"
text = String(nullable=False)
stub = String("make_stub")
def make_stub(self):
return utils.create_stub(self.text)
def after_created(self):
Relationship.creat... |
4858431 | import argparse
from signal_generator import generate_signals_for_seed
ARGS = [
{
'args': ('--groundstation-file',),
'kwargs': {
'type': str,
'help': "Local path to file of groundstation locations",
'required': True
}
},
{
'args': ('--tle... |
4858439 | from __future__ import division
import matplotlib.pyplot as plt
from lyssa.dict_learning import ksvd_coder, online_dictionary_coder
from lyssa.sparse_coding import sparse_encoder
from lyssa.feature_extract.preproc import preproc
from lyssa.utils.img import extract_patches
from lyssa.utils import get_images
from sklea... |
4858491 | from abc import ABC, abstractmethod
class ClassFromKeymapFactory(ABC):
def __init__(self, key):
self._key = key
@property
@abstractmethod
def _keymap(self) -> dict:
""" This property should be implemented. """
def get_class(self):
return self._keymap.get(self._key, None)
... |
4858500 | class Solution:
"""
@param n: count lucky numbers from 1 ~ n
@return: the numbers of lucky number
"""
def luckyNumber(self, n):
# Write your code here
return sum('8' in str(i) for i in range(1, n + 1))
|
4858521 | from __future__ import division
from __future__ import absolute_import
from Queue import Queue
import traceback
import rospy
from threading import Event
from .hexapod_ik_driver import LegPositions, Vector3, Vector2, LegFlags
from .hexapod_choreographer import Choreographer
from hopper_controller.msg import FoldCommand... |
4858523 | import re
MIN_BARS = 15
GRAMMAR_CHARACTERS = "zabcdefgABCDEFG23468T-^=_,></'|"
# region REGULAR EXPRESSION OBJECTS
# region --- Grammar Generation
APOSTROPHE_RE = re.compile('[’`´]')
SEMICOLON_RE = re.compile(';')
BARLINES_RE = re.compile('(\|]+)|(\[+\|)|(\|!\|)')
REPEATS_RE = re.compile(':\|*:+')
END_1_RE = re.compi... |
4858536 | import os, sys
import numpy as np
import argparse
import time
from scipy import stats
from simple_projections import project_onto_chi_square_ball
from create_datasets import data_loader
def add_intercept(X):
intercept = np.ones((X.shape[0], 1))
return np.concatenate((X, intercept), axis=1)
def sigmoid(z):
... |
4858569 | from runner.run_descriptions.run_description import RunDescription, Experiment, ParamGrid
_params = ParamGrid([
('icm_beta', [0.2, 0.5, 0.8]),
('prediction_bonus_coeff', [0.01, 0.02, 0.05]),
])
_experiment = Experiment(
'doom_sweep',
'python -m algorithms.curious_a2c.train_curious_a2c --env=doom_maze_... |
4858586 | import torch
from torch import nn
import torch.nn.functional as F
import math
class biDafAttn(nn.Module):
def __init__(self, channel_size):
super(biDafAttn, self).__init__()
"""
This method do biDaf from s2 to s1:
The return value will have the same size as s1.
:param c... |
4858591 | import pytest
from tests.test_resources.helper import get_stream
from common.settings import UPDATED_BEFORE_DATE
from tests.test_resources.test_settings import NUMBER_OF_ADS, DAWN_OF_TIME, current_time_stamp
# mark all tests in this file as @pytest.mark.jobstream
pytestmark = pytest.mark.jobstream
def test_stream_filt... |
4858599 | import os
import random
from dotenv import load_dotenv
load_dotenv()
os.environ["LOCAL_DB"] = "True"
# Set random seed, for random team matches
random.seed(5511)
from src.process.process_main import process_main # noqa: E402
start_year = 2022
end_year = 2022
clean = False
process_main(start_year, end_year, clea... |
4858625 | from django.utils.translation import ugettext_lazy as _
from django.utils import six
from django_filters import FilterSet, CharFilter, BooleanFilter, ChoiceFilter
from .models import Engagement_Survey, Question
class SurveyFilter(FilterSet):
name = CharFilter(lookup_expr='icontains')
description = CharFilter... |
4858640 | import argparse
import os
import io
import shutil
import tarfile
import wget
import subprocess
from utils import create_manifest
parser = argparse.ArgumentParser(description='Processes nikl.')
parser.add_argument('--target-dir', default='./data/nikl_dataset', help='Path to save dataset')
parser.add_argument('--min-du... |
4858656 | from scrapy import Request, Spider
class DelaySpider(Spider):
name = "delay"
def start_requests(self):
for delay in [1, 2, 3, 4, 5]:
url = "http://httpbin.org/delay/{}".format(delay)
yield Request(url)
def parse(self, response):
pass
|
4858668 | from packaging import version
try:
import fsspec
assert version.parse(fsspec.__version__) >= version.parse("0.4.4")
except (ImportError, AssertionError): # pramga: no cover
raise ImportError('The llcreader module requires fsspec version 0.4.4 or '
'or greater to be installed. '
... |
4858669 | import json
import os
import pickle
import random
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
from sklearn.metrics import roc_auc_score
from torch.utils.data import Dataset, DataLoader
def unpickle(file):
import _pickle as cPickle
with open(file, 'rb') as fo:
... |
4858720 | from .conv_ae import ConvAE
from .eqv_ae import EquivariantAE
from .gconv_ae import GConvAE
from .conv_vae import ConvVAE
from .gconv_vae import GConvVAE
from .eqv_vae import EquivariantVAE
from .monet import MONet
from .eqv_monet import EquivariantMONet
|
4858732 | import matplotlib.pyplot as plt
import numpy as np
import sys
if __name__ == '__main__':
img = plt.imread(sys.argv[1])
img = np.transpose(img, [2,0,1])
with open('image.c', 'w') as f:
print('const unsigned char gImage_image[] __attribute__((aligned(128))) ={', file=f)
print(', '.j... |
4858740 | import sys, os
import re
import math
import datetime as dt
import numpy as np
from scipy import stats
import urepr
from loguniform import LogUniform, ModifiedLogUniform
from kumaraswamy import kumaraswamy
# CONSTANTS
mjup2mearth = 317.8284065946748 # 1 Mjup in Mearth
template_setup = """
[kima]
GP: false
G... |
4858784 | from __future__ import print_function
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
4858797 | r'''
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
'''
import codecs
from os import path
from setuptools import find_packages
from setuptools import setup
install_requires = ['gin-config >= 0.1.1', 'absl-py >= 0.2.2',
'tensorflow==1.15.4', 'opencv-python >= 3.4.1.15',
... |
4858836 | from datetime import datetime
from .base import AutoFocusObject
# A dictionaries for mapping AutoFocus Analysis Response objects
# to their corresponding normalization classes and vice-vers
_coverage_2_class_map = {}
_class_2_coverage_map = {}
class AutoFocusCoverage(AutoFocusObject):
def __init__(self, obj_dat... |
4858842 | import numpy as np
import os
import torch
from PIL import Image
import torchvision.transforms as transforms
from tlkit.data.img_transforms import MAKE_RESCALE_0_1_NEG1_POS1
SPLITS = ['train', 'val', 'test']
t_to_np = lambda x: (np.transpose(x.cpu().numpy(), (1,2,0)) * 255).astype(np.uint8)
show = lambda x: Image.froma... |
4858872 | import abc
import copy
import torch
import numpy as np
from rl_agents.agents.budgeted_ftq.greedy_policy import optimal_mixture, pareto_frontier_at
from rl_agents.agents.common.exploration.epsilon_greedy import EpsilonGreedy
from rl_agents.agents.common.utils import sample_simplex
class BudgetedPolicy:
__metaclas... |
4858887 | import csv
import numpy as np
from sklearn import cluster, covariance, manifold
from sklearn.cluster import MeanShift, estimate_bandwidth
import matplotlib.pyplot as plt
# Load data from input file
input_file = 'wholesale.csv'
file_reader = csv.reader(open(input_file, 'rb'), delimiter=',')
X = []
for count, row in en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.