max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 7 115 | max_stars_count int64 101 368k | id stringlengths 2 8 | content stringlengths 6 1.03M |
|---|---|---|---|---|
libcity/data/batch.py | moghadas76/test_bigcity | 221 | 11113707 | <reponame>moghadas76/test_bigcity
import torch
import numpy as np
class Batch(object):
def __init__(self, feature_name, pad_item=None, pad_max_len=None):
"""Summary of class here
Args:
feature_name (dict): key is the corresponding feature's name, and
the value is the ... |
sdk/cognitiveservices/azure-cognitiveservices-vision-contentmoderator/azure/cognitiveservices/vision/contentmoderator/operations/__init__.py | rsdoherty/azure-sdk-for-python | 2,728 | 11113735 | <filename>sdk/cognitiveservices/azure-cognitiveservices-vision-contentmoderator/azure/cognitiveservices/vision/contentmoderator/operations/__init__.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under ... |
c++/paddle_infer_demo/test_yolov3.py | windstamp/Paddle-Inference-Demo | 115 | 11113756 | <reponame>windstamp/Paddle-Inference-Demo<gh_stars>100-1000
import numpy as np
import argparse
import time
import os
from paddle.inference import Config
from paddle.inference import create_predictor
def init_predictor(args):
config = Config()
if args.model_dir == "":
config.set_model(args.model_file,... |
package_control/downloaders/basic_auth_downloader.py | evandrocoan/package_control | 3,373 | 11113762 | <reponame>evandrocoan/package_control<filename>package_control/downloaders/basic_auth_downloader.py
import base64
try:
# Python 3
from urllib.parse import urlparse
except (ImportError):
# Python 2
from urlparse import urlparse
class BasicAuthDownloader(object):
"""
A base for downloaders to ... |
problems/first-greater-number/first-greater-number.py | vidyadeepa/the-coding-interview | 1,571 | 11113812 | <gh_stars>1000+
def first_greater(l, n):
return next((i for i in l if i > n), None)
print first_greater([2, 10,5,6,80], 6)
print first_greater([2, 10,5,6,80], 20)
print first_greater([2, 10,5,6,80], 100)
|
tools/autoconfig.py | joyzainzy/xiaomi_miot_raw | 1,294 | 11113842 | <filename>tools/autoconfig.py<gh_stars>1000+
import requests
url_all = 'http://miot-spec.org/miot-spec-v2/instances?status=all'
url_spec = 'http://miot-spec.org/miot-spec-v2/instance'
def deviceinfo(j):
print(f"设备描述:{j['description']}")
print("设备属性:")
for s in j['services']:
print(f"\nsiid {s['ii... |
tests/tools/test_flake8_works.py | asdfCYBER/nbQA | 457 | 11113909 | """Check :code:`flake8` works as intended."""
import os
from textwrap import dedent
from typing import TYPE_CHECKING
import pytest
from nbqa.__main__ import main
if TYPE_CHECKING:
from _pytest.capture import CaptureFixture
@pytest.mark.parametrize(
"path_0, path_1, path_2",
(
(
os.... |
front/models.py | llazzaro/django-front | 135 | 11113951 | <reponame>llazzaro/django-front<gh_stars>100-1000
from django.db import models
from django.core.cache import cache
from django.dispatch import receiver
from django.db.models.signals import post_save
import hashlib
import six
class Placeholder(models.Model):
key = models.CharField(max_length=40, primary_key=True, ... |
spockbot/mcp/mcpacket.py | SpockBotMC/SpockBot | 171 | 11113966 | try:
basestring
except NameError:
basestring = str
import copy
import logging
import zlib
from time import gmtime, strftime
from spockbot.mcp import datautils, proto
from spockbot.mcp.bbuff import BoundBuffer, BufferUnderflowException
from spockbot.mcp.extensions import hashed_extensions
from spockbot.mcp.pro... |
data_preparation/move_valid_files.py | Dieg0Alejandr0/EquiBind | 128 | 11113977 | <filename>data_preparation/move_valid_files.py
import os
from shutil import copyfile
from tqdm import tqdm
from commons.utils import read_strings_from_txt
data_path = '../data/PDBBind'
overwrite = False
names = sorted(os.listdir(data_path))
invalid_names = read_strings_from_txt('select_chains.log')
valid_names = li... |
DQM/L1TMonitor/python/L1GtHwValidation_cff.py | ckamtsikis/cmssw | 852 | 11113978 | import FWCore.ParameterSet.Config as cms
from DQM.L1TMonitor.l1GtHwValidation_cfi import *
from DQM.L1TMonitor.l1Stage1GtHwValidation_cfi import *
|
evdev/__init__.py | alexbprofit/python-evdev | 231 | 11113992 | #--------------------------------------------------------------------------
# Gather everything into a single, convenient namespace.
#--------------------------------------------------------------------------
from evdev.device import DeviceInfo, InputDevice, AbsInfo, EvdevError
from evdev.events import InputEvent, Key... |
caffe2/python/operator_test/rms_norm_op_test.py | Hacky-DH/pytorch | 60,067 | 11113997 |
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
import unittest
class TestRMSNormOp(hu.HypothesisTestCase):
@given(
M=st.integers(0, 8),
N=st.integers(1, 16),
eps... |
examples/applications/restapi/handlers.py | electrumsv/electrumsv | 136 | 11114041 | <gh_stars>100-1000
# TODO(REST-API-Refactoring) Notes follow.
# - All these functions should be moved out of the example and into the code base proper. We should
# make a very simple example that extends it as a daemon app.
# - Remove the variables like VERSION, NETWORK, .... a good idea in theory but they overcompli... |
alipay/aop/api/response/AlipayOpenMiniTemplatemessageUsertemplateApplyResponse.py | snowxmas/alipay-sdk-python-all | 213 | 11114055 | <filename>alipay/aop/api/response/AlipayOpenMiniTemplatemessageUsertemplateApplyResponse.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOpenMiniTemplatemessageUsertemplateApplyResponse(AlipayResponse):
def __init__(self)... |
nitorch/transforms.py | ArneBinder/Pytorch-LRP | 117 | 11114068 | <reponame>ArneBinder/Pytorch-LRP
import numpy as np
import numbers
import torch
from scipy.ndimage.interpolation import rotate
from scipy.ndimage.interpolation import zoom
def normalize_float(x, min=-1):
"""
Function that performs min-max normalization on a `numpy.ndarray`
matrix.
"""
if min ==... |
demo/demo/app/models.py | HiveTechies/django-star-ratings | 296 | 11114076 | from __future__ import unicode_literals
from django.db import models
class Foo(models.Model):
bar = models.CharField(max_length=100)
|
homeassistant/components/workday/__init__.py | domwillcode/home-assistant | 30,023 | 11114093 | <filename>homeassistant/components/workday/__init__.py
"""Sensor to indicate whether the current day is a workday."""
|
ui/UpgradeDownloader.py | s1kx/BitcoinArmory | 410 | 11114096 | <gh_stars>100-1000
################################################################################
# #
# Copyright (C) 2011-2015, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License ... |
fastmri_recon/data/scripts/multicoil_nc_tf_records_generation.py | samiulshuvo/fastmri-reproducible-benchmark | 105 | 11114108 | from pathlib import Path
import tensorflow as tf
from tfkbnufft.kbnufft import KbNufftModule
from tfkbnufft import kbnufft_forward, kbnufft_adjoint
from tfkbnufft.mri.dcomp_calc import calculate_density_compensator
from tqdm import tqdm
from fastmri_recon.config import FASTMRI_DATA_DIR
from fastmri_recon.data.utils.c... |
toy/mdn.py | mehrdad-shokri/WorldModels-1 | 149 | 11114130 | import matplotlib.pyplot as plt
plt.switch_backend('agg')
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import training, datasets, iterators, report
from chainer.training import extensions
import numpy as np
class MDN(chainer.Chain):
def __init__(self, hidden_dim, output_d... |
toad/preprocessing/partition.py | Padfoot-ted/toad | 325 | 11114170 | import numpy as np
import pandas as pd
class Partition:
def partition(self, data):
"""partition data
Args:
data (DataFrame): dataframe
Returns:
iterator -> ndarray[bool]: mask of partition data
iterator -> str: suffix string of current partitio... |
convokit/model/corpusComponent.py | CornellNLP/Cornell-Conversational-Analysis-Toolkit | 371 | 11114227 | <filename>convokit/model/corpusComponent.py
from .convoKitMeta import ConvoKitMeta
from convokit.util import warn, deprecation
from typing import List, Optional
class CorpusComponent:
def __init__(self, obj_type: str, owner=None, id=None, vectors: List[str]=None, meta=None):
self.obj_type = obj_type # u... |
samsungctl/upnp/UPNP_Device/instance_singleton.py | p3g4asus/samsungctl | 135 | 11114265 | # -*- coding: utf-8 -*-
class InstanceSingleton(type):
_objects = {}
def __call__(cls, id, *args):
if id not in InstanceSingleton._objects:
InstanceSingleton._objects[id] = (
super(InstanceSingleton, cls).__call__(id, *args)
)
return InstanceSingleton... |
openrec/tf1/legacy/modules/__init__.py | pbaiz/openrec | 399 | 11114291 | from openrec.tf1.legacy.modules.module import Module
|
labs/notebooks/reinforcement_learning/RL.py | mtreviso/lxmls-toolkit | 183 | 11114368 | <reponame>mtreviso/lxmls-toolkit
from IPython import embed
# Load Part-of-Speech data
from lxmls.readers.pos_corpus import PostagCorpusData
data = PostagCorpusData()
print(data.input_size)
print(data.output_size)
print(data.maxL)
import numpy as np
import time
batch_size = 1
# Get batch iterators for train and tes... |
test/vectors_example.py | shardros/autopep8 | 3,459 | 11114381 | <gh_stars>1000+
# vectors - a simple vector, complex, quaternion, and 4d matrix math module
'''
http://www.halley.cc/code/python/vectors.py
A simple vector, complex, quaternion, and 4d matrix math module.
ABSTRACT
This module gives a simple way of doing lightweight 2D, 3D or other
vector math tasks without the heav... |
ikbtbasics/ik_classes.py | uw-biorobotics/IKBT | 129 | 11114426 | #!/usr/bin/python
#
# Inverse Kinematics Classes
#
# Copyright 2017 University of Washington
# Developed by <NAME> and <NAME>
# BioRobotics Lab, University of Washington
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met... |
packages/opal-common/opal_common/fetcher/engine/fetch_worker.py | permitio/opal | 106 | 11114428 | import asyncio
from typing import Coroutine
from ..events import FetchEvent
from ..fetcher_register import FetcherRegister
from ..logger import get_logger
from .base_fetching_engine import BaseFetchingEngine
logger = get_logger("fetch_worker")
async def fetch_worker(queue: asyncio.Queue, engine):
"""The worker ... |
testrunner/app_level_tests.py | nanjekyejoannah/pypy | 381 | 11114430 | <filename>testrunner/app_level_tests.py
#!/usr/bin/env python
"""
This is what the buildbot runs to execute the app-level tests
on top of pypy-c.
"""
import sys, os
import subprocess
rootdir = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
os.environ['PYTHONPATH'] = rootdir
os.environ['PYTEST_PLUGINS'... |
static.py | wschae/wschae.github.io | 191 | 11114436 | #!/usr/bin/env python
"""static - A stupidly simple WSGI way to serve static (or mixed) content.
(See the docstrings of the various functions and classes.)
Copyright (C) 2006-2009 <NAME> - http://lukearno.com/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser G... |
designate-8.0.0/designate/storage/impl_sqlalchemy/migrate_repo/versions/083_change_managed_column_types.py | scottwedge/OpenStack-Stein | 145 | 11114511 | <reponame>scottwedge/OpenStack-Stein
# Copyright 2016 Hewlett Packard Enterprise Development Company LP
#
# Author: <NAME> <<EMAIL>>
#
# 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
#
# h... |
fasterai/sparse/sparsify_callback.py | nathanhubens/fasterai | 191 | 11114515 | <filename>fasterai/sparse/sparsify_callback.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02_sparsify_callback.ipynb (unless otherwise specified).
__all__ = ['SparsifyCallback']
# Cell
from fastai.vision.all import *
from fastai.callback.all import *
from .sparsifier import *
from .criteria import *
import torc... |
PythonToolbox/quantconnect/Result.py | BlackBoxAM/Lean | 6,580 | 11114537 | <reponame>BlackBoxAM/Lean<filename>PythonToolbox/quantconnect/Result.py
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file exc... |
myia/operations/prim_shape.py | strint/myia | 222 | 11114543 | <reponame>strint/myia
"""Definitions for the primitive `shape`."""
from .. import xtype
from ..lib import (
TYPE,
VALUE,
AbstractArray,
AbstractScalar,
AbstractTuple,
bprop_to_grad_transform,
force_pending,
standard_prim,
)
from ..operations import zeros_like
from . import primitives as... |
koku/masu/test/external/downloader/azure/test_azure_services.py | rubik-ai/koku | 157 | 11114559 | <reponame>rubik-ai/koku
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Test the AzureService object."""
from datetime import datetime
from unittest.mock import Mock
from unittest.mock import patch
from unittest.mock import PropertyMock
from adal.adal_error import AdalError
from azure.common... |
examples/language-model/make_data.py | greedyuser/kur | 867 | 11114616 | """
Copyright 2016 Deepgram
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 applicable law or agreed to in writing, software
distri... |
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/testing/loader.py | jeikabu/lumberyard | 1,738 | 11114623 | <filename>dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/testing/loader.py
import numba.unittest_support as unittest
from unittest import loader, case
from os.path import isdir, isfile, join, dirname, basename
class TestLoader(loader.TestLoader):
def __init__(self, topleveldir=None):
super(TestL... |
tests/nnapi/specs/V1_2/sin_1D_float_nnfw.mod.py | periannath/ONE | 255 | 11114640 | # model
model = Model()
i1 = Input("op1", "TENSOR_FLOAT32", "{4}") #A vector of inputs
i2 = Output("op2", "TENSOR_FLOAT32", "{4}") #A vector of outputs
model = model.Operation("SIN", i1).To(i2)
# Example 1. Input in operand 0,
input0 = {i1: # input 0
[2.0, 90.0, 1.0, 0.012]}
output0 = {i2: # output 0
... |
Algo and DSA/LeetCode-Solutions-master/Python/insufficient-nodes-in-root-to-leaf-paths.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 11114661 | <gh_stars>1000+
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sufficientSubset(self, root, limit):
"""
:type root: TreeNode
... |
visualization/evanescent/createsample.py | mika314/simuleios | 197 | 11114687 | #-------------createsample.py--------------------------------------------------#
#
# create sample.py
#
# Purpose: To create sample blender data for testing voxel stuff with.
#
#------------------------------------------------------------------------------#
#import bpy
import numpy as np
import struct
# ... |
transistor/browsers/splash_browser.py | awesome-archive/transistor | 232 | 11114781 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
transistor.browsers.splash_browser
~~~~~~~~~~~~
This module implements the SplashBrowser class.
Splash browser is a subclass of mechanicalsoup.StatefulBrowser which
adds a few new methods and overrides most existing methods to make it work
with Splash and/or Splash + Craw... |
chips/compiler/instruction_utils.py | dillonhuff/Chips-2.0 | 221 | 11114827 | __author__ = "<NAME>"
__copyright__ = "Copyright (C) 2012, <NAME>"
__version__ = "0.1"
from register_map import *
def push(trace, instructions, reg):
"""Push the content of *reg(* onto the stack"""
instructions.append({"trace": trace, "op": "push", "reg": reg})
return instructions
def pop(trace, instru... |
vnpy/gateway/bitmex/__init__.py | funrunskypalace/vnpy | 19,529 | 11114832 | from .bitmex_gateway import BitmexGateway
|
音频处理/音频尾部处理.py | liusongtao99/tools_python | 130 | 11114876 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: xag
@license: Apache Licence
@contact: <EMAIL>
@site: http://www.xingag.top
@software: PyCharm
@file: 尾部处理.py
@time: 2021-01-02 09:59
@description:TODO
"""
from pydub import AudioSegment
from pydub.playback import play
video_path = './... |
tests/test_sequence_tagger.py | ParikhKadam/flair | 7,539 | 11114878 | <filename>tests/test_sequence_tagger.py
import pytest
from torch.optim import SGD
from torch.optim.adam import Adam
import flair.datasets
from flair.data import MultiCorpus, Sentence
from flair.embeddings import FlairEmbeddings, WordEmbeddings
from flair.models import SequenceTagger
from flair.trainers import ModelTra... |
transformer_courses/BERT_distillation/PaddleSlim-develop/paddleslim/prune/idx_selector.py | wwhio/awesome-DeepLearning | 1,150 | 11114880 | <filename>transformer_courses/BERT_distillation/PaddleSlim-develop/paddleslim/prune/idx_selector.py
"""Define some functions to sort substructures of parameter by importance.
"""
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may ... |
service/argo/rest_api.py | simpsonw/atmosphere | 197 | 11114891 | <reponame>simpsonw/atmosphere
"""
Client to access Argo REST API
"""
import json
import requests
from threepio import celery_logger as logger
from service.argo.exception import ResponseNotJSON
try:
from json import JSONDecodeError
except ImportError:
# python2 does not has JSONDecodeError
JSONDecodeError ... |
ochre/select_vudnc_files.py | KBNLresearch/ochre | 113 | 11114898 | #!/usr/bin/env python
import click
import os
import json
from nlppln.utils import cwl_file
@click.command()
@click.argument('dir_in', type=click.Path(exists=True))
def command(dir_in):
files_out = []
newspapers = ['ad1951', 'nrc1950', 't1950', 'tr1950', 'vk1951']
for np in newspapers:
path = os... |
setup.py | DuncanBetts/flask-redis | 409 | 11114906 | import codecs
import os
import re
from setuptools import find_packages, setup
NAME = "flask-redis"
KEYWORDS = ["flask", "redis"]
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Operating System :: OS Ind... |
test/package/test_trace_dep/__init__.py | Hacky-DH/pytorch | 60,067 | 11114935 | <filename>test/package/test_trace_dep/__init__.py<gh_stars>1000+
import torch
import yaml
class SumMod(torch.nn.Module):
def forward(self, inp):
return torch.sum(inp)
|
src/genie/libs/parser/ios/show_vlan.py | nujo/genieparser | 204 | 11114948 | <reponame>nujo/genieparser
"""
IOS Parsers
"""
# genieparser
from genie.libs.parser.iosxe.show_vlan import ShowVlan as ShowVlan_iosxe, \
ShowVlanMtu as ShowVlanMtu_iosxe,\
ShowVlanAccessMap as ShowVlanAccessMap_iosxe,\
... |
gengine/maintenance/scripts/generate_revision.py | greck2908/gamification-engine | 347 | 11114972 | # -*- coding: utf-8 -*-
import sys
import os
import pyramid_dogpile_cache
from pyramid.config import Configurator
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from sqlalchemy import engine_from_config
def usage(argv):
cmd = os.path.basename(... |
mayan/apps/tags/__init__.py | eshbeata/open-paperless | 2,743 | 11115003 | from __future__ import unicode_literals
default_app_config = 'tags.apps.TagsApp'
|
InnerEye/Common/resource_monitor.py | JacopoTeneggi/InnerEye-DeepLearning | 402 | 11115019 | # ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
src/python/k4a/tests/test_functional_api_azurekinect.py | seanyen/Azure-Kinect-Sensor-SDK | 1,120 | 11115085 | '''
test_device_azurekinect.py
Tests for the Device class for Azure Kinect device.
Copyright (C) Microsoft Corporation. All rights reserved.
'''
import unittest
import copy
from time import sleep
import numpy as np
import k4a
import test_config
def k4a_device_set_and_get_color_control(
device:k4a.Device,
... |
parse_text_http_headers.py | DazEB2/SimplePyScripts | 117 | 11115110 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import re
from typing import Dict
HTTP_HEADER_PATTERN = re.compile(r'([\w-]+): (.*)', flags=re.IGNORECASE)
def parse(text: str) -> Dict[str, str]:
return dict(HTTP_HEADER_PATTERN.findall(text))
if __name__ == '__main__':
text_http_h... |
tests/cpydiff/modules_array_subscrstep.py | sebastien-riou/micropython | 13,648 | 11115164 | <reponame>sebastien-riou/micropython<gh_stars>1000+
"""
categories: Modules,array
description: Subscript with step != 1 is not yet implemented
cause: Unknown
workaround: Unknown
"""
import array
a = array.array("b", (1, 2, 3))
print(a[3:2:2])
|
tests/algorithms/test_rvea.py | jarreguit/pymoo | 762 | 11115172 | <filename>tests/algorithms/test_rvea.py<gh_stars>100-1000
import numpy as np
from pymoo.algorithms.moo.rvea import APDSurvival, RVEA
from pymoo.factory import DTLZ2
from pymoo.core.population import Population
from tests.util import path_to_test_resource
def test_survival():
problem = DTLZ2(n_obj=3)
for k i... |
adaptdl/adaptdl/conftest.py | jessezbj/adaptdl | 294 | 11115228 | # Copyright 2020 Petuum, Inc. All Rights Reserved.
#
# 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 applicable law or... |
esphome/components/am43/cover/__init__.py | OttoWinter/esphomeyaml | 249 | 11115229 | <reponame>OttoWinter/esphomeyaml<gh_stars>100-1000
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import cover, ble_client
from esphome.const import CONF_ID, CONF_PIN
CODEOWNERS = ["@buxtronix"]
DEPENDENCIES = ["ble_client"]
AUTO_LOAD = ["am43", "sensor"]
CONF_INVERT_POSIT... |
allennlp/modules/transformer/layer_norm.py | MSLars/allennlp | 11,433 | 11115245 | import torch
from allennlp.modules.transformer.transformer_module import TransformerModule
class LayerNorm(torch.nn.LayerNorm, TransformerModule):
_pretrained_mapping = {"gamma": "weight", "beta": "bias"}
|
libcity/data/dataset/eta_encoder/abstract_eta_encoder.py | moghadas76/test_bigcity | 221 | 11115258 | from logging import getLogger
class AbstractETAEncoder(object):
"""ETA Encoder
ETA Encoder is used to encode the spatiotemporal information in trajectory.
We abstract the encoding operation from the Dataset Module to facilitate developers
to achive more flexible and diverse trajectory representation ... |
Chapter04/DeepLearningDemo.py | Tanishadel/Mastering-Machine-Learning-for-Penetration-Testing | 241 | 11115327 | from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
seed = 7
numpy.random.seed(seed)
(X_train, y_train), (X_test, y_test) = mnist.load_data()
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train / 255
X_test = X_test / 255... |
pysb/examples/tutorial_c.py | FFroehlich/pysb | 105 | 11115331 | from pysb import *
Model()
Monomer('Raf', ['s', 'k'], {'s': ['u', 'p']})
Monomer('MEK', ['s218', 's222', 'k'], {'s218': ['u', 'p'], 's222': ['u', 'p']})
Parameter('kf', 1e-5)
Parameter('Raf_0', 7e4)
Parameter('MEK_0', 3e6)
|
cycles/utils/setMat_crackedCeramic.py | HTDerekLiu/BlenderToolbox | 208 | 11115335 | # Copyright 2020 <NAME>
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... |
deepFEPE/models/DeepFNetSampleLoss.py | KuangHaofei/pytorch-deepFEPE | 112 | 11115364 | """ DeepF for sample loss
Keep but not tested (you-yi on 07/13/2020)
Authors: <NAME>, <NAME>
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable, Function
from torch.nn.functional import grid_sample
import numpy as np
import cv2
import dsac_tools.utils_F as ut... |
pyez/gather_facts.py | rsmekala/junosautomation | 117 | 11115401 | <reponame>rsmekala/junosautomation
from jnpr.junos import Device
from pprint import pprint
dev = Device(host='xxxx', user='demo', password='<PASSWORD>')
dev.open()
pprint (dev.facts)
# As dev.facts is a dictionary, we can fetch any specific data
print dev.facts['serialnumber']
print dev.facts['version']
print dev.fa... |
data/transcoder_evaluation_gfg/python/COUNT_PALINDROME_SUB_STRINGS_STRING.py | mxl1n/CodeGen | 241 | 11115417 | # Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( str , n ) :
dp = [ [ 0 for x in range ( n ) ] for y in range ( n ) ]
P = [ [ False for x in range ( n ) ] f... |
dnnweaver2/scalar/ops.py | ZixuanJiang/dnnweaver2 | 159 | 11115421 | <filename>dnnweaver2/scalar/ops.py
from dnnweaver2.scalar.dtypes import Dtype
class ScalarOp(object):
def __init__(self, op_str, dtype):
self.op_str = op_str
self.dtype = dtype
def __str__(self):
if isinstance(self.dtype, Dtype):
return '{}({})'.format(self.op_str, self.dtyp... |
cosrlib/sources/webarchive.py | commonsearch/cosr-back | 141 | 11115436 | <reponame>commonsearch/cosr-back<filename>cosrlib/sources/webarchive.py
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import tempfile
from cosrlib.sources import Source
from cosrlib.url import URL
import warc
from gzipstream import GzipStreamFile
try:
from http_parse... |
demo/tracking/deep_sort.py | shachargluska/centerpose | 245 | 11115471 | <gh_stars>100-1000
import time
import numpy as np
from .feature_extractor import Extractor
from .sort.detection import Detection
from .sort.nn_matching import NearestNeighborDistanceMetric
from .sort.preprocessing import non_max_suppression
from .sort.tracker import Tracker
class DeepSort(object):
d... |
explorer/python-api/explorer_python_api/app.py | johnnynetgevity/cardano-sl | 4,174 | 11115482 | <reponame>johnnynetgevity/cardano-sl<gh_stars>1000+
import atexit
import json
import logging
import os
import records
import requests
import pytz
import time
from flask import Flask, request
from flask.logging import default_handler
from prometheus_flask_exporter import PrometheusMetrics
from prometheus_client import C... |
python-gurobi model/Netflow problem.py | woruoweikunlun/Python-Gurobi | 162 | 11115497 | <reponame>woruoweikunlun/Python-Gurobi
#!/usr/bin/python
# Copyright 2016, Gurobi Optimization, Inc.
# Solve a multi-commodity flow problem. Two products ('Pencils' and 'Pens')
# are produced in 2 cities ('Detroit' and 'Denver') and must be sent to
# warehouses in 3 cities ('Boston', 'New York', and 'Seattle') to
# ... |
lvsr/ops.py | dendisuhubdy/attention-lvcsr | 295 | 11115600 | from __future__ import print_function
import math
try:
import fst
except ImportError:
print("No PyFST module, trying to work without it. If you want to run the "
"language model, please install openfst and PyFST")
import numpy
import theano
import itertools
from theano import tensor, Op
from theano.gr... |
pyobjus/consts/__init__.py | zenvarlab/pyobjus | 114 | 11115656 | <gh_stars>100-1000
'''
Tools to allow reading const ObjC values. See pyobjus.consts.corebluetooth for
an example of usage.
Under normal circumstances, this is just a convoluted way to generate a class
with attributes containing the default values.
But with 'PYOBJUS_DEV' in the environment, this will instead automatic... |
autofixture_tests/urls.py | jayvdb/django-autofixture | 332 | 11115674 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
from django.http import HttpResponse
def handle404(request):
return HttpResponse('404')
def handle500(request):
return HttpResponse('500')
handler404 = 'autofixture_tests.urls.handle404'
handler500 = 'autofixture_tests.urls.handle500'
urlpatterns = [
]
|
adalink/errors.py | pomplesiegel/Adafruit_Adalink | 119 | 11115704 | <filename>adalink/errors.py<gh_stars>100-1000
# adalink Errors
#
# Common errors and exceptions raised by adalink.
#
# Author: <NAME>
class AdaLinkError(Exception):
"""Class to represent an error from AdaLink. Base-class for all AdaLink
errors.
"""
pass
|
autogl/module/nas/estimator/__init__.py | THUMNLab/AutoGL | 824 | 11115740 | <filename>autogl/module/nas/estimator/__init__.py
import importlib
import os
from .base import BaseEstimator
NAS_ESTIMATOR_DICT = {}
def register_nas_estimator(name):
def register_nas_estimator_cls(cls):
if name in NAS_ESTIMATOR_DICT:
raise ValueError(
"Cannot register duplica... |
tests/test_domaintools.py | target/huntlib | 116 | 11115759 | #!/usr/bin/env python
import os
import unittest
from multiprocessing import cpu_count
from unittest import TestCase
from huntlib.domaintools import DomainTools
import pandas as pd
import numpy as np
class TestDomainTools(TestCase):
_handle = None
_nonexistent_domain = "ladfownlasdfabwhxpaowanlsuwjn.com"
... |
unittest_reinvent/running_modes/lib_invent_tests/logger_tests/__init__.py | lilleswing/Reinvent-1 | 183 | 11115772 | <reponame>lilleswing/Reinvent-1
from unittest_reinvent.running_modes.lib_invent_tests.logger_tests.test_reinforcement_logger import \
TestReinforcementLogger |
test/test_khan_dl.py | rand-net/khan-dl | 835 | 11115779 | import unittest
import youtube_dl
import sys
sys.path.append("../khan_dl")
from khan_dl.khan_dl import *
class TestKhanDL(unittest.TestCase):
def test_get_courses(self):
print("test_get_courses")
khan_dl = KhanDL()
courses, courses_url = khan_dl.get_courses("https://www.khanacademy.org/ma... |
boto3_type_annotations_with_docs/boto3_type_annotations/elastictranscoder/waiter.py | cowboygneox/boto3_type_annotations | 119 | 11115791 | from typing import Dict
from botocore.waiter import Waiter
class JobComplete(Waiter):
def wait(self, Id: str, WaiterConfig: Dict = None):
"""
Polls :py:meth:`ElasticTranscoder.Client.read_job` every 30 seconds until a successful state is reached. An error is returned after 120 failed checks.
... |
blacksheep/server/authentication/jwt.py | q0w/BlackSheep | 420 | 11115823 | from typing import Optional, Sequence
from guardpost.asynchronous.authentication import AuthenticationHandler
from guardpost.authentication import Identity
from guardpost.jwks import KeysProvider
from guardpost.jwts import InvalidAccessToken, JWTValidator
from jwt.exceptions import InvalidTokenError
from blacksheep.b... |
querybook/server/logic/result_store.py | shivammmmm/querybook | 1,144 | 11115832 | <filename>querybook/server/logic/result_store.py
import csv
from io import StringIO
import sys
from typing import List
from datetime import datetime
from app.db import with_session
from models.result_store import KeyValueStore
# HACK: https://stackoverflow.com/questions/15063936/csv-error-field-larger-than-field-lim... |
python/src/main/python/pygw/statistics/binning_strategy/numeric_range_field_value_binning_strategy.py | radiant-maxar/geowave | 280 | 11115855 | <reponame>radiant-maxar/geowave<filename>python/src/main/python/pygw/statistics/binning_strategy/numeric_range_field_value_binning_strategy.py<gh_stars>100-1000
#
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding cop... |
configs/_base_/det_pipelines/psenet_pipeline.py | yuexy/mmocr | 2,261 | 11115894 | <gh_stars>1000+
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
dict(
type='LoadTextAnnotations',
with_bbox=True,
with_mask=True,
poly2mas... |
contracts/migrations/0021_idv_piid_verbose_name.py | mepsd/CLAC | 126 | 11115898 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-10 18:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contracts', '0020_add_indexes'),
]
operations = [
migrations.AlterField(
... |
tools/kernel_names.py | datalayer-contrib/jupyterwidgets-tutorial | 342 | 11115912 | <reponame>datalayer-contrib/jupyterwidgets-tutorial
from argparse import ArgumentParser
from pathlib import Path
import nbformat
NB_VERSION = 4
def change_kernel_name(notebook_name, kernel_name, display_name=None):
"""
Change the name of the notebook kernel.
"""
dname = display_name if display_name ... |
test/test_bindings.py | hujiawei-sjtu/sdf_tools | 159 | 11115932 | #! /usr/bin/env python
import unittest
import numpy as np
from sdf_tools import utils_2d
class TestSDFTools(unittest.TestCase):
def test_sdf_tools(self):
res = 0.05
x_width = 20
y_height = 40
grid_world = np.zeros([y_height, x_width], dtype=np.uint8)
grid_world[1, 3] = ... |
sasila/system_normal/manager/spider_manager.py | iiiusky/Sasila | 327 | 11115959 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import threading
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf-8')
class SpiderManager(object):
def __init__(self):
self.spider_list = dict()
def set_spider(self, spider):
self.spider_list[sp... |
reclist/datasets.py | nsbits/reclist | 183 | 11116008 | import json
import tempfile
import zipfile
import os
from reclist.abstractions import RecDataset
from reclist.utils.config import *
class MovieLensDataset(RecDataset):
"""
MovieLens 25M Dataset
Reference: https://files.grouplens.org/datasets/movielens/ml-25m-README.html
"""
def __init__(self, **... |
test/test_kp_term_in_kp.py | Usama0121/flashtext | 5,330 | 11116018 | <filename>test/test_kp_term_in_kp.py
from collections import defaultdict
from flashtext import KeywordProcessor
import logging
import unittest
import json
import re
logger = logging.getLogger(__name__)
class TestKPDictionaryLikeFeatures(unittest.TestCase):
def setUp(self):
logger.info("Starting...")
... |
Angel/Libraries/DevIL-SDK-1.7.8/srcs/BuildImageLibraries.py | Tifox/Grog-Knight | 171 | 11116045 | <filename>Angel/Libraries/DevIL-SDK-1.7.8/srcs/BuildImageLibraries.py<gh_stars>100-1000
#!/usr/bin/python
# This file builds all the mac version of the image libraries.
# It won't work on Windows as it's using the Unix build methods.
import os
import sys
import shutil
FILE_PATH = os.path.abspath(__file__)
ROOT_DIR... |
test/test_console_notifier.py | trae-horton/secret-bridge | 152 | 11116061 | <reponame>trae-horton/secret-bridge<filename>test/test_console_notifier.py<gh_stars>100-1000
import unittest
from pathlib import Path
from config import Config
from notifiers import Registry
from models.finding import Finding
class TestConsoleNotifier(unittest.TestCase):
def test_console_notifier(self):
c... |
ipypublish/__init__.py | parmentelat/ipypublish | 220 | 11116082 | from ipypublish.scripts import nb_setup # noqa: F401
__version__ = "0.10.12"
|
tests/basic_checks/issue_46_non_existant_signal_column.py | jmabry/pyaf | 377 | 11116106 | import numpy as np
import pandas as pd
import pyaf.ForecastEngine as autof
try:
df = pd.DataFrame([[0 , 0.54543]], columns = ['date' , 'signal'])
lEngine = autof.cForecastEngine()
lEngine.train(df , 'date' , 'signal_non_existant', 1);
raise Exception("NOT_OK")
except Exception as e:
# should fail
... |
src/brain.py | Atharv-cyber/Jarvis-1 | 251 | 11116117 | <gh_stars>100-1000
import re
import webbrowser
import os
import random
import urllib
import thread
import yaml
from src import google_tts
from src.wikipedia import wikipedia
from src import network
from src.some_functions import *
from src import common
speak_engine = google_tts.Google_TTS()
with open('config.yml',... |
pytorch-pretrained-bert/eval/evaluate_ae.py | lianapanatau/BERT-for-RRC-ABSA | 425 | 11116136 | <reponame>lianapanatau/BERT-for-RRC-ABSA
import argparse
import time
import json
import numpy as np
import math
import random
import xml.etree.ElementTree as ET
from subprocess import check_output
def label_rest_xml(fn, output_fn, corpus, label):
dom=ET.parse(fn)
root=dom.getroot()
pred_y=[]
for zx, s... |
tests/test_metrics.py | Jeanselme/xgboost-survival-embeddings | 197 | 11116170 | import pandas as pd
import numpy as np
from xgbse.metrics import concordance_index, approx_brier_score, dist_calibration_score
from xgbse import XGBSEDebiasedBCE
from xgbse.non_parametric import get_time_bins, calculate_kaplan_vectorized
from tests.data import get_data
(
X_train,
X_test,
X_valid,
T_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.