id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11450373 | from setuptools import setup
with open("anom/__init__.py") as module:
version_marker = "__version__ = "
for line in module:
if line.startswith(version_marker):
version = line[len(version_marker):].strip().strip('"')
break
else:
assert False, "could not find version ... |
11450384 | from pyrealtime.layer import ProducerMixin, ThreadLayer, TransformMixin, EncoderMixin, DecoderMixin
import time
def find_serial_port(name):
"""Utility function to scan available serial ports by name. The returned object is intended to be passed to the
:meth:`~pyrealtime.serial_layer.SerialWriteLayer.from_port... |
11450397 | from pkg_resources import get_distribution, DistributionNotFound
try:
version = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
version = "unknown"
__title__ = 'pycoin'
__author__ = '<NAME>'
__version__ = version
__license__ = 'MIT'
__copyright__ = 'Copyright 201... |
11450459 | from typing import Dict, List, Tuple, Any
import copy
import json
import pickle
import pytest
from metadict import MetaDict
from metadict.metadict import complies_variable_syntax
@pytest.fixture
def config() -> Dict:
dropout = [[0.1, 0.2]]
special_tokens = [['<NUM>', '<YEAR>']]
tokenizer_... |
11450555 | from pyalign.tests import TestCase
from typing import Iterator
import pyalign.problems
import pyalign.solve
import pyalign.gaps
class TestWatermanSmithBeyer(TestCase):
def test_cg_ccga(self):
# test case is taken from default settings (for logarithmic gap settings) at
# http://rna.informatik.uni-freiburg.de/Tea... |
11450562 | from logging import NullHandler
from typing import List, Dict, Tuple
import tqdm.notebook as tq
from tqdm.notebook import tqdm
import pandas as pd
import numpy as np
import torch
from pathlib import Path
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks im... |
11450591 | import sys
inputFile = str(sys.argv[1])
file = open(inputFile, 'r')
words = file.read().split()
d = {}
for word in words:
if word in d:
continue
else:
d[word] = words.count(word)
newFile = open('Q1.txt', 'w')
i = 0
for key in d:
if i == len(d) - 1:
var = key + ' ' + str(i) + ' ' + ... |
11450610 | import pytest # type: ignore
import itertools
import trio
import trio.testing
from .. import RWLock
from typing import List, Optional
from trio_typing import TaskStatus
async def test_rwlock(autojump_clock: trio.testing.MockClock) -> None:
lock = RWLock()
assert not lock.locked()
lock.acquire_read_nowai... |
11450614 | import mxnet as mx
import numpy as np
import numpy.matlib
import numpy.random
import os
import json, pickle
import random
import logging
import lmdb
import time
class SimpleBatch(object):
def __init__(self, data_names, data, label_names, label,
bucket_key=None, qid=None, ans_all=None, splits=None):
... |
11450637 | import dbus
import time
class wifiUtils:
def __init__(self,interface):
self.bus = dbus.SystemBus()
self.manager_bus_object = self.bus.get_object("org.freedesktop.NetworkManager",
"/org/freedesktop/NetworkManager")
self.manager = dbus.Interface(sel... |
11450642 | import os.path
import sys
from pyaxmlparser.arscparser import ARSCParser
from pyaxmlparser.axmlprinter import AXMLPrinter
from pyaxmlparser.utils import NS_ANDROID
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
test_apk = 'tests/test_apk/'
def test_app_name_extraction():
axml_file = os.path.join(test_apk, '... |
11450645 | import sys
import subprocess
def get_environment_from_batch_command(env_cmd, initial=None):
"""
Take a command (either a single command or list of arguments)
and return the environment created after running that command.
Note that if the command must be a batch file or .cmd file, or the
changes to ... |
11450662 | import os
from pint import UnitRegistry
def unit_registry():
file_path = os.path.join(os.path.dirname(__file__), 'default_units.txt')
return UnitRegistry(file_path)
def unit_list():
reg = unit_registry()
return [u for u in dir(reg) if isinstance(getattr(reg, u), type(reg.A))] |
11450671 | from kivymd_extensions.sweetalert.animation.failure_icon import FailureAnimation
from kivymd_extensions.sweetalert.animation.others_icon import OthersAnimation
from kivymd_extensions.sweetalert.animation.success_icon import SuccessAnimation
|
11450707 | import os
import numpy as np
import cv2
from imgreg2D import CACHE_IMG_PATH
def create_marked_ref_image(img, points):
"Adds a circle and a number to mark where the fixed points are on the template image"
# Opencv font stuff
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
... |
11450720 | from enum import Enum
from typing import Optional, Any
from System import Exception as CSharpException # pylint: disable=import-error
from FlaUILibrary.flaui.util.converter import Converter
from FlaUILibrary.flaui.exception import FlaUiError
from FlaUILibrary.flaui.interface import (ModuleInterface, ValueContainer)
... |
11450729 | from model.alphagozero_resnet_model import *
class AlphaGoZeroResNetELU(AlphaGoZeroResNet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _relu(self, x, leak=0):
"""change relu to elu"""
return tf.nn.elu(x)
# override _residual block with ELU model
... |
11450754 | import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from mesa.batchrunner import BatchRunnerMP
from elecsim.model.world import World
import logging
"""
File name: batch_run
Date created: 19/01/2019
Feature: # Enables world to be run multiple times based on different parame... |
11450779 | import random
def amb(
pitch_center=40,
pitch_range=6,
pulse=120,
rhythm=0.0,
detune=0.0,
repeat=0.5,
memory=5,
length=24,
):
"""Simple version of <NAME>'s Anna's Music Box as a function."""
# start with empty lists for both pitch and duration
my_pitches = []
my_durs =... |
11450825 | from abc import ABC, abstractmethod
import torch
import torch.nn as nn
import numpy as np
from typing import Optional, Union, List, Dict, Iterator, Tuple
from lifelong_methods.models.resnetcifar import ResNetCIFAR
from lifelong_methods.models.resnet import ResNet
from lifelong_methods.utils import get_optimizer
from i... |
11450841 | from lib.utils import note_name, note_number
def test_note_name():
assert 'C4' == note_name(60)
assert 'Db4' == note_name(61)
assert 'D4' == note_name(62)
assert 'Eb4' == note_name(63)
assert 'E4' == note_name(64)
assert 'F4' == note_name(65)
assert 'Gb4' == note_name(66)
assert 'G4' =... |
11450868 | from __future__ import unicode_literals
from contextlib import contextmanager
from itertools import product
import os
import shutil
import pytest
from pre_commit_hooks.insert_license import main as insert_license, LicenseInfo
from pre_commit_hooks.insert_license import find_license_header_index
# pylint: disable=too... |
11450877 | from django.contrib.auth.backends import RemoteUserBackend
class InvRemoteUserBackend(RemoteUserBackend):
def configure_user(self, user):
user.set_unusable_password()
user.save()
return user
|
11450958 | import functools
import math
from math import sqrt
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from torch import einsum
from models.gpt_voice.dvae_arch_playground.discretization_loss import DiscretizationLoss
from models.vqvae.vqvae import Quantize
from trainer.netw... |
11450964 | import os
from datetime import datetime
import pytz
from tempfile import NamedTemporaryFile
from uuid import uuid4
from urllib.parse import urlencode
from django.utils.deconstruct import deconstructible
from django.conf import settings
from django.core.files.storage import Storage
from django.core.urlresolvers import... |
11450991 | import rest_framework.pagination as pagination
from rest_framework.response import Response
class GenericModelPaginator(pagination.PageNumberPagination):
page_size = 12
page_size_query_param = 'page_size'
def get_paginated_response(self, data):
return Response({
'results': data,
... |
11450997 | from collections import deque
import logging
import os
import numpy as np
from chainerrl.experiments.evaluator import Evaluator
from chainerrl.experiments.evaluator import save_agent
def train_agent_batch(agent, env, steps, outdir,
checkpoint_freq=None, log_interval=None,
... |
11451026 | from airflow.hooks.base_hook import BaseHook
class SomethingHook(BaseHook):
def __init__(self, *args, **kwargs):
pass
def get_conn(self):
pass
def get_records(self, sql):
pass
def get_pandas_df(self, sql):
pass
def run(self, sql):
pass
|
11451042 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="WonderPy",
version="0.1.0",
author="<NAME>",
author_email="<EMAIL>",
description="Python API for working with Wonder Workshop robots",
long_description=long_description,
long_descr... |
11451079 | from __future__ import absolute_import
import cffi
import sys
ffibuilder = cffi.FFI()
ffibuilder.set_source('blurhash._functions', '''
#include <stdbool.h>
#include "common.h"
const char* blurHashForPixels(int x_components, int y_components,
int width, int height,
... |
11451090 | import re
__version__ = "1.4.0"
ESP32_DEFAULT_OTA_DATA = 'https://raw.githubusercontent.com/espressif/arduino-esp32/1.0.0/tools/partitions/boot_app0.bin'
ESP32_DEFAULT_BOOTLOADER_FORMAT = 'https://raw.githubusercontent.com/espressif/arduino-esp32/' \
'1.0.4/tools/sdk/bin/bootloader_$... |
11451144 | from flask import jsonify
from flask_restful import Resource
from database.constants import (
all_tags,
)
#===========================================================================
# * TAGS RESTful Resource
# ? Locally computes the `tags` nested list-field of the Snippet model
#
# Responsible... |
11451146 | from builtins import str
import hashlib
from flask import Flask, abort, redirect, url_for, make_response
from flask_restful import Resource, Api, abort
from vegadns.api import endpoint
from vegadns.api.config import config
from vegadns.api.endpoints import AbstractEndpoint
from vegadns.api.models.domain import Domain... |
11451195 | import os
import re
from datetime import datetime as dt
from typing import Optional, Dict, List, Any
from pandas import DataFrame
from pymongo import MongoClient
from database.issues.preprocessor import preprocess_df
MONGODB_HOST = os.environ.get("MONGODB_HOST", default="localhost")
MONGODB_PORT = int(os.environ.ge... |
11451231 | from typing import Optional
import typer
from python_on_whales import docker
from python_on_whales.download_binaries import download_docker_cli
app = typer.Typer()
volume_app = typer.Typer()
@volume_app.command()
def copy(source: str, destination: str):
if ":" in source:
source_volume, source_path = ... |
11451278 | import argparse
import itertools
import random
import time
import cv2
import numpy as np
from PIL import ImageDraw, Image
from backbone.base import Base as BackboneBase
from config.eval_config import EvalConfig as Config
from dataset.base import Base as DatasetBase
from bbox import BBox
from model import Model
from r... |
11451299 | import pytest
from aiogoogle.resource import (
Resource,
GoogleAPI,
STACK_QUERY_PARAMETER_DEFAULT_VALUE,
STACK_QUERY_PARAMETERS,
)
from ..ALL_APIS import ALL_APIS
@pytest.mark.parametrize("name,version", ALL_APIS)
def test_getitem(open_discovery_document, name, version):
discovery_document = open... |
11451429 | bl_info = {
"name": "Spaceship Generator",
"author": "<NAME>",
"version": (1, 1, 3),
"blender": (2, 80, 0),
"location": "View3D > Add > Mesh",
"description": "Procedurally generate 3D spaceships from a random seed.",
"wiki_url": "https://github.com/a1studmuffin/SpaceshipGenerator/blob/master... |
11451436 | import pytz
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.views.decorators.cache import cache_page
from panopuppet.pano.puppetdb import puppetdb
from panopuppet.pano.puppetdb.puppetdb import set_server, get_server
from panopuppet.pano.settings impo... |
11451440 | import time
from django.core.management.base import BaseCommand
from drawquest.apps.quest_comments.models import QuestComment
class Command(BaseCommand):
args = ''
help = "Top 30 shared links from the last 30 days."
def handle(self, *args, **options):
urls = defaultdict(int)
num... |
11451487 | import fire
import numpy as np
# Useful imports
# from example_save_trials import *
import tensorflow as tf
# Import the necessary garage classes
from garage.experiment import run_experiment
from garage.np.baselines.zero_baseline import ZeroBaseline
from garage.tf.envs import TfEnv
from garage.tf.experiment import Loca... |
11451513 | from abc import abstractmethod
from ledger.util import count_bits_set
from ledger.util import highest_bit_set
class HashStore:
"""
Store of nodeHashes and leafHashes mapped against their sequence numbers.
"""
@property
@abstractmethod
def is_persistent(self) -> bool:
pass
@abstra... |
11451569 | from rest_framework import serializers
from user.models import Author
class AuthorDocumentSerializer(serializers.ModelSerializer):
profile_image = serializers.SerializerMethodField()
university = serializers.SerializerMethodField()
headline = serializers.SerializerMethodField()
class Meta(object):
... |
11451594 | from django.contrib.auth.models import AnonymousUser
from core.models import Identity
from api.v2.serializers.post import AccountSerializer
from api.v2.views.base import AdminModelViewSet
class AccountViewSet(AdminModelViewSet):
"""
API endpoint that allows providers to be viewed or edited.
"""
look... |
11451615 | import pygtk
pygtk.require('2.0')
import gtk
import sys
import gobject
import sqlite3
import time
import datetime
class LibManager:
bookColumName = (u"书本号", u"书名", u"作者", u"出版社",
u"价格", u"购入日期", u"分类", u"简介", u"馆藏数")
readerColumName = (u"读者号", u"读者姓名", u"读者身份", u"备注")
def __init__(self):
self.dbconn = sqlite... |
11451667 | from onnx_tf.common import get_unique_suffix
from onnx_tf.handlers.frontend_handler import FrontendHandler
from onnx_tf.handlers.handler import tf_op
from onnx_tf.handlers.frontend.div import Div
from onnx_tf.handlers.frontend.floor import Floor
from onnx_tf.pb_wrapper import TensorflowNode
@tf_op("FloorDiv")
class F... |
11451694 | from bottle import route, hook, response, run, request
import datetime
import remotequeue
import sys
Q = remotequeue.get('127.0.0.1', 'secret')
@hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
@route('/')
def index():
print '[' + str(datetime.datetime.now()) + '... |
11451714 | class Counter:
def __init__(self, name, number, description):
self.name = name
self.description = description
try:
self.number = int(number)
except ValueError:
self.number = 0
class Parser:
def __init__(self, filename=None):
self.counters = {}
... |
11451717 | import os
import sys
# Append OpenSpiel (included in this package's git repository) to the system path so it can be imported.
_OPEN_SPIEL_MODULES_PATH = os.path.abspath(os.path.join(__file__, "../../../dependencies/open_spiel"))
_OPEN_SPIEL_PYBIND_PATH = os.path.join(_OPEN_SPIEL_MODULES_PATH, "build/python")
sys.path.... |
11451728 | import json
import sys
import convert
import AO3search
# takes in a JSON filename and returns a list of AO3data objects containing the search specifications
def importFile(filename, verbose):
# load JSON from file
try:
with open(filename) as f:
j = json.load(f)
except:
sys.exi... |
11451731 | import unittest
from app import configure_proxy_settings
IP = '127.0.0.1'
PORT = '8000'
USERNAME = 'user'
PASSWORD = 'password'
class ProxyConfigTestCase(unittest.TestCase):
def test_proxies_without_credentials(self):
actual = configure_proxy_settings(IP, PORT)
expected = {'http': 'http://127.0.0... |
11451742 | import logging
import sys
log = logging.getLogger(__name__)
def is_inside_idle():
"""True if program was started inside IDLE.
The implementation is a HACK, because there is no correct solution.
"""
idle = 'idlelib.run' in sys.modules
if idle:
log.debug('Running IDLE')
return idle
|
11451831 | import pytest
import torch
import torch.nn as nn
from mmcv.cnn.bricks import (ACTIVATION_LAYERS, CONV_LAYERS, NORM_LAYERS,
PADDING_LAYERS, build_activation_layer,
build_conv_layer, build_norm_layer,
build_padding_layer, build_upsamp... |
11451920 | import os
import sys
from cottoncandy import options
args = sys.argv
paths_to_search_list = args[1:]
replacement_dict = {
options.config.get('login', 'access_key'): "FAKE_ACCESS_KEY",
options.config.get('login', 'secret_key'): "FAKE_SECRET_KEY",
options.config.get('login', 'endpoint_url'): "FAKE_ENDPOINT... |
11451941 | import base64
import random
import string
mimiakatz_file=open('mimikatz.exe','rb')
base64_str = base64.b64encode(mimiakatz_file.read())
print base64_str
|
11451952 | import unittest
import copy
import os
import numpy as num
from anuga.config import netcdf_float
from anuga.coordinate_transforms.geo_reference import Geo_reference
from anuga.geometry.polygon import is_inside_polygon
from anuga.abstract_2d_finite_volumes.util import file_function
from anuga.config import netcdf_mode... |
11451955 | import os
import unittest
from programytest.client import TestClient
class PatternSetTestClient(TestClient):
def __init__(self):
TestClient.__init__(self)
def load_storage(self):
super(PatternSetTestClient, self).load_storage()
self.add_default_stores()
self.add_categories_s... |
11451982 | import angr
class GetCurrentThreadId(angr.SimProcedure):
def run(self):
return 0xbad76ead
|
11452016 | from django.utils.translation import ugettext_lazy as _
def humanize_duration(duration):
"""
Returns a humanized string representing time difference
For example: 2 days 1 hour 25 minutes 10 seconds
"""
days = duration.days
hours = duration.seconds / 3600
minutes = duration.seconds % 3600 ... |
11452041 | from torch.utils.data import Dataset
import logging
import gzip
from queue import Queue
from .. import SentenceTransformer
from typing import List
import random
class ParallelSentencesDataset(Dataset):
"""
This dataset reader can be used to read-in parallel sentences, i.e., it reads in a file with tab-seperate... |
11452068 | import os
import textwrap
import xml.etree.ElementTree as ET
from scripts.artifact_report import ArtifactHtmlReport
from scripts.cleapfuncs import logfunc, logdevinfo, tsv, timeline, is_platform_windows, get_next_unused_name, open_sqlite_db_readonly, get_browser_name
def get_paloAltoGlobalProtect(files_found, report_... |
11452095 | import json
import logging
import os
import time
from typing import Dict, Optional
from os import path
from autoconf import conf
import autofit as af
import autoarray as aa
import autogalaxy as ag
from autoarray.exc import PixelizationException
from autolens.lens.model.analysis import AnalysisDataset
... |
11452122 | import io
import re
import sys
import time
import pprint
import os.path
import logging
import pytest
import yaml
import colorama
from werkzeug.exceptions import HTTPException
from piecrust.app import PieCrustFactory, apply_variants_and_values
from piecrust.configuration import merge_dicts
from .mockutil import mock_fs,... |
11452145 | class pyArangoException(Exception):
"""The calss from witch all Exceptions inherit"""
def __init__(self, message, errors = None):
Exception.__init__(self, message)
if errors is None:
errors = {}
self.message = message
self.errors = errors
def __str__(self):
... |
11452146 | import math
import torch
from torch import nn, cat
import torchvision
class ConvRelu(nn.Module):
def __init__(self, in_, out, activate=True):
super(ConvRelu, self).__init__()
self.activate = activate
self.conv = nn.Conv2d(in_, out, 3, padding=1)
self.activation = nn.ReLU(inplace=Tr... |
11452206 | import fields
import debug
import csv
import os
import sys
import datetime
def writer(vulns, **params):
csvfile = params['fobj']
flist = params['flist']
debug.write('.')
for vuln in vulns:
# First thing before we do any parsing is we need to generate the
# firstSeenDate and lastSeenDa... |
11452215 | r"""
Composition Tableaux
AUTHORS:
- <NAME>, <NAME> (2012-9): Initial version
"""
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
from sage.sets.non_negative_integers import NonNegativeIntegers
from sage.sets.family import Family
from sage.misc.classcall_metaclass import ClasscallMet... |
11452225 | true_statement = ("y", "yes", "on", "1", "true", "t")
def booleanize(value) -> bool:
"""
This function will try to assume that provided string value is boolean in some way. It will accept a wide range
of values for strings like ('y', 'yes', 'on', '1', 'true' and 't'. Any other value will be treated as fal... |
11452227 | import cv2
import numpy as np
import time
import threading
import queue
from xavier_config import qsize
class VideoStream(threading.Thread):
def __init__(self, url, pos, frame_q, resolution=(360, 640), threaded=False):
super(VideoStream, self).__init__()
self.cam = cv2.VideoCapture(url)
se... |
11452244 | import os
import unittest.mock as mock
import synapse.common as s_common
import synapse.tests.utils as s_test
import synapse.lib.cell as s_cell
import synapse.lib.msgpack as s_msgpack
import synapse.tools.hive.load as s_hiveload
htree0 = {
'kids': {
'hehe': {'value': 20},
'haha': {'value': 30, ... |
11452287 | from pathlib import Path
import holoviews as hv
import numpy as np
from bokeh.document import Document
from panel.io.server import set_curdoc
from panel.param import Param
from lumen.sources import DerivedSource, FileSource
from lumen.state import state
from lumen.target import Target
from lumen.transforms import As... |
11452300 | from unittest import TestCase
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
import requests
from core.govdelivery import (
ExceptionMockGovDelivery,
LoggingMockGovDelivery,
MockGovDelivery,
ServerErrorMockGovDelivery,
get_govdelivery_api,
)
class Unit... |
11452310 | import argparse
from autolab_core import YamlConfig
from isaacgym import gymapi
from isaacgym_utils.scene import GymScene
from isaacgym_utils.assets import GymFranka, GymBoxAsset, GymTetGridAsset
from isaacgym_utils.policy import GraspPointPolicy
from isaacgym_utils.draw import draw_transforms
if __name__ == "__mai... |
11452366 | from pytest import raises
from .env import NInt, get_session, key
from .env import session
from sider.types import SortedSet
from sider.transaction import Transaction
from sider.exceptions import CommitError
S = frozenset
IntSet = SortedSet(NInt)
def test_iterate(session):
set_ = session.set(key('test_sortedset... |
11452370 | from collections import OrderedDict
import numpy as np
class LogBuffer(object):
def __init__(self):
self.val_history = OrderedDict()
self.n_history = OrderedDict()
self.output = OrderedDict()
self.ready = False
def clear(self):
self.val_history.clear()
self.n... |
11452378 | import os
import sys
sys.path.append(os.getcwd())
import src.data.gen_data as data
import torch
from jobman import DD
vocab_paths = {
"emotion": "data/vocabs/emotion.vocab",
"motivation": "data/vocabs/motivation.vocab",
"sentence": "data/vocabs/tokens.vocab",
"plutchik": "data/vocabs/plutchik8.vocab... |
11452390 | import tensorflow as tf
import numpy as np
import math
import json
def uniform(shape, scale=0.05, name=None):
initial = tf.random_uniform(shape, minval=-scale, maxval=scale, dtype=tf.float32)
return tf.Variable(initial, name=name)
def glorot(shape, name=None):
init_range = np.sqrt(6.0/(shape[0]+shape[1]... |
11452403 | import numpy as np
import ipdb
def nms(scores, overlaps, th):
idx = []
N = len(scores)
if len(scores) < 1:
return idx
assert N == overlaps.shape[0] and N == overlaps.shape[1]
scores = np.array(scores)
sidx = np.argsort(scores)[::-1]
idx.append(sidx[0]) # retain the idx c.t. the h... |
11452424 | import Gramatica as Gram
import interprete as Inter
from Instruccion import *
from Instruccion import heap as hp
heap = hp
def ejecutarSQL():
cadena = heap[-1]
nueva = str(cadena).upper()
#print(nueva)
Inter.inicializarEjecucionAscendente(cadena)
#Inter.Ejecucion():
# if len(Lista) > 0:
# ... |
11452443 | from setuptools import setup, Extension
from subprocess import Popen, PIPE
import os, sys
#----------------------------------------------------------------------------
# Get version string from git
#
# Author: <NAME> <<EMAIL>>
# http://dcreager.net/2010/02/10/setuptools-git-version-numbers/
#
# PEP 386 adaptation from... |
11452487 | import os.path
import unittest
import numpy as np
import sys
compare_mt_root = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
sys.path.append(compare_mt_root)
from compare_mt import scorers
from compare_mt.corpus_utils import load_tokens, load_alignments
from compare_mt import compare_mt_main
from co... |
11452488 | from exports.bindings import Exports
from imports.bindings import add_imports_to_linker, Imports
from typing import Tuple, List
import exports.bindings as e
import imports.bindings as i
import sys
import wasmtime
class MyImports:
def list_in_record1(self, a: i.ListInRecord1) -> None:
pass
def list_in_... |
11452513 | from functools import wraps
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
return f(*args, **kwds)
return wrapper
|
11452523 | import torch.nn as nn
from nas_core.global_enum import Activation
from nas_core.layer.utils import _act
class BatchNorm1d_(nn.Module):
def __init__(self, num_features,
eps=1e-5,
momentum=0.1,
affine=True,
track_running_stats=True,
... |
11452525 | import os
import re
from math import ceil
base_dir = os.path.dirname(os.path.abspath(__file__))
def GetSelection(list_name):
rs=''
for i in list_name:
rs+=str(i)
rs=rs+' '
rs.strip(' ')
command = r'py {0}\delete_mark_ui.py {1}'.format(base_dir,rs)
r = os.popen(command)
output = r... |
11452537 | import numpy as np
import pylab as pl
x = np.random.uniform(1, 100, 1000)
y = np.log(x) + np.random.normal(0, .3, 1000)
pl.scatter(x, y, s=1, label="log(x) with noise")
pl.plot(np.arange(1, 100), np.log(np.arange(1, 100)), c="b", label="log(x) true function")
pl.xlabel("x")
pl.ylabel("f(x) = log(x)")
pl.legend(loc="b... |
11452541 | from django.test import TestCase
from models import check_achievement_class
class AchievementClassesCheckTest(TestCase):
def test_check_achievement_class(self):
class AchievementDef(object):
name = "Username achivement"
key = "username"
description = "Handles when a us... |
11452543 | import json
from LanguagePrinter import LanguagePrinter
def getName(j):
name = j['name']
if name.startswith('coq_') or name.startswith('Coq_'):
name = name[4:]
return name.replace('.coq_', '.').replace('.Coq_', '.')
def type_glob_to_str(j, ignoreFailures=False):
if not ignoreFailures:
... |
11452550 | from app import db
from app.models import BTCPayClientStore
from btcpay import BTCPayClient
from btcpay.crypto import generate_privkey
from flask import request
import os
import psutil
import signal
import time
from urllib.parse import urlparse, urljoin
def is_safe_url(target):
# prevents malicious redirects
... |
11452711 | from trame.app import get_server
from trame.assets.local import LocalFileManager
from trame.widgets import html, vuetify
from trame.ui.vuetify import SinglePageLayout
# -----------------------------------------------------------------------------
# Trame setup
# --------------------------------------------------------... |
11452720 | import os
import glob
import gym
import textworld.gym
def get_training_game_env(data_dir, difficulty_level, training_size, requested_infos, max_episode_steps, batch_size):
assert difficulty_level in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 99]
assert training_size in [1, 20, 100]
# training games
... |
11452743 | import json
import scrapy
from scrape.items import Item
class YellowSpider(scrapy.Spider):
name = "yellow"
def __init__(self, *args, **kwargs):
super(YellowSpider, self).__init__(*args, **kwargs)
self.seen_business_names = []
self.seen_phonenumbers = []
self.seen_websites = []
... |
11452772 | import os
import sys
import ssl
import pprint
import socket
import urllib.parse
# Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer.
from http.server import (HTTPServer as _HTTPServer,
SimpleHTTPRequestHandler, BaseHTTPRequestHandler)
from test import support
threading = support.import_mod... |
11452776 | import sys
import urllib
import requests
# print(sys.argv[0])
msg = sys.argv[1]
# url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}'.format(urllib.parse.quote(msg))
start_head = "http://api.qingyunke.com/api.php?key=free&appid=0&msg="
full_head = start_head+msg
# print(full_head)
url = full_head
html = r... |
11452791 | import os
import warnings
from functools import partial
from multiprocessing.pool import ThreadPool
from typing import Optional, Dict
import numpy as np
import onnxruntime as ort
from jina import Executor, requests, DocumentArray
from clip_server.model import clip
from clip_server.model.clip_onnx import CLIPOnnxModel... |
11452798 | from .features import RegexMatches, Stopwords
name = "bengali"
'''
try:
import enchant
dictionary = enchant.Dict("bn")
except enchant.errors.DictNotFoundError:
raise ImportError("No enchant-compatible dictionary found for 'bn'. " +
"Consider installing 'aspell-bn'.")
dictionary = ... |
11452873 | import asyncio, re, json
from smsgateway.sources.sms import command_list
from smsgateway.config import *
from smsgateway.sources.utils import *
from smsgateway import sink_sms
from telethon import TelegramClient, utils
from telethon.tl.types import Chat, User, Channel, \
PeerUser, PeerChat, PeerChannel, \
Me... |
11452874 | import numpy as np
import time
import os
import shutil
import sys
import warnings
import emoji
from inversionson import InversionsonError, InversionsonWarning
import toml
from colorama import init
from colorama import Fore, Style
from typing import Union, List
from inversionson.remote_helpers.helpers import preprocess_... |
11452884 | import torch
import torch.nn as nn
import torch.nn.functional as F
from dgmvae.dataset.corpora import PAD, BOS, EOS, UNK
from torch.autograd import Variable
from dgmvae import criterions
from dgmvae.enc2dec.decoders import DecoderRNN
from dgmvae.enc2dec.encoders import EncoderRNN
from dgmvae.utils import INT, FLOAT, LO... |
11452929 | import re
import unittest
from vgio.quake.tests.basecase import TestCase
from vgio.quake import map
significant_digits = 5
class TestMapReadWrite(TestCase):
def test_loads(self):
map_file = open('./test_data/test.map')
map_text = map_file.read(-1)
map_file.close()
world_spawn, i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.