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 |
|---|---|---|---|---|
Packs/Sixgill-Darkfeed/Scripts/SixgillSearchIndicators/SixgillSearchIndicators_test.py | diCagri/content | 799 | 11048783 | import json
import demistomock as demisto
from SixgillSearchIndicators import search_indicators
json_raw_data = '''[
{
"Contents": [
{
"CustomFields": {
"actor": "random",
"description": "Malware available for download from file-sharing ... |
layers/eight_mile/__init__.py | sagnik/baseline | 241 | 11048795 | <reponame>sagnik/baseline
from eight_mile.version import __version__
|
kong/datadog_checks/kong/check.py | mchelen-gov/integrations-core | 663 | 11048841 | <filename>kong/datadog_checks/kong/check.py
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from datadog_checks.base import OpenMetricsBaseCheckV2
from .metrics import METRIC_MAP
class KongCheck(OpenMetricsBaseCheckV2):
__NAMESPACE__ = 'kong'
... |
cart_venv/Lib/site-packages/tensorboard/_vendor/bleach/encoding.py | juice1000/Synchronous-vs-Asynchronous-Learning-Tensorflow- | 353 | 11048903 | import datetime
from decimal import Decimal
import types
import six
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_unicode(strings_only=True).
"""
return isinstance(obj, (
six.inte... |
Lib/test/test_longexp.py | jimmyyu2004/jython | 332 | 11048979 | <filename>Lib/test/test_longexp.py
import sys
from support import TestSkipped
REPS = 65580
#XXX: Is there a way around the method length limit in Jython?
if sys.platform.startswith('java'):
raise TestSkipped('The 65535 byte limit on methods in the JVM is a problem for jython.')
if sys.platform == 'mac':
impo... |
torch_audiomentations/utils/config.py | mogwai/torch-audiomentations | 430 | 11049005 | from pathlib import Path
from typing import Any, Dict, Text, Union
import torch_audiomentations
from torch_audiomentations import Compose
from torch_audiomentations.core.transforms_interface import BaseWaveformTransform
# TODO: define this elsewhere?
# TODO: update when a new type of transform is added (e.g. BaseSpec... |
ltr/index.py | tanjie123/hello-ltr | 109 | 11049036 | from ltr.helpers.movies import indexable_movies, noop
def rebuild(client, index, doc_src, force = False):
""" Reload a configuration on disk for each search engine
(Solr a configset, Elasticsearch a json file)
and reindex
"""
if client.check_index_exists(index):
if (force):
... |
src/app/tests/zoomus/tests_zoomus_invitation.py | iNerV/education-backend | 151 | 11049049 | import pytest
from app.integrations.zoomus import ZoomusHTTPException
pytestmark = [pytest.mark.django_db]
INVITE_URL = 'https://api.zoom.us/v2/webinars/100500/registrants/'
SUCCESS_JSON = {
'id': '0022304902349',
'join_url': 'https://join.url',
'registrant_id': 'CBjmE6twOzqzweby',
'start_time': '2... |
dataframes.py | caiobran/equiTable | 121 | 11049100 | import pandas as pd
import numpy as np
import sqlite3
import json
import sys
import re
import os
class DataFrames():
db_file = 'db/mstables.sqlite' # Standard db file name
def __init__(self, file = db_file):
msg = 'Creating initial DataFrames objects from file {}...\n'
print(msg.format(file... |
recipes_source/recipes/benchmark.py | woojinsong/PyTorch-tutorials-kr | 221 | 11049128 | """
PyTorch Benchmark
====================================
This recipe provides a quick-start guide to using PyTorch
``benchmark`` module to measure and compare code performance.
Introduction
------------
Benchmarking is an important step in writing code. It helps
us validate that our code meets performance expectatio... |
scripts/experimental/bmk2/logproc.py | bigwater/Galois | 230 | 11049138 | #!/usr/bin/env python
#
# logproc.py
#
# Log file reader library for bmk2. Reads log files generated by
# test2.py, for example.
#
# Copyright (c) 2015, 2016 The University of Texas at Austin
#
# Author: <NAME> <<EMAIL>>
#
# Intended to be licensed under GPL3
import re
import datetime
from collections import namedtupl... |
WEEKS/CD_Sata-Structures/_RESOURCES/pygorithm/pygorithm/searching/linear_search.py | webdevhub42/Lambda | 4,736 | 11049148 | """
Author: <NAME>
Created On: 1st August 2017
- Best O(1)
- Average O(n)
- Worst O(n)
"""
import inspect
def search(_list, target, initial_position=0):
"""sequential search algorithm
This function returns the position
of the target if found else returns -1
:param _list:
:param tar... |
spikex/wikigraph/__init__.py | hp0404/spikex | 339 | 11049196 | <filename>spikex/wikigraph/__init__.py<gh_stars>100-1000
from .wikigraph import WikiGraph, load
|
src/main/python/com/bluehonour/baostock/query_trade_dates.py | kingmoon3/stock-data-analysis-and-prediction | 162 | 11049216 | import baostock as bs
import pandas as pd
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from utils import *
"""
方法说明:通过API接口获取股票交易日信息,可以通过参数设置获取起止年份数据,提供上交所1990-今年数据。
返回类型:pandas的DataFrame类型。
返回数据说明
参数名称 参数描述
calendar_date 日期
is_trading_day 是否交... |
cli/rpc2socks/wmi.py | klsecservices/rpc2socks | 109 | 11049237 | # Copyright (c) Lexfo
# SPDX-License-Identifier: BSD-3-Clause
import contextlib
import time
from impacket.dcerpc.v5 import dtypes as impkt_dtypes
from impacket.dcerpc.v5.dcom import wmi as impkt_wmi
from . import smb
from .utils import dispatcher
from .utils import logging
__all__ = ("wmi_rexec", )
logger = loggi... |
examples/fractal.py | esnyder/axi | 239 | 11049246 | <filename>examples/fractal.py
from shapely import geometry
import axi
import sys
def main():
size = axi.A3_SIZE
bounds = axi.A3_BOUNDS
d = axi.Drawing.load(sys.argv[1])
print(len(d.paths[0]))
d = d.scale_to_fit(*size).center(*size)
d = d.simplify_paths(0.01 / 25.4)
print(len(d.paths[0]))
... |
spectral/tests/spatial.py | wwlswj/spectral | 398 | 11049253 | '''
Runs unit tests for various SPy spatial functions.
To run the unit tests, type the following from the system command line:
# python -m spectral.tests.spatial
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from numpy.testing import assert_allclose
fr... |
tests/test_pixabay.py | korymath/talk-generator | 110 | 11049255 | <reponame>korymath/talk-generator<filename>tests/test_pixabay.py
import unittest
from talkgenerator.sources import unsplash, pixabay
class PixabayTest(unittest.TestCase):
def test_pixabay_access(self):
images = pixabay.search_photos("office chair")
self.assertTrue(len(images) > 0)
sources ... |
utils/bazel/llvm-project-overlay/libc/libc_build_rules.bzl | LaudateCorpus1/llvm-project | 605 | 11049257 | <filename>utils/bazel/llvm-project-overlay/libc/libc_build_rules.bzl
# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""LLVM libc startlark rules for building individual fun... |
tensorflow/nlp/evaluate.py | huang-xx/cs230-code-examples | 1,860 | 11049275 | """Evaluate the model"""
import argparse
import logging
import os
import numpy as np
import tensorflow as tf
from model.utils import Params
from model.utils import set_logger
from model.evaluation import evaluate
from model.input_fn import input_fn
from model.input_fn import load_dataset_from_text
from model.model_f... |
qml-intro/ex-simple-item/pyside/ellipseitem.py | jgompis/kdabtv | 140 | 11049297 | <reponame>jgompis/kdabtv<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019, Klaralvdalens Datakonsult AB (KDAB)
# All rights reserved.
#
# See the LICENSE.txt file shipped along with this file for the license.
from PySide2.QtCore import Signal, Property
from PySide2.QtGui import QP... |
openhgnn/sampler/random_walk_sampler.py | jingmouren/OpenHGNN | 235 | 11049301 | import dgl
import numpy as np
from torch.utils.data import Dataset
import torch
class RandomWalkSampler(Dataset):
def __init__(self, g, rw_walks: int, window_size: int, neg_size: int, metapath=None, rw_prob=None, rw_length=None):
self.g = g
self.start_idx = [0]
for i, num_nodes in enumera... |
cakechat/utils/w2v/__init__.py | sketscripter/emotional-chatbot-cakechat | 1,608 | 11049333 | from cakechat.utils.w2v.utils import get_w2v_model_path, get_w2v_params_str, get_w2v_model_name
|
libp2p/crypto/authenticated_encryption.py | g-r-a-n-t/py-libp2p | 315 | 11049406 | from dataclasses import dataclass
import hmac
from typing import Tuple
from Crypto.Cipher import AES
import Crypto.Util.Counter as Counter
class InvalidMACException(Exception):
pass
@dataclass(frozen=True)
class EncryptionParameters:
cipher_type: str
hash_type: str
iv: bytes
mac_key: bytes
... |
simple_history/registry_tests/migration_test_app/migrations/0007_alter_historicalmodelwithcustomattrforeignkey_options_and_more.py | skept/django-simple-history | 911 | 11049418 | <filename>simple_history/registry_tests/migration_test_app/migrations/0007_alter_historicalmodelwithcustomattrforeignkey_options_and_more.py
# Generated by Django 4.0.1 on 2022-01-28 11:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
(
"migration_t... |
pandas/io/clipboard/exceptions.py | vimalromeo/pandas | 6,989 | 11049421 | import ctypes
class PyperclipException(RuntimeError):
pass
class PyperclipWindowsException(PyperclipException):
def __init__(self, message):
message += " ({err})".format(err=ctypes.WinError())
super(PyperclipWindowsException, self).__init__(message)
|
gimp-plugins/DeblurGANv2/testing.py | sunlin7/GIMP-ML | 1,077 | 11049436 | <reponame>sunlin7/GIMP-ML
import cv2
from predictorClass import Predictor
predictor = Predictor(weights_path='best_fpn.h5')
img = cv2.imread('img/img.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
pred = predictor(img, None)
pred = cv2.cvtColor(pred, cv2.COLOR_RGB2BGR)
cv2.imwrite('submit/img.jpg',pred)
|
models/others/gmm.py | wiseodd/bayesian-models | 232 | 11049453 | <filename>models/others/gmm.py
"""
MLE for Gaussian Mixture Model using EM
"""
import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
K = 2
# Generate data
X1 = np.random.multivariate_normal([5, 5], np.diag([0.5, 0.5]), size=20)
X2 = np.random.multivariate_normal([8, 8], np.diag([0.5, 0.5]), siz... |
droidlet/lowlevel/locobot/remote/pyrobot/utils/util.py | ali-senguel/fairo | 669 | 11049455 | <reponame>ali-senguel/fairo
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import numpy as np
# import rospy
# import tf
from ..habitat import transformations as tf_transformation... |
tests/test_utils/__init__.py | wx-b/cockpit | 367 | 11049468 | """Tests for ``cockpit.utils``."""
|
grow/performance/profile.py | akashkalal/grow | 335 | 11049505 | """Code timing for profiling."""
import time
class Timer(object):
"""Times code to see how long it takes using a context manager."""
def __init__(self, key, label=None, meta=None):
self._time = time
self.key = key
self.label = label or key
self.meta = meta
self.start ... |
linguistic_style_transfer_model/config/global_config.py | spencerbraun/linguistic-style-transfer | 136 | 11049510 | <gh_stars>100-1000
from datetime import datetime as dt
logger_name = "linguistic_style_transfer"
experiment_timestamp = dt.now().strftime("%Y%m%d%H%M%S")
vocab_size = None # set by runtime param
bow_size = None # set by runtime params and exclusions
filter_sentiment_words = True
filter_stopwords = True
embedding_... |
python/ql/test/library-tests/PointsTo/guarded/type_test.py | vadi2/codeql | 4,036 | 11049515 | <filename>python/ql/test/library-tests/PointsTo/guarded/type_test.py
def f(d = {}):
if isinstance(d, dict):
use(d)
else:
use(d)
def g(cond):
x = 0 if cond else 1.0
if isinstance(x, int):
use(x)
elif isinstance(x, float):
use(x)
else:
use(x)
def h(arg... |
tests/basics/gen_yield_from_close.py | peterson79/pycom-micropython-sigfox | 303 | 11049550 | def gen():
yield 1
yield 2
yield 3
yield 4
def gen2():
yield -1
print((yield from gen()))
yield 10
yield 11
g = gen2()
print(next(g))
print(next(g))
g.close()
try:
print(next(g))
except StopIteration:
print("StopIteration")
# Now variation of same test, but with leaf generato... |
xautodl/datasets/math_dynamic_generator.py | Joey61Liuyi/AutoDL-Projects | 817 | 11049551 | <gh_stars>100-1000
#####################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2021.03 #
#####################################################
import abc
import numpy as np
def assert_list_tuple(x):
assert isinstance(x, (list, tuple))
return len(x)
class DynamicGenerator(abc... |
starfish/core/spots/DecodeSpots/metric_decoder.py | haoxusci/starfish | 164 | 11049552 | from starfish.core.codebook.codebook import Codebook
from starfish.core.intensity_table.decoded_intensity_table import DecodedIntensityTable
from starfish.core.intensity_table.intensity_table_coordinates import \
transfer_physical_coords_to_intensity_table
from starfish.core.spots.DecodeSpots.trace_builders import ... |
metrics/kvret/response_entity_hit.py | HKUNLP/UnifiedSKG | 191 | 11049566 | # coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors.
#
# 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 requir... |
examples/mpc_cifar/launcher.py | knarflin/CrypTen | 1,074 | 11049592 | <gh_stars>1000+
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
To run mpc_cifar example in multiprocess mode:
$ python3 examples/mpc_cifar/launcher.py \
--e... |
ants/core/ants_metric_io.py | xemio/ANTsPy | 338 | 11049626 | """
"""
__all__ = ['new_ants_metric',
'create_ants_metric',
'supported_metrics']
import os
import numpy as np
from .. import utils
from . import ants_image as iio
from . import ants_metric as mio
_supported_metrics = {'MeanSquares',
'MattesMutualInformation',
... |
utils/expert_timings.py | kaizhang1215/mmt | 201 | 11049645 | <filename>utils/expert_timings.py
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
electrumsv/wallet_database/migrations/migration_0025_invoices.py | electrumsv/electrumsv | 136 | 11049671 | import json
try:
# Linux expects the latest package version of 3.35.4 (as of pysqlite-binary 0.4.6)
import pysqlite3
except ModuleNotFoundError:
# MacOS has latest brew version of 3.35.5 (as of 2021-06-20).
# Windows builds use the official Python 3.9.5 builds and bundled version of 3.35.5.
import s... |
rpi_weather.py | caternuson/rpi-weather | 130 | 11049717 | <filename>rpi_weather.py
#===============================================================================
# rpi_weather.py
#
# Class for interfacing to Raspberry Pi with four Adafruit 8x8 LEDs attached.
#
# 2015-04-15
# <NAME>
#===============================================================================
from time im... |
modules/nltk_contrib/stringcomp.py | h4ck3rm1k3/NLP-project | 123 | 11049726 | # Natural Language Toolkit
# String Comparison Module
# Author: <NAME> <<EMAIL>>
"""
String Comparison Module.
Author: <NAME> <<EMAIL>>
Based on previous work by <NAME>, <NAME>, <NAME>, <NAME>,
and <NAME>.
"""
def stringcomp (fx, fy):
"""
Return a number within C{0.0} and C{1.0} indicating the similarity bet... |
examples/dp_a.py | uta8a/Jikka | 139 | 11049747 | <filename>examples/dp_a.py
# https://atcoder.jp/contests/dp/tasks/dp_a
from typing import *
def solve(n: int, h: List[int]) -> int:
assert 2 <= n <= 10 ** 5
assert len(h) == n
assert all(1 <= h_i <= 10 ** 4 for h_i in h)
dp = [-1 for _ in range(n)]
dp[0] = 0
dp[1] = abs(h[1] - h[0])
for i ... |
tools/pot/openvino/tools/pot/algorithms/quantization/default/algorithm.py | pazamelin/openvino | 2,406 | 11049757 | <reponame>pazamelin/openvino
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from copy import deepcopy
from ..bias_correction.algorithm import BiasCorrection
from ..channel_alignment.algorithm import ActivationChannelAlignment
from ..fast_bias_correction.algorithm import FastBiasCorr... |
tests/operator/test_binary_arithmetic.py | maggyero/desugar | 109 | 11049796 | <reponame>maggyero/desugar<filename>tests/operator/test_binary_arithmetic.py
import operator
import pytest
import desugar.operator
from . import common
class BinaryOperationTests:
"""Standard tests for binary operators.
Subclasses are expected to provide the appropriate details to test a binary
opera... |
vlt.py | sennnnn/Vision-Language-Transformer | 132 | 11049802 | import argparse
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
from yacs.config import CfgNode as CN
from executor import Tester, Trainer, Debugger
MODES = ['train', 'test', 'debug']
parser = argparse.ArgumentParser()
parser.add_argument('phase', choices=MODES)
p... |
src/oddt/build/lib/oddt/scoring/functions/NNScore.py | annacarbery/VS_ECFP | 264 | 11049814 | <filename>src/oddt/build/lib/oddt/scoring/functions/NNScore.py<gh_stars>100-1000
from __future__ import print_function
import sys
from os.path import dirname, isfile, join as path_join
import numpy as np
import warnings
from joblib import Parallel, delayed
from scipy.stats import pearsonr
from sklearn.metrics import r... |
runway_model.py | mathematiguy/stylized-neural-painting | 1,309 | 11049824 | <reponame>mathematiguy/stylized-neural-painting
import argparse
import torch
torch.cuda.current_device()
import torch.optim as optim
import runway
from painter import *
# Decide which device we want to run on
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
from PIL import Image
# settings
pars... |
corehq/apps/hqwebapp/tests/test_two_factor_gateways.py | dimagilg/commcare-hq | 471 | 11049837 | from unittest.mock import Mock, patch
from .. import two_factor_gateways as mod
def test_gateway_make_call():
gateway = mod.Gateway.__new__(mod.Gateway) # instantiate without __init__
gateway.from_number = "+16145551234"
gateway.client = Mock(name="client")
device = Mock(name="device")
device.nu... |
benchmarking/conftest.py | tadeu/markdown-it-py | 285 | 11049853 | def pytest_benchmark_update_machine_info(config, machine_info):
import psutil
freq = psutil.cpu_freq()
machine_info["psutil"] = {
"cpu_count": psutil.cpu_count(logical=False),
"cpu_count_logical": psutil.cpu_count(logical=True),
"cpu_percent": psutil.cpu_percent(),
"cpu_freq... |
test/config/multi_thread/multi_thread_tuner.py | dutxubo/nni | 9,680 | 11049867 | <filename>test/config/multi_thread/multi_thread_tuner.py<gh_stars>1000+
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import logging
import time
from nni.tuner import Tuner
class MultiThreadTuner(Tuner):
def __init__(self):
self.parent_done = False
def generate_parameters(... |
refinery/bnpy/bnpy-dev/bnpy/allocmodel/admix/HDPBetaOptimizer.py | csa0001/Refinery | 103 | 11049920 | <gh_stars>100-1000
'''
HDPBetaOptimizer.py
Functions for obtaining point estimates of the HDP global appearance probabilities.
Model Notation
--------
HDP with a finite truncation to K active components
v := K-length vector with entries in [0,1]
beta := K+1-length vector with entries in [0,1]
entries mus... |
mmdet/models/detectors/DCM.py | ydiller/BalancedGroupSoftmax | 333 | 11049924 | <filename>mmdet/models/detectors/DCM.py
from ..registry import DETECTORS
from .two_stage import TwoStageDetector
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmdet.core import bbox2result, bbox2roi
from mmdet.core import multiclass_nms
@DETECTORS.register_module
class DCM(TwoStageDetecto... |
experiments/mnist_dropout_nofire.py | dojitza/ddnn | 110 | 11049927 | from __future__ import absolute_import
from __future__ import print_function
import random
random.seed(9001)
import os
import sys
sys.path.append('..')
import argparse
import chainer
import numpy as np
#from datasets.datasets import get_mvmc, get_mvmc_flatten
from datasets.mnist import get_mnist
import deepopt.choo... |
Chapter18/hw/zero.py | haohaoxiao/Deep-Reinforcement-Learning-Hands-On-Second-Edition | 621 | 11049939 | <reponame>haohaoxiao/Deep-Reinforcement-Learning-Hands-On-Second-Edition<filename>Chapter18/hw/zero.py
"""
Turns robot legs to zero positions
"""
from libhw import servo
import utime
PINS = ["B6", "B7", "B10", "B11"]
INV = [True, False, True, False]
def zero():
ch = servo.pins_to_timer_channels(PINS)
brain... |
pytorch_ares/third_party/hydra/trainer/crown-ibp.py | thu-ml/realsafe | 107 | 11050028 | <reponame>thu-ml/realsafe
import time
import torch
import torch.nn as nn
import torchvision
from utils.logging import AverageMeter, ProgressMeter
from utils.eval import accuracy
from utils.adv import trades_loss
import numpy as np
from symbolic_interval.symbolic_network import sym_interval_analyze, naive_interval_a... |
src/salt/base/ext/_modules/hooklib.py | autopi-io/autopi-core | 133 | 11050031 | import logging
import dateutil.parser
import re
from messaging import keyword_resolve
from salt_more import cached_loader
log = logging.getLogger(__name__)
def echo_handler(*args, **kwargs):
"""
Mainly for testing.
"""
log.info("Echo: {:}".format(args))
def module_handler(name, *args, **kwargs):... |
wg-manager-backend/script/obfuscate/shapeshifter.py | SH-Daemon/wg-manager | 417 | 11050034 | <reponame>SH-Daemon/wg-manager
import os
from threading import Thread
from script.obfuscate import BaseObfuscation, NotInstalledError
import re
import pathlib
import shutil
current_dir = pathlib.Path(__file__).parent.absolute()
shapeshifter_path = current_dir.joinpath("binary/shapeshifter-dispatcher")
shapeshifter_bi... |
genbmm/genbmm/genmul.py | harvardnlp/cascaded-generation | 122 | 11050053 | import torch
try:
import _genbmm
except ImportError:
pass
class LogMatMul(torch.autograd.Function):
@staticmethod
def forward(ctx, a, b):
out, = _genbmm.forward(a, b, 0)
ctx.save_for_backward(a, b, out)
return out
@staticmethod
def backward(ctx, grad_output):
... |
boto3_type_annotations_with_docs/boto3_type_annotations/iam/waiter.py | cowboygneox/boto3_type_annotations | 119 | 11050060 | from typing import Dict
from botocore.waiter import Waiter
class InstanceProfileExists(Waiter):
def wait(self, InstanceProfileName: str, WaiterConfig: Dict = None):
"""
Polls :py:meth:`IAM.Client.get_instance_profile` every 1 seconds until a successful state is reached. An error is returned after ... |
zippy/benchmarks/src/micro/list-iterating-explicit.py | lucapele/pele-c | 319 | 11050079 | <reponame>lucapele/pele-c<filename>zippy/benchmarks/src/micro/list-iterating-explicit.py
# zwei 12/28/13
# iterates an int list
import time
LIST = [i % 15 for i in range(900)]
def iterate_list(ll, num):
for t in range(num):
iterator = iter(LIST)
try:
while True:
i = next(iterator)
item = ll[i... |
allennlp_models/classification/models/__init__.py | shunk031/allennlp-models | 402 | 11050102 | <filename>allennlp_models/classification/models/__init__.py
from allennlp_models.classification.models.biattentive_classification_network import (
BiattentiveClassificationNetwork,
)
from allennlp_models.classification.models.transformer_classification_tt import (
TransformerClassificationTT,
)
|
recognition/arcface_paddle/dynamic/backbones/mobilefacenet.py | qaz734913414/insightface | 12,377 | 11050107 | <reponame>qaz734913414/insightface
# Copyright (c) 2021 PaddlePaddle Authors. 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/LICEN... |
DQM/Physics/python/ewkDQM_cfi.py | ckamtsikis/cmssw | 852 | 11050132 | import FWCore.ParameterSet.Config as cms
# DQM monitor module for EWK
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
ewkDQM = DQMEDAnalyzer('EwkDQM',
elecTriggerPathToPass = cms.vstring("HLT_Ele", "HLT_DoubleEle", "HLT_DoublePhoton"),
muonTriggerPathToPass = cms.vstring("HLT_Mu... |
ebcli/operations/platformops.py | sdolenc/aws-elastic-beanstalk-cli | 110 | 11050147 | <filename>ebcli/operations/platformops.py<gh_stars>100-1000
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aw... |
IDLE-files/euclid_algorithm.py | arvidl/dynamical-systems-with-applications-using-python | 106 | 11050155 | <filename>IDLE-files/euclid_algorithm.py
# Euclid's algorithm to find the gcd.
# See Exercise 10.
# Run the Module (or type F5).
a = 12348
b = 14238
while b != 0:
d = a % b
a = b
b = d
print('The greatest common divisor is {}'.format(a))
|
aws_sso_credential_process/__init__.py | benkehoe/aws-sso-credential-process | 129 | 11050166 | <gh_stars>100-1000
from .aws_sso_credential_process import __version__
|
tests/test_snapshots.py | gmarkey/k8s-snapshots | 326 | 11050173 | <reponame>gmarkey/k8s-snapshots
from datetime import timedelta
from pendulum import Pendulum
from unittest import TestCase
from k8s_snapshots.backends.abstract import Snapshot
from k8s_snapshots.context import Context
from k8s_snapshots.rule import Rule
from k8s_snapshots.snapshot import snapshots_for_rule_are_outdate... |
examples/docs_snippets/docs_snippets/concepts/partitions_schedules_sensors/date_config_job.py | rpatil524/dagster | 4,606 | 11050219 | from dagster import job, op
@op(config_schema={"date": str})
def process_data_for_date(context):
date = context.op_config["date"]
context.log.info(f"processing data for {date}")
@job
def do_stuff():
process_data_for_date()
|
angrmanagement/plugins/source_viewer/__init__.py | DennyDai/angr-management | 474 | 11050220 | from .source_viewer_plugin import SourceViewerPlugin
|
models/professor.py | noryb009/rmc | 164 | 11050226 | from bson import json_util
import mongoengine as me
import re
import redis
import rating as _rating
import review as _review
import rmc.shared.constants as c
from rmc.shared import util
import user_course
import itertools
# TODO(mack): remove this from here?
r = redis.StrictRedis(host=c.REDIS_HOST, port=c.REDIS_PORT,... |
launch/jfr2018/pose_to_odom.py | scumatteo/rtabmap_ros | 657 | 11050236 | <filename>launch/jfr2018/pose_to_odom.py
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseWithCovarianceStamped
from nav_msgs.msg import Odometry
def callback(data):
odom = Odometry()
odom.header = data.header
odom.child_frame_id = child_frame_id
odom.pose = data.pose
pub.publis... |
voice2json/core.py | CvH/voice2json | 913 | 11050258 | """
Core voice2json command support.
"""
import asyncio
import io
import logging
import os
import queue
import shlex
import ssl
import sys
import threading
import typing
import wave
from pathlib import Path
import pydash
_LOGGER = logging.getLogger("voice2json.core")
# -----------------------------------------------... |
integration_tests/test_3d.py | eodcgmbh/datacube-core | 363 | 11050261 | # This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2020 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
import logging
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace
import numpy
import pytest
import yaml
try... |
matchzoo/datasets/embeddings/__init__.py | baajur/MatchZoo | 2,209 | 11050263 | from pathlib import Path
from .load_glove_embedding import load_glove_embedding
DATA_ROOT = Path(__file__).parent
EMBED_RANK = DATA_ROOT.joinpath('embed_rank.txt')
EMBED_10 = DATA_ROOT.joinpath('embed_10_word2vec.txt')
EMBED_10_GLOVE = DATA_ROOT.joinpath('embed_10_glove.txt')
|
custom/AbstractCustomFormatter.py | MikeSilvis/spacecommander | 340 | 11050275 | <reponame>MikeSilvis/spacecommander
# AbstractCustomFormatter.py
# Provides common functionality for custom formatters.
#
# If a filename is specified as a parameter, it will change that file in place.
# If input is provided through stdin, it will send the result to stdout.
# Copyright 2015 Square, Inc
import sys
cla... |
hatesonar/crawler/twitter.py | r00tr00tr00t/HateSonar | 155 | 11050285 | """
Twitter crawler.
"""
import os
import tweepy
def load_keys():
"""Loads Twitter keys.
Returns:
tuple: consumer_key, consumer_secret, access_token, access_token_secret
"""
consumer_key = os.environ.get('CONSUMER_KEY')
consumer_secret = os.environ.get('CONSUMER_SECRET')
access_token... |
setup.py | coder-lipenghui/untp | 161 | 11050304 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'untp',
version = '1.1.8',
description = 'A command line tool to split TexturePacker published files.',
url = 'https://github.com/justbilt/untp',
author = 'justbilt',
author_email = '<EMAIL>',
license = 'MIT Li... |
reddit2telegram/channels/r_damnthatsinteresting/app.py | mainyordle/reddit2telegram | 187 | 11050320 | <reponame>mainyordle/reddit2telegram<filename>reddit2telegram/channels/r_damnthatsinteresting/app.py
#encoding:utf-8
# Write here subreddit name. Like this one for /r/Damnthatsinteresting.
subreddit = 'Damnthatsinteresting'
# This is for your public telegram channel.
t_channel = '@r_Damnthatsinteresting'
def send_po... |
databricks_cli/clusters/api.py | testruction/databricks-cli | 252 | 11050340 | <gh_stars>100-1000
# Databricks CLI
# Copyright 2017 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"), except
# that the use of services to which certain application programming
# interfaces (each, an "API") connect requires that the user first obtain
# a license for the use of the AP... |
models/ltlib/bidict.py | SonjaAits/MTL-Bioinformatics-2016 | 171 | 11050365 | <gh_stars>100-1000
import numpy as np
from collections import MutableMapping
class Bidict(MutableMapping):
"""Bidirectional dictionary.
Implementation following in part https://github.com/jab/bidict/
"""
def __init__(self, *args, **kwargs):
self._fwd = dict()
self._inv = dict()
... |
tensorflow_addons/layers/tests/snake_test.py | leandro-gracia-gil/addons | 1,560 | 11050396 | # Copyright 2020 The TensorFlow Authors. 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 applica... |
tests/r/test_default.py | hajime9652/observations | 199 | 11050420 | <gh_stars>100-1000
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.default import default
def test_default():
"""Test module default.py by downloading
default.csv and testing shape of
ex... |
Demo/tkinter/guido/imageview.py | cemeyer/tauthon | 2,293 | 11050424 | <reponame>cemeyer/tauthon<filename>Demo/tkinter/guido/imageview.py<gh_stars>1000+
from Tkinter import *
import sys
def main():
filename = sys.argv[1]
root = Tk()
img = PhotoImage(file=filename)
label = Label(root, image=img)
label.pack()
root.mainloop()
main()
|
dataset_preprocessing/preprocess_Multicam_videos.py | malikhussain72/cnn_fall-detection | 183 | 11050443 | <filename>dataset_preprocessing/preprocess_Multicam_videos.py
import os
import cv2
import sys
import json
import glob
import shutil
import codecs
import zipfile
# Path where the videos are stored (in zip format, as in a fresh download)
data_folder = '/home/user/Downloads/'
dst_folder = '' # folder where the dataset is... |
src/c3nav/mapdata/migrations/0004_space_level_category_name.py | johnjohndoe/c3nav | 132 | 11050453 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-26 18:18
from __future__ import unicode_literals
from django.db import migrations, models
def set_space_level_category(apps, schema_editor):
Space = apps.get_model('mapdata', 'Space')
Space.objects.filter(level='').update(leve... |
meshreg/visualize/vizdemo.py | pgrady3/handobjectconsist | 103 | 11050503 | import cv2
import numpy as np
def draw_contours(img, mask, color=(0, 255, 255)):
"""
Get outline of mask and draw it on the image
Args:
img: image on which to draw
mask: mask for which contours should be found
color: color of contours to draw
"""
contours = cv2.findContour... |
tutorials/setup-gcp/rdbox-gui/flask_rdbox/views/utils.py | hamstick/rdbox | 278 | 11050504 | #!/usr/bin/env python3
import psutil
import re
import os
class Utils(object):
@classmethod
def find_procs_by_name(cls, name):
"Return a list of processes matching 'name'."
assert name, name
ls = []
for p in psutil.process_iter():
name_, exe, cmdline = "", "", []
... |
HomeComponents/PopupWindow.py | Satanepigone/osr2mp4-app | 262 | 11050537 | <reponame>Satanepigone/osr2mp4-app<filename>HomeComponents/PopupWindow.py
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QTextEdit, QFrame, QLabel
from PyQt5 import QtCore
from BaseComponents.Buttons import Button
class PopupWindow(Button):
def __init__(self, parent):
super(PopupWindow, self).__init__(p... |
modules/nltk_contrib/hadoop/tf_idf/sort.py | h4ck3rm1k3/NLP-project | 123 | 11050546 | """
sort program in windows sometimes behaves strangely
so we write a small sorting program to be used in testing
"""
import sys
li = []
for line in sys.stdin:
li.append(line)
li.sort()
for e in li:
print e,
|
tests/resources/diagram_export.py | j0ono0/pinout-diagram | 304 | 11050579 | <filename>tests/resources/diagram_export.py<gh_stars>100-1000
from typing import Text
from pinout.components.layout import Diagram
from pinout.components.text import TextBlock
diagram = Diagram(800, 400, tag="pinout")
diagram.add_stylesheet("styles.css")
diagram.add(TextBlock("Pinout export test.", x=100, y=100))
|
kili/queries/user/queries.py | ASonay/kili-playground | 214 | 11050599 | """
Queries of user queries
"""
def gql_users(fragment):
"""
Return the GraphQL users query
"""
return f'''
query($where: UserWhere!, $first: PageSize!, $skip: Int!) {{
data: users(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
'''
GQL_USERS_COUNT = '''
query($where: UserWher... |
feathermodules/classical/vigenere.py | timgates42/featherduster | 1,026 | 11050602 | <gh_stars>1000+
# Vigenere cipher FeatherModule by <NAME>
import cryptanalib as ca
import feathermodules
def break_vigenere(ciphertexts):
options = dict(feathermodules.current_options)
results = []
for i, sample in enumerate(ciphertexts):
keys = ca.break_vigenere(sample,
... |
modules/Sublime_AdvancedNewFile_1_0_0/advanced_new_file/commands/duplicate_file_base.py | ElectricImp-CSE/ElectricImp-Sublime | 597 | 11050603 | import os
import re
import sublime_plugin
from .command_base import AdvancedNewFileBase
from ..anf_util import *
class DuplicateFileBase(AdvancedNewFileBase, sublime_plugin.WindowCommand):
def __init__(self, window):
super(DuplicateFileBase, self).__init__(window)
def run(self, is_python=False, init... |
examples/definitions_schema.py | wyfo/apimodel | 118 | 11050631 | from dataclasses import dataclass
from apischema.json_schema import definitions_schema
@dataclass
class Bar:
baz: int = 0
@dataclass
class Foo:
bar: Bar
assert definitions_schema(deserialization=[list[Foo]], all_refs=True) == {
"Foo": {
"type": "object",
"properties": {"bar": {"$ref":... |
CV/PaddleFSL/dataloader/omniglot.py | zhangyimi/Research | 1,319 | 11050642 | import numpy as np
import paddle
import paddle.fluid as fluid
import pickle as pkl
from PIL import Image
import os
import glob
import csv
import random
class LoadData():
def __init__(self,mode):
self.mode = mode
self.datafile = 'data/omniglot/omniglot_' + self.mode + '.pkl'
print('loading o... |
backend/www/test/versioning_test.py | sleepingAnt/viewfinder | 645 | 11050672 | # Copyright 2012 Viewfinder Inc. All Rights Reserved.
"""Test old and new message formats.
This module contains tests that cover various versioning scenarios:
1. Tests of older message formats that clients may still be using,
in order to make sure that we still accept them.
2. Tests to make sure we do not ... |
chapter08/dags/custom/ranking.py | add54/Data_PipeLine_Apache_Airflow | 303 | 11050715 | import pandas as pd
def rank_movies_by_rating(ratings, min_ratings=2):
ranking = (
ratings.groupby("movieId")
.agg(
avg_rating=pd.NamedAgg(column="rating", aggfunc="mean"),
num_ratings=pd.NamedAgg(column="userId", aggfunc="nunique"),
)
.loc[lambda df: df["nu... |
code_examples/tensorflow/block_sparse/utils.py | payoto/graphcore_examples | 260 | 11050772 | # Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
import numpy as np
from functools import reduce
from operator import mul
from operator import add
from subprocess import run
g_random_sparse_mask = np.random.RandomState()
g_random_data = np.random.RandomState()
g_random_labels = np.random.RandomState... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.