id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11553225 | import math as _math
def error(msg, debug=True):
if debug:
print(f"[ERROR]! {msg}")
def warn(msg, debug=True):
if debug:
print(f"[WARNING]! {msg}")
def info(msg, debug=True):
if debug: print(f"{msg}")
def success(msg, debug=True):
if debug:
print(f"[SUCCESS]! {msg}")
de... |
11553243 | import yaml
from twisted.trial import unittest
from ooni.reporter import OSafeDumper
from scapy.all import IP, UDP
class TestScapyRepresent(unittest.TestCase):
def test_represent_scapy(self):
data = IP() / UDP()
yaml.dump_all([data], Dumper=OSafeDumper)
|
11553282 | import functools
import spconv.pytorch as spconv
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from ..ops import (ballquery_batch_p, bfs_cluster, get_mask_iou_on_cluster, get_mask_iou_on_pred,
get_mask_label, global_avg_pool, sec_max, sec_min, v... |
11553296 | import torch
import numpy as np
from mmdet.core import bbox2result
from mmdet.models.builder import DETECTORS
from ...core.utils import flip_tensor
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class CenterNet(SingleStageDetector):
"""Implementation of CenterNet(Objects as Points)
... |
11553302 | import hashlib
import logging
import subprocess
import tarfile # For sending through a channel.
from typing import List
import gevent
import pytest
import os
from dateutil.parser import parse as dateparse
from volttron.platform.messaging.health import STATUS_GOOD, STATUS_BAD, \
STATUS_UNKNOWN
from vo... |
11553333 | import numpy as np
from SALib.sample import sobol_sequence
from ..src.doe import DOE
from ..src.data import *
import pandas as pd
class doe_SALib(DOE):
"""
DOE-Module wrap for SALib
"""
def __init__(self, num, variable, method='sobol'):
""" Initialize """
self.__name__ = "SAL... |
11553342 | from __future__ import annotations
from jsonclasses import jsonclass, types
@jsonclass
class LinkedOwner:
id: str = types.str.primary.required
permissions: list[LinkedPermission] = types.listof('LinkedPermission').linkedby('owner')
@jsonclass(
can_read=types.getop.isobj(types.this.fval('owner'))
)
class... |
11553375 | from PikaObj import *
class List(TinyObj):
def __init__():
pass
# add an arg after the end of list
def append(arg: any):
pass
# get an arg by the index
def get(i: int) -> any:
pass
# set an arg by the index
def set(i: int, arg: any):
pass
# get the l... |
11553379 | from bitmovin.resources.models import H264CodecConfiguration
from ..rest_service import RestService
class H264(RestService):
BASE_ENDPOINT_URL = 'encoding/configurations/video/h264'
def __init__(self, http_client):
super().__init__(http_client=http_client, relative_url=self.BASE_ENDPOINT_URL, class_=... |
11553393 | import h5py
import json
import os.path
import numpy as np
import torch
import torch.nn.init
from torch.utils.data import Dataset
from PIL import Image
from torchvision import transforms
class sclevrDataset(Dataset):
"""clevr dataset."""
def __init__(self, opt, mode = 'train'):
"""
Args:
... |
11553399 | from .random_erasing import RandomErasing
from .pad_crop import padcrop
from .autoaug import ImageNetPolicy
from .augmix import AugMix
from .half_crop import HalfCrop
import torchvision.transforms as transforms
__transforms_factory_before = {
'autoaug': ImageNetPolicy(prob=0.5),
'randomflip': transforms.Rando... |
11553436 | import pandas as pd
from textblob import TextBlob
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def sentiment_scores(X):
"""
Calculate sentiment indicators from `TextBlob <https://textblob.readthedocs.io/en/dev/>`_ (polarity and
subjectivity) and `vaderSentiment <https://pypi.org/pr... |
11553447 | from datasets import fashion200k
from datasets import fashion_iq
from datasets import shoes
from datasets import vocabulary
import numpy as np
import tensorflow as tf
# python read_glove.py --dataset='fashion_iq' --data_path='datasets/fashion_iq/image_data'
# python read_glove.py --dataset='shoes' --data_path=''
# py... |
11553450 | from django.contrib.syndication.views import Feed
from django.utils import timezone
class LatestEntriesFeed(Feed):
def items(self):
now = timezone.now()
NewsItem = self.news_index.get_newsitem_model()
newsitem_list = NewsItem.objects.live().order_by('-date').filter(
newsindex=... |
11553451 | import unittest
import os
import fudge
from fudge.inspector import arg
from fabric.contrib import project
class UploadProjectTestCase(unittest.TestCase):
"""Test case for :func: `fabric.contrib.project.upload_project`."""
fake_tmp = "testtempfolder"
def setUp(self):
fudge.clear_expectations()... |
11553466 | from typing import List, Optional
import torch
import torch.nn as nn
from torecsys.layers import FMLayer, DNNLayer
from torecsys.models.ctr import CtrBaseModel
class FactorizationMachineSupportedNeuralNetworkModel(CtrBaseModel):
r"""
Model class of Factorization Machine supported Neural Network (FMNN).
... |
11553484 | import time
import json
from uuid import uuid4
from enum import Enum
from threading import Thread
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from clouds.models import StaticModel, Image, Instance, Mount, IN... |
11553506 | import numpy
import chainer
from chainer import configuration
from chainer import cuda
from chainer.functions.normalization import batch_normalization
from chainer import initializers
from chainer import link
from chainer.utils import argument
from chainer import variable
from chainer.links import EmbedID
import chain... |
11553509 | import simplejson as json
from django import template
from django.core.serializers import serialize
from django.db.models import QuerySet
from django.utils.encoding import force_str
from django.utils.functional import Promise
from django.utils.safestring import mark_safe
register = template.Library()
@register.simp... |
11553534 | from time import sleep
from abc import abstractmethod
from asciimatics.widgets import (
Frame, ListBox, Layout, Divider, Text, Button, Label, FileBrowser, RadioButtons, CheckBox, QRCode
)
from asciimatics.exceptions import NextScene
from asciimatics.event import KeyboardEvent, MouseEvent
from asciimatics.scene impo... |
11553555 | import torch
def append_bias_ones(tensor):
"""Appends vector of ones to last dimension of tensor.
For examples, if the input is of shape [4, 6], then the outputs has shape
[4, 7] where the slice [:, -1] is a tensor of all ones.
"""
shape = list(tensor.shape[:-1]) + [1]
return torch.cat([tenso... |
11553622 | from __future__ import division
from noise import snoise2
# TODO: add generator with Perlin noise, noise.pnoise2
LAKE_THRESHOLD = 0.35 # 0 to 1, fraction of water corners for water polygon
class SimplexIsland:
"""
Generate lands with Simplex noise.
"""
def __init__(self, islands_level=1.5, octaves... |
11553624 | from .data_dicts import LANGUAGE_DISTANCES
from typing import Dict, Tuple
TagTriple = Tuple[str, str, str]
_DISTANCE_CACHE: Dict[Tuple[TagTriple, TagTriple], int] = {}
DEFAULT_LANGUAGE_DISTANCE = LANGUAGE_DISTANCES["*"]["*"]
DEFAULT_SCRIPT_DISTANCE = LANGUAGE_DISTANCES["*_*"]["*_*"]
DEFAULT_TERRITORY_DISTANCE = 4
#... |
11553625 | from twisted.names import client, server, dns
from oonib.config import config
class DNSTestHelper(server.DNSServerFactory):
def __init__(self, authorities=None,
caches=None, clients=None,
verbose=0):
try:
host, port = config.helpers.dns.split(':')
... |
11553642 | class Juicer(object):
"""
Main class for all juicers.
"""
def __init__(self, name):
self.name = name
def juice(self, target_juice):
"""
This is the main function that processes the provided
target object.
:param target_juice: The target object which needs to be processed by the juicer.
:return: Dep... |
11553654 | import uuid
import json
import os
import pytest
import postgraas_server.backends.docker.postgres_instance_driver as pid
import postgraas_server.backends.postgres_cluster.postgres_cluster_driver as pgcd
import postgraas_server.configuration as configuration
from postgraas_server.backends.exceptions import PostgraasApiE... |
11553683 | import os
import os.path
import re
import shutil
import logging
import yaml
from piecrust.importing.base import FileWalkingImporter
logger = logging.getLogger(__name__)
class PieCrust1Importer(FileWalkingImporter):
name = 'piecrust1'
description = "Imports content from a PieCrust 1 website."
requires_we... |
11553686 | from contextlib import contextmanager
from ctypes import cast, c_void_p, POINTER, create_string_buffer
from os import fstat, stat
from . import ffi
from .ffi import (
ARCHIVE_EOF, OPEN_CALLBACK, READ_CALLBACK, CLOSE_CALLBACK, SEEK_CALLBACK,
NO_OPEN_CB, NO_CLOSE_CB, page_size,
)
from .entry import ArchiveEntry,... |
11553712 | import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_text as text
config = tfds.translate.wmt.WmtConfig(
description="WMT 2019 translation task dataset.",
version="0.0.3",
language_pair=("zh", "en"),
subsets={
tfds.Split.TRAIN: ["newscommentary_v13"],
tfds.Split.... |
11553748 | import asyncio
import websockets
from .majsoul_pb2 import Wrapper
class MSJRpcChannel(object):
def __init__(self, endpoint):
self._endpoint = endpoint
self._req_events = {}
self._new_req_idx = 1;
self._res = {}
self._hooks = {}
def add_hook(self, msg_type, hook):
... |
11553769 | from datadog import initialize, api
options = {
'api_key': '<DATADOG_API_KEY>',
'app_key': '<DATADOG_APPLICATION_KEY>'
}
initialize(**options)
# Cancel all downtimes with scope
api.Downtime.cancel_downtime_by_scope('env:testing')
|
11553784 | import os
from abc import ABC, abstractmethod
from collections import OrderedDict, namedtuple
from typing import List
from spotty.config.container_config import ContainerConfig
from spotty.config.project_config import ProjectConfig
from spotty.config.tmp_dir_volume import TmpDirVolume
from spotty.config.validation impo... |
11553832 | import os
import sys
import time
import pdb
import gc
import numpy as np
import faiss
import argparse
import resource
import benchmark.datasets
from benchmark.datasets import DATASETS
from benchmark.plotting import eval_range_search
####################################################################
# Index building... |
11553848 | from ...utilities import db, moocdb_utils
from common import *
from datetime import datetime
def GetForumPosts(vars):
output_items = []
post_ctid = moocdb_utils.GetCollaborationTypeMap(vars)['forum_post']
comment_ctid = moocdb_utils.GetCollaborationTypeMap(vars)['forum_comment']
forum_num_pos... |
11553856 | import os
import sys
import pickle
import argparse
import numpy as np
import time
from sklearn.metrics import balanced_accuracy_score, mean_squared_error
sys.path.append(os.getcwd())
from tpot import TPOTClassifier, TPOTRegressor
from mindware.datasets.utils import load_data, load_train_test_data
from mindware.compone... |
11553875 | from os.path import abspath
from os.path import dirname
import numpy as np
def generate_train_targets():
"""Used to generate the targets for each training set.
Note: The target datasets are already pre-generated in each folder as train_target.csv
"""
folders = ["phm", "cmapss_1", "cmapss_2", "cmapss_3... |
11553877 | import oss2
from aliyunsdkcore.client import AcsClient
import ci.util
def _credentials(alicloud_cfg: str):
if isinstance(alicloud_cfg, str):
cfg_factory = ci.util.ctx().cfg_factory()
alicloud_cfg = cfg_factory.alicloud(alicloud_cfg)
return alicloud_cfg
def oss_auth(alicloud_cfg: str):
cr... |
11553948 | import unittest
import const
import json
import jwsmodify_mitmproxy_addon as jma
class TestJWSModifyMethods(unittest.TestCase):
def test_can_find_raw_jws(self):
self.assertTrue(jma.extract_jws_payload(const.RAW_JWS) is not None)
def test_can_find_jws_in_json(self):
my_obj = {
... |
11553958 | import tvm
from tvm import te, arith
from tensorizer.intrinsics import INTRINSICS
import numpy as np
n, c, h, w = 1, 192, 18, 18
kh, kw, ic, ko = 3, 3, c, 192
a = te.placeholder((n, c // 16, h, w, 16), 'float16')
b = te.placeholder((ko // 16, ic // 16, kh, kw, 16, 16), 'float16')
rc = te.reduce_axis((0, c), 'rc')
rh... |
11553998 | from pybuilder.core import init, use_plugin
@init
def initialize(project):
project.set_property("run_unit_tests_propagate_stdout", True)
project.set_property("run_unit_tests_propagate_stderr", True)
project.set_property("verbose", True)
use_plugin("exec")
use_plugin("python.core")
use_plugin("python.uni... |
11554008 | from rest_framework.settings import api_settings
from rest_framework.throttling import (
UserRateThrottle as DefaultUserRateThrottle)
class UserRateThrottle(DefaultUserRateThrottle):
"""
Subclass of the original UserRateThrottle which applies settings
at init time, rather than class definition time. T... |
11554046 | import socket
import inspect
import contextlib
from unittest.mock import patch
from dffml.util.testing.source import SourceTest
from dffml.util.asynctestcase import AsyncTestCase
from dffml_source_mysql.source import MySQLSourceConfig, MySQLSource
from dffml_source_mysql.util.mysql_docker import mysql, DOCKER_ENV
... |
11554069 | from os import environ
INTEGRATION = 'INTEGRATION'
UNIT = 'UNIT'
MODE = environ.get('TEST_MODE', UNIT) |
11554101 | import matplotlib.pyplot as plt
from brancher.variables import ProbabilisticModel
from brancher.standard_variables import NormalVariable, LogNormalVariable
from brancher.transformations import truncate_model
from brancher.visualizations import plot_density
# Normal model
mu = NormalVariable(0., 1., "mu")
x = NormalV... |
11554130 | import argparse
import fasttext
import json
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument(
"-d",
"--documents",
type=str,
default="../training_data/training-data.json",
help="path to documents",
)
parser.add_argument(
"-train", "--train_document", type=str, default="... |
11554132 | from .assertion import Assertion
from .model import Model
from .policy import Policy
from .function import FunctionMap
|
11554150 | from .annotation import Annotation
from .shortcut_helper.shortcut_helper import Shortcut, ShortcutHelper
from .utils import AdditionalOutputElement
__all__ = ["Annotation", "AdditionalOutputElement", "Shortcut", "ShortcutHelper"]
|
11554173 | from drf_triad_permissions.permissions import get_triad_permission
class Policy:
allow = None
deny = None
@classmethod
def expand(cls, default_resource=None):
return [get_triad_permission(allow=cls.allow, deny=cls.deny, default_resource=default_resource)]
class BasicPolicy(Policy):
allo... |
11554178 | from seamless.core import context, cell, StructuredCell
ctx = context(toplevel=True)
ctx.data = cell("mixed")
ctx.sc = StructuredCell(
data=ctx.data
)
data = ctx.sc.handle
data.set(20)
ctx.compute()
print(data.data, ctx.data.value)
data.set(data + 1)
ctx.compute()
print(data.data, ctx.data.value)
print(type(dat... |
11554238 | from django.conf import settings
from django.utils.http import urlencode
def keycloak_logout(request):
logout_url = settings.OIDC_OP_LOGOUT_ENDPOINT
return_to_url = request.build_absolute_uri(settings.LOGOUT_REDIRECT_URL)
return logout_url + '?' + urlencode({'redirect_uri': return_to_url, 'client_id': settings.O... |
11554243 | import torch
import torch.optim as O
import torch.nn as nn
from tasks.snli.third_party import datasets
from tasks.snli.third_party import models
import datetime
from prettytable import PrettyTable
from tasks.snli.third_party.utils import *
from pdb import set_trace
class Evaluate():
def __init__(self, args=... |
11554370 | import gspread
import yaml
class GSheets
def PULL_FROM_GSHEETS(count):
with open('Config/Cloud_Config.yaml', 'r') as f:
doc = yaml.load(f, Loader=yaml.FullLoader)
Sheet = doc["GCloud"]["Sheet"]
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/aut... |
11554396 | import contextlib
import logging
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.models import (FairseqMultiModel, register_model,
register_model_architecture)
from fairseq.models.nat.nonautoregressive_transformer import ... |
11554455 | from ..tweet_sentiment_classifier import Classifier
import numpy as np
import pickle as pkl
import json
import os
import tensorflow_hub as hub
import tensorflow as tf
try:
import bert
FullTokenizer = bert.bert_tokenization.FullTokenizer
except ImportError:
raise ImportError('Issue loading bert-for-tf, ... |
11554515 | import os,rootpath
rootpath.append(pattern='main.py') # add the directory of main.py to PATH
import pprint
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ObjectProperty,DictProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.logger imp... |
11554602 | people = ['Nick', 'Rick', 'Roger', 'Syd']
ages = [23, 24, 23, 21]
for person, age in zip(people, ages):
print(person, age)
|
11554611 | import glob
import json
import os
from notebook.utils import url_path_join as ujoin
from tornado.web import StaticFileHandler, RequestHandler
from . import zotero_oauth
def find_zotero_styles_dir():
pattern = os.path.expanduser('~/.zotero/zotero/*/zotero/styles/')
candidates = glob.glob(pattern)
if not ca... |
11554643 | import torch
import torch.nn as nn
import numpy as np
from models.language import RNNEncoder, ModuleInputAttention
from models.modules import AttendRelationModule, AttendLocationModule, AttendNodeModule
from models.modules import MergeModule, TransferModule, NormAttnMap
class SGReason(nn.Module):
def __init__(s... |
11554653 | from my_lib import Object
import os
from my_lib import Object3
from my_lib import Object2
import sys
from third_party import lib15, lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14
import sys
from __future__ import absolute_import
from third_party import lib3
print("Hey")... |
11554686 | from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow
from tensorflow.python.framework import tensor_util
from tensorflow.core.framework import attr_value_pb2
import sys
from ox.tensorflow.tensorflow_graph import *
import ox.common.IR.graph_pb2 as graph_pb2
from o... |
11554689 | from time import strptime, mktime, gmtime
now = lambda: mktime(gmtime()) // 60
stamp = lambda x: mktime(strptime(x, '%d.%m.%Y %H:%M:%S')) // 60
print(int(now() - stamp('30.11.2017 22:00:58'))) |
11554705 | from __future__ import print_function
# Object Registration
testutil.enable_extensible()
#@ Registration from C++, the parent class
\? testutil
#@ Registration from C++, a test module
\? sample_module_p_y
#@ Registration from C++, register_module function
\? register_module
#@ Registration from C++, register_funct... |
11554784 | import torch
from mmdet.models import DETECTORS
from .two_stage import TwoStage3DDetector
@DETECTORS.register_module()
class BRNet(TwoStage3DDetector):
def __init__(self,
backbone,
neck=None,
rpn_head=None,
roi_head=None,
train_c... |
11554815 | import csv
import random
from staticmap import StaticMap, CircleMarker
m = StaticMap(1000, 900, url_template='http://a.tile.stamen.com/toner/{z}/{x}/{y}.png')
def label_to_color(label):
alpha = 180
return {
'good': (0,153,102,alpha),
'moderate': (255,222,51,alpha),
'unhealthy for sensi... |
11554838 | import boshdata
import struct
import io
BFCAP = 12
BFMASK = (2 ** BFCAP) - 1
def byte2_unpack(numtuple):
"little-endian! receives a tuple like (11, 4095) and return corrosponding bytes"
num = numtuple[0] | (numtuple[1] << 4)
# Packing unsigned short int, should be 2-byte
return struct.pack(b"<H", num... |
11554893 | import torch
from .base import CplxToCplx
from ... import cplx
class CplxDropout(torch.nn.Dropout2d, CplxToCplx):
r"""Complex 1d dropout layer: simultaneous dropout on both real and
imaginary parts.
See torch.nn.Dropout1d for reference on the input dimensions and arguments.
"""
def forward(self,... |
11554901 | import json
from typing import Any, Mapping, Optional
import pulumi_consul as consul
import pulumi
class ConsulServiceDefault(pulumi.ComponentResource):
"""
Create a Service Default type of Consul Config Entry.
This is primarily for setting a non-default protocol
"""
def __init__(
self,... |
11554930 | import torch
import torch.nn as nn
import math
from nets import base
class Net(nn.Module):
def __init__(self, in_channel, out_channel, n_colors=3, n_feats=64, n_resblocks=16, res_scale=0.1, scale=2):
super(Net, self).__init__()
self.conv_input = nn.Conv2d(in_channel, n_feats, kernel_size=3, stride... |
11554938 | fh = open('mbox-short.txt')
#The 'mbox-short.txt' file can be downloaded from the link: https://www.py4e.com/code3/mbox-short.txt
sum = 0
count = 0
for fx in fh:
fx = fx.rstrip()
if not fx.startswith("X-DSPAM-Confidence:") :
continue
fy = fx[19:]
count = count + 1
sum = sum + float(fy)
print ('Average spam confi... |
11554939 | import json
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Optional, Type, TypeVar
from rotkehlchen.accounting.cost_basis import CostBasisInfo
from rotkehlchen.accounting.mixins.event import AccountingEventType
from rotkehlchen.accounting.pnl import PNL
from rotkehlchen.assets.asset i... |
11555001 | import pytest
import numpy as np
import pymaster as nmt
from .utils import normdiff
class BinTester(object):
def __init__(self):
self.nside = 1024
self.lmax = 2000
self.nlb = 4
self.bc = nmt.NmtBin(self.nside, nlb=4, lmax=self.lmax)
ells = np.arange(self.lmax - 4, dtype=int... |
11555060 | import sys
import os
import lmdb # install lmdb by "pip install lmdb"
import cv2
import numpy as np
def checkImageIsValid(imageBin):
if imageBin is None:
return False
imageBuf = np.fromstring(imageBin, dtype=np.uint8)
img = cv2.imdecode(imageBuf, cv2.IMREAD_COLOR)
imgH, imgW = img.shape[0], img... |
11555155 | from enum import Enum
from typing import List
class LINK(Enum):
CONTAINER = '<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'
RESOURCE = '<http://www.w3.org/ns/ldp#Resource>; rel="type"'
def append_slashes_at_end(url) -> str:
if url[-1] != '/':
url += '/'
return url
def remove_slashe... |
11555166 | import tkinter
class EraserWaiterView:
__DESCRIPTIONBORDER = 10
__DESCRIPTIONROW = 0
__BUTTONPADDING = 5
__NAMECOLUMN = 1
def __center(self):
self.__root.withdraw()
self.__root.update_idletasks()
x = (self.__root.winfo_screenwidth() - self.__root.winfo_reqwidth()) / 2
... |
11555248 | from numpy import zeros, float64, int64, array, random
import ctypes
import _ctypes
from math import ceil, floor
import sys
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
def c_char_ptr(x):
return x.ctypes.data_as(ctypes.POINTER(ctypes.c_char))
def c_long_ptr(x):
return x.ctypes.da... |
11555252 | from ...suggestion.algorithm.base_hyperopt_algorithm import BaseHyperoptAlgorithm
class SimulateAnnealAlgorithm(BaseHyperoptAlgorithm):
"""
The implementation is based on https://github.com/tobegit3hub/advisor
Get the new suggested trials with simulate anneal algorithm.
"""
def __init__(self):
... |
11555292 | expected_output = {
"ospf3-neighbor-information": {
"ospf3-neighbor": [
{
"activity-timer": "34",
"bdr-id": "0.0.0.0",
"dr-id": "0.0.0.0",
"interface-name": "ge-0/0/0.0",
"neighbor-address": "fe80::250:56ff:fe8d:53c0... |
11555294 | import numpy as np
import scipy.optimize as sciopt
def gaussian(x, *p):
A, mu, sigma = p
return A*np.exp(-(x-mu)**2/(2.*sigma**2))
def fit_gaussian(x, y, z_2d, save_fits=False):
z = z_2d
max_idx = np.unravel_index(z.argmax(), z.shape)
max_row = max_idx[0] - 1
max_col = max_idx[1] - 1
z_m... |
11555319 | import asyncio
import logging
import signal
import typing as t
import arrow
import discord
from aiohttp import ClientSession
from discord import Activity, AllowedMentions, Intents
from discord.client import _cleanup_loop
from discord.ext import commands
from modmail.config import CONFIG
from modmail.log import Modmai... |
11555363 | import discord
import logging
from discord.ext import commands
log = logging.getLogger('daijobuudes.moderation')
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
# Purge messages
@commands.command()
@commands.has_permissions(manage_channels=True)
async d... |
11555372 | import unittest
from soap.datatype import int_type, IntegerArrayType
from soap.expression import (
Variable, BinaryArithExpr, BinaryBoolExpr, operators, UnaryArithExpr,
SelectExpr, FixExpr, AccessExpr, UpdateExpr, Subscript,
)
from soap.semantics.error import IntegerInterval
from soap.semantics.functions.label... |
11555381 | from django import template
from bs4 import BeautifulSoup
register = template.Library()
@register.tag(name='activehref')
def do_active_href(parser, token):
nodelist = parser.parse(('endactivehref',))
parser.delete_first_token()
return ActiveHref(nodelist)
class ActiveHref(template.Node):
"""
Thi... |
11555385 | import socket
import os
from stanfordnlp.server import CoreNLPClient
def is_port_occupied(ip='127.0.0.1', port=80):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False
def get_corenlp_client(... |
11555437 | import numpy as np
import pandas as pd
import pytest
from xgboost import XGBClassifier
from trelawney.lime_explainer import LimeExplainer
def _do_explainer_test(explainer, data_to_test=None, col_real='real', col_fake='fake'):
data_to_test = data_to_test if data_to_test is not None else pd.DataFrame([[5, 0.1], [... |
11555461 | import re
import operator
import string
import numpy as np
import spacy
from nltk.tokenize import word_tokenize as nltk_word_tokenize
from nltk.tokenize import sent_tokenize as nltk_sent_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import *
from nltk.stem import WordNetLemmatizer
stop_words = set(st... |
11555504 | from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.player import Player
from pypokerengine.engine.seats import Seats
class SeatsTest(BaseUnitTest):
def setUp(self):
self.seats = Seats()
self.p1 = Player("uuid1", 100)
self.p2 = Player("uuid2", 100)
self.p3 = Player("uuid3", 100)
... |
11555510 | import argparse
parser = argparse.ArgumentParser(description='Disfluency Detection')
parser.add_argument('-file', type=str, default='swbdIO/test.txt')
parser.add_argument('-pred_file', type=str, default='swbdIO/test.txt')
parser.add_argument('-out_file', type=str, default='swbdIO/test.txt')
args = parser.parse_args()
... |
11555523 | import tensorflow as tf
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal
from tefla.core import metrics
@pytest.fixture(autouse=True)
def _reset_graph():
tf.reset_default_graph()
def test_kappav2_op():
kappav2 = metrics.KappaV2()
labels = tf.placeholder(shape=(32, ), name=... |
11555538 | import math
import glob
import os
import uuid
import itertools
import pandas as pd
import numpy as np
import datetime as dt
class GSTools(object):
@staticmethod
def load_csv_files(dir_str):
'''
This function reads all csv from the given directory, stores them in a dictionary and returns it.
... |
11555545 | import skimage.io as sio
import numpy as np
import torch
from torchvision import transforms as trn
from torch.autograd import Variable
from skimage.transform import resize
import json
import os
import os.path as osp
import pickle as pkl
import pandas as pd
def set_gpu_devices(gpu_id):
gpu = ''
if gpu_id != -1:... |
11555575 | import re
from rx import Observable
from rx.subjects import Subject
class TransactionValidator:
def __init__(self):
self._error_stream = Subject()
self._price_stream = Subject()
self._symbol_stream = Subject()
self.latest_valid_order = None
def next_error(self, field, error_te... |
11555577 | import os
import time
import copy
import torch
import numpy as np
from common import flatten_lists
from common.utils import dotdict
from common.sc2_utils import _update_window, warfare, save_results
from agents.grprop import GRProp
class Runner:
def __init__(self, envs, agent, ilp, sc2_filewriter, config, args,... |
11555610 | import sys
from ansible.errors import AnsibleError
from ansible.parsing.vault import VaultLib
def load_vault_key(key_path):
key = None
with open(key_path, 'r') as fp:
key = fp.read().strip()
if key is None:
raise Exception('Could not load key or it had zero content')
return VaultLib... |
11555613 | import pytest
from unittest.mock import patch
from flask_mailman import EmailMessage
from resources.email import Email
@pytest.mark.usefixtures("empty_test_db")
class TesttEmail:
@patch.object(EmailMessage, "send")
def test_reset_password_msg(self, send_mail_msg, create_user):
with patch.object(EmailM... |
11555614 | import pytest
from remote.configuration.classic import CONFIG_FILE_NAME, ClassicConfigurationMedium
from remote.configuration.discovery import get_configuration_medium, resolve_workspace_root
def test_resolve_workspace_root(tmp_path):
work_dir = tmp_path / "foo" / "bar"
work_dir.mkdir(parents=True)
(tmp_... |
11555650 | import FWCore.ParameterSet.Config as cms
#
# produce stGenEvent with all necessary ingredients
#
from TopQuarkAnalysis.TopEventProducers.producers.TopInitSubset_cfi import *
from TopQuarkAnalysis.TopEventProducers.producers.TopDecaySubset_cfi import *
from TopQuarkAnalysis.TopEventProducers.producers.StGenEvtProducer_... |
11555651 | from flask import render_template, request, flash
from nanobrok.models import DeviceInfo, User
import uuid, jwt
from dynaconf import settings
from nanobrok.ext.database import db
from flask_login import login_required
# This file is part of the Nanobrok Open Source Project.
# nanobrok is licensed under the Apache 2.0... |
11555680 | from __future__ import unicode_literals
import re
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from djblets.db.fields import JSONField
from reviewboard.attachments.models import FileAtta... |
11555694 | from inspr import *
import sys
PING_INPUT_CHANNEL = "pinginput"
PING_OUTPUT_CHANNEL = "pingoutput"
def main():
client = Client()
msg = "Ping!"
@client.handle_channel(PING_INPUT_CHANNEL)
def read_pong_and_send_ping(data):
if data == 'Pong!':
print(data, file=sys.stderr)
el... |
11555720 | from skyfield.data import hipparcos
from skyfield.api import Star, load
import numpy as np
import erfa
HEADER = '''############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ##... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.