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 |
|---|---|---|---|---|
torch/utils/data/datapipes/iter/httpreader.py | xiaohanhuang/pytorch | 60,067 | 12781056 | <reponame>xiaohanhuang/pytorch<filename>torch/utils/data/datapipes/iter/httpreader.py
from io import IOBase
from typing import Sized, Tuple
from torch.utils.data import IterDataPipe
from torch.utils.data.datapipes.utils.common import deprecation_warning_torchdata
class HTTPReaderIterDataPipe(IterDataPipe[Tuple[str, I... |
scipy/stats/tests/test_crosstab.py | Ennosigaeon/scipy | 9,095 | 12781061 | <filename>scipy/stats/tests/test_crosstab.py
import pytest
import numpy as np
from numpy.testing import assert_array_equal
from scipy.stats.contingency import crosstab
@pytest.mark.parametrize('sparse', [False, True])
def test_crosstab_basic(sparse):
a = [0, 0, 9, 9, 0, 0, 9]
b = [2, 1, 3, 1, 2, 3, 3]
exp... |
examples/libtest/imports/allsimple.py | takipsizad/pyjs | 739 | 12781079 | """
Helper module for import * without __all__
"""
all_import2 = 3
all_import3 = 3
all_override = True
|
step30_multiple_stacks/Python/backend/lambda.py | fullstackwebdev/full-stack-serverless-cdk | 192 | 12781091 | <reponame>fullstackwebdev/full-stack-serverless-cdk<filename>step30_multiple_stacks/Python/backend/lambda.py
import json
import random
import string
def lambda_handler(event, context):
# print(event)
# print(context)
letters = string.ascii_lowercase
value = ''.join(random.choice(letters) for i in... |
scripts/benchmark_ecef2geo.py | wrlssqi/pymap3d | 116 | 12781116 | <filename>scripts/benchmark_ecef2geo.py
#!/usr/bin/env python3
"""
benchmark ecef2geodetic
"""
import time
from pymap3d.ecef import ecef2geodetic
import numpy as np
import argparse
ll0 = (42.0, 82.0)
def bench(N: int) -> float:
x = np.random.random(N)
y = np.random.random(N)
z = np.random.random(N)
... |
mmdeploy/codebase/mmdet3d/models/voxelnet.py | xizi/mmdeploy | 746 | 12781126 | # Copyright (c) OpenMMLab. All rights reserved.
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
'mmdet3d.models.detectors.voxelnet.VoxelNet.simple_test')
def voxelnet__simple_test(ctx,
self,
voxels,
num... |
egg/hatch.py | TheMartianObserver/nsimd | 247 | 12781151 | <filename>egg/hatch.py
# Copyright (c) 2021 Agenium Scale
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify... |
ggtnn_graph_parse.py | hexahedria/gated-graph-transformer-network | 160 | 12781160 | <filename>ggtnn_graph_parse.py<gh_stars>100-1000
import os
import sys
import re
import collections
import numpy as np
import scipy
import json
import itertools
import pickle
import gc
import gzip
import argparse
def tokenize(sent):
'''Return the tokens of a sentence including punctuation.
>>> tokenize('Bob dro... |
src/examples/plot_costs.py | zhhengcs/sunny-side-up | 581 | 12781176 | #!/usr/bin/env python
import os
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--start", default=25, type=int)
arg_parser.add_argument("cost_file", default="metrics_costs.json", narg... |
tests/unit/test_utils.py | shkumagai/python-ndb | 137 | 12781247 | <reponame>shkumagai/python-ndb
# Copyright 2018 Google LLC
#
# 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 applicabl... |
test/test_cairopen.py | colinmford/coldtype | 142 | 12781260 | import unittest
from coldtype.pens.cairopen import CairoPen
from pathlib import Path
from coldtype.color import hsl
from coldtype.geometry import Rect
from coldtype.text.composer import StSt, Font
from coldtype.pens.datpen import DATPen, DATPens
from PIL import Image
import drawBot as db
import imagehash
import conte... |
start_mirt_pipeline.py | hmirin/guacamole | 141 | 12781293 | <reponame>hmirin/guacamole
#!/usr/bin/env python
"""This file will take you all the way from a CSV of student performance on
test items to trained parameters describing the difficulties of the assessment
items.
The parameters can be used to identify the different concepts in your
assessment items, and to drive your own... |
samples/python/46.teams-auth/bots/__init__.py | Aliacf21/BotBuilder-Samples | 1,998 | 12781296 | <reponame>Aliacf21/BotBuilder-Samples<gh_stars>1000+
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .dialog_bot import DialogBot
from .teams_bot import TeamsBot
__all__ = ["DialogBot", "TeamsBot"]
|
tests/test_model_methods/test_load_all.py | naterenegar/ormar | 905 | 12781304 | <filename>tests/test_model_methods/test_load_all.py<gh_stars>100-1000
from typing import List
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
class BaseMeta(ormar.... |
features/steps/log-scale-axes.py | eaton-lab/toyplot | 438 | 12781313 | <reponame>eaton-lab/toyplot<filename>features/steps/log-scale-axes.py<gh_stars>100-1000
# Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
from behave import *
import nose
import numpy
import toy... |
PyLeap_CPB_EyeLights_LED_Glasses_Sparkle/code.py | gamblor21/Adafruit_Learning_System_Guides | 665 | 12781322 | # SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
import board
from adafruit_led_animation.animation.sparkle import Sparkle
from adafruit_led_animation.color import PURPLE
from adafruit_led_animation.sequence import AnimationSequence
from adafruit_is31fl3741.adafruit_ledglasses import MUST_BUFFER, ... |
plum/util.py | ruancomelli/plum | 153 | 12781336 | <filename>plum/util.py
import abc
import logging
__all__ = ["multihash", "Comparable", "is_in_class", "get_class", "get_context"]
log = logging.getLogger(__name__)
def multihash(*args):
"""Multi-argument order-sensitive hash.
Args:
*args: Objects to hash.
Returns:
int: Hash.
"""
... |
tools/spaln/list_spaln_tables.py | ic4f/tools-iuc | 142 | 12781352 | #!/usr/bin/env python3
import argparse
import shlex
import sys
from subprocess import run
from typing import TextIO
def find_common_ancestor_distance(
taxon: str, other_taxon: str, taxonomy_db_path: str, only_canonical: bool
):
canonical = "--only_canonical" if only_canonical else ""
cmd_str = f"taxonomy... |
OmniMarkupLib/Renderers/MediaWikiRenderer.py | henumohe/OmniMarkupPreviewer | 476 | 12781363 | <filename>OmniMarkupLib/Renderers/MediaWikiRenderer.py<gh_stars>100-1000
from .base_renderer import *
import os.path
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
@renderer
class MediaWikiRenderer(CommandlineRenderer):
def __init__(self):
super(MediaWikiRend... |
Python/Battery_Full_Charged_Notifier/battery_full_charged_notifier.pyw | iamakkkhil/Rotten-Scripts | 1,127 | 12781364 | import psutil #Library to get System details
import time
import pyttsx3 # Library for text to speech Offline
from win10toast import ToastNotifier # also need to install win32api (This is for Notifications)
import threading # To make notification and speech work at same time
toaster = ToastNotifier()
x=pyttsx3.init()
x... |
A1014280203/7/7.py | saurabh896/python-1 | 3,976 | 12781369 | import os
code_lines = list()
notation_lines = list()
blank_lines = list()
def process_file(filename):
global code_lines
global notation_lines
global blank_lines
with open(filename, 'r') as file:
for line in file.readlines():
_line = line.strip()
if not _... |
users/models.py | hrbhat/twissandra | 308 | 12781383 | # Nope, we're using Cassandra :) |
ci/release.py | steve-louis/mist-ce | 778 | 12781387 | <gh_stars>100-1000
#!/usr/bin/env python
import os
import sys
import hashlib
import argparse
import magic
import requests
def main():
args = parse_args()
request = Client(args.owner, args.repo, args.token)
update_release(
request, args.tag, msg=args.msg, files=args.files,
prerelease=args... |
build/lib/jet_django/__init__.py | lukejamison/jet-dasboard | 193 | 12781388 | VERSION = '0.0.1'
default_app_config = 'jet_django.apps.JetDjangoConfig'
|
tests/suite/test_healthcheck_uri.py | snebel29/kubernetes-ingress | 3,803 | 12781401 | <reponame>snebel29/kubernetes-ingress
import pytest
import requests
from suite.resources_utils import ensure_connection
@pytest.mark.ingresses
@pytest.mark.parametrize('ingress_controller, expected_responses',
[
pytest.param({"extra_args": ["-health-status=true",... |
kino-webhook/handler.py | DongjunLee/kino-bot | 109 | 12781404 | import arrow
import json
import requests
def kanban_webhook(event, context):
input_body = json.loads(event['body'])
print(event['body'])
action = input_body["action"]
action_type = action["type"]
if action_type == "createCard":
list_name, card_name = get_create_card(action["data"])
... |
tests/unittests/load_functions/outside_main_code_in_main/main.py | anandagopal6/azure-functions-python-worker | 277 | 12781426 | <reponame>anandagopal6/azure-functions-python-worker
# This function app is to ensure the code outside main() function
# should only get loaded once in __init__.py
from .count import invoke, get_invoke_count, reset_count
invoke()
def main(req):
count = get_invoke_count()
reset_count()
return f'executed... |
layers.py | gemilepus/ShadeSketch | 313 | 12781430 | """
ShadeSketch
https://github.com/qyzdao/ShadeSketch
Learning to Shadow Hand-drawn Sketches
<NAME>, <NAME>, <NAME>
Copyright (C) 2020 The respective authors and Project HAT. All rights reserved.
Licensed under MIT license.
"""
import tensorflow as tf
# import keras
keras = tf.keras
K = keras.backend
Layer = keras.... |
smartmin/perms.py | nickhargreaves/smartmin | 166 | 12781445 | from django.contrib.auth.models import Permission
def assign_perm(perm, group):
"""
Assigns a permission to a group
"""
if not isinstance(perm, Permission):
try:
app_label, codename = perm.split('.', 1)
except ValueError:
raise ValueError("For global permissions... |
hummingbot/connector/exchange/huobi/huobi_api_order_book_data_source.py | BGTCapital/hummingbot | 3,027 | 12781455 | #!/usr/bin/env python
import asyncio
import logging
import hummingbot.connector.exchange.huobi.huobi_constants as CONSTANTS
from collections import defaultdict
from typing import (
Any,
Dict,
List,
Optional,
)
from hummingbot.connector.exchange.huobi.huobi_order_book import HuobiOrderBook
from hum... |
acora/__init__.py | scoder/acora | 209 | 12781492 | """\
Acora - a multi-keyword search engine based on Aho-Corasick trees.
Usage::
>>> from acora import AcoraBuilder
Collect some keywords::
>>> builder = AcoraBuilder('ab', 'bc', 'de')
>>> builder.add('a', 'b')
Generate the Acora search engine::
>>> ac = builder.build()
Search a string for all occ... |
tests/model_test.py | gaganchhabra/appkernel | 156 | 12781516 | import json
from decimal import Decimal
from pymongo import MongoClient
from appkernel import PropertyRequiredException
from appkernel.configuration import config
from appkernel.repository import mongo_type_converter_to_dict, mongo_type_converter_from_dict
from .utils import *
import pytest
from jsonschema import valid... |
study/vanilla/models.py | NunoEdgarGFlowHub/wavetorch | 470 | 12781536 | import torch
import torch.nn as nn
from torch.nn import functional as F
class CustomRNN(nn.Module):
def __init__(self, input_size, output_size, hidden_size, batch_first=True, W_scale=1e-1, f_hidden=None):
super(CustomRNN, self).__init__()
self.input_size = input_size
self.output_size = out... |
office-plugin/windows-office/program/wizards/common/Properties.py | jerrykcode/kkFileView | 6,660 | 12781554 | #
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This file incorporates work covered by the following license noti... |
indicnlp/transliterate/unicode_transliterate.py | shubham303/indic_nlp_library | 432 | 12781564 | <reponame>shubham303/indic_nlp_library
#
# Copyright (c) 2013-present, <NAME>
# All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
#Program for text written in one Indic script to another based on Unicode mapping... |
tensorflow/python/tools/module_util.py | KosingZhu/tensorflow | 190,993 | 12781575 | # Copyright 2019 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/qos/conftest.py | dmytroxshevchuk/sonic-mgmt | 132 | 12781592 | <gh_stars>100-1000
from .args.qos_sai_args import add_qos_sai_args
from .args.buffer_args import add_dynamic_buffer_calculation_args
# QoS pytest arguments
def pytest_addoption(parser):
'''
Adds option to QoS pytest
Args:
parser: pytest parser object
Returns:
None
... |
scripts/automation/trex_control_plane/stf/trex_stf_lib/trex_daemon_server.py | timgates42/trex-core | 956 | 12781603 | #!/usr/bin/python
import outer_packages
import daemon
from trex_server import do_main_program, trex_parser
import CCustomLogger
import logging
import time
import sys
import os, errno
import grp
import signal
from daemon import runner
from extended_daemon_runner import ExtendedDaemonRunner
import lockfile
import errno... |
streaming-mqtt/python-tests/tests.py | JacopoCastello/bahir | 337 | 12781610 | <gh_stars>100-1000
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licens... |
desktop/core/ext-py/cx_Oracle-6.4.1/samples/tutorial/query_one.py | yetsun/hue | 5,079 | 12781613 | #------------------------------------------------------------------------------
# query_one.py (Section 3.2)
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Copyright 2017, 2018, Oracle and/or its affiliat... |
running_modes/reinforcement_learning/core_reinforcement_learning.py | lilleswing/Reinvent-1 | 183 | 12781637 | <gh_stars>100-1000
import time
import numpy as np
import torch
from reinvent_chemistry.utils import get_indices_of_unique_smiles
from reinvent_models.lib_invent.enums.generative_model_regime import GenerativeModelRegimeEnum
from reinvent_models.model_factory.configurations.model_configuration import ModelConfiguration... |
pixelssl/task_template/__init__.py | charlesCXK/PixelSSL | 223 | 12781641 | from . import func as func_template
from . import data as data_template
from . import model as model_template
from . import criterion as criterion_template
from . import proxy as proxy_template
__all__ = [
'func_template',
'data_template',
'model_template',
'criterion_template',
'proxy_template',
] |
Python3/1302.py | rakhi2001/ecom7 | 854 | 12781662 | <gh_stars>100-1000
__________________________________________________________________________________________________
sample 72 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:... |
HOG-Features/scikithog.py | saneravi/ML_Stuff | 209 | 12781674 | #!/usr/bin/env python
"""Calculate HOG features for an image"""
import os
import matplotlib.pyplot as plt
from hog_features import image2pixelarray
from skimage import exposure
from skimage.feature import hog
def main(filename):
"""
Orchestrate the HOG feature calculation
Parameters
----------
... |
cactus/listener/__init__.py | danielchasehooper/Cactus | 1,048 | 12781766 | <filename>cactus/listener/__init__.py
import logging
from cactus.listener.polling import PollingListener
logger = logging.getLogger(__name__)
try:
from cactus.listener.mac import FSEventsListener as Listener
except (ImportError, OSError):
logger.debug("Failed to load FSEventsListener, falling back to Poll... |
python/RawNet2/dataloader.py | ishine/RawNet | 199 | 12781810 | <reponame>ishine/RawNet<gh_stars>100-1000
import numpy as np
import soundfile as sf
from torch.utils import data
class Dataset_VoxCeleb2(data.Dataset):
def __init__(self, list_IDs, base_dir, nb_samp = 0, labels = {}, cut = True, return_label = True, norm_scale = True):
'''
self.list_IDs : list of strings (each s... |
website/discovery/views.py | gaybro8777/osf.io | 628 | 12781812 | <filename>website/discovery/views.py
from framework.flask import redirect
def redirect_activity_to_search(**kwargs):
return redirect('/search/')
|
lib/models/mixformer/__init__.py | SangbumChoi/MixFormer | 103 | 12781829 | from .mixformer import build_mixformer
from .mixformer_online import build_mixformer_online_score |
interpretation/deepseismic_interpretation/dutchf3/tests/test_dataloaders.py | elmajdma/seismic-deeplearning | 270 | 12781849 | <filename>interpretation/deepseismic_interpretation/dutchf3/tests/test_dataloaders.py<gh_stars>100-1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Tests for TrainLoader and TestLoader classes when overriding the file names of the seismic and label data.
"""
import... |
ISMLnextGen/dynamicCoro.py | Ravenclaw-OIer/ISML_auto_voter | 128 | 12781851 | import asyncio
from threading import Thread
async def production_task():
i = 0
while 1:
# 将consumption这个协程每秒注册一个到运行在线程中的循环,thread_loop每秒会获得一个一直打印i的无限循环任务
asyncio.run_coroutine_threadsafe(consumption(i),
thread_loop) # 注意:run_coroutine_threadsafe... |
tf_quant_finance/math/qmc/__init__.py | slowy07/tf-quant-finance | 3,138 | 12781861 | # Lint as: python3
# Copyright 2021 Google LLC
#
# 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 agr... |
bo/pp/pp_gp_my_distmat.py | ZachZhu7/banana-git | 167 | 12781865 | <gh_stars>100-1000
"""
Classes for GP models without any PP backend, using a given distance matrix.
"""
from argparse import Namespace
import time
import copy
import numpy as np
from scipy.spatial.distance import cdist
from bo.pp.pp_core import DiscPP
from bo.pp.gp.gp_utils import kern_exp_quad, kern_matern32, \
ge... |
python/python-core/datetimes.py | josephobonyo/sigma_coding_youtube | 893 | 12781892 | # import our libraries
import time
import datetime
# get today's date
today = date.today()
print(today)
# create a custom date
future_date = date(2020, 1, 31)
print(future_date)
# let's create a time stamp
time_stamp = time.time()
print(time_stamp)
# create a date from a timestamp
date_stamp = date.fromtimestamp(ti... |
sample_project/env/lib/python3.9/site-packages/fontTools/misc/roundTools.py | Istiakmorsalin/ML-Data-Science | 38,667 | 12781897 | """
Various round-to-integer helpers.
"""
import math
import functools
import logging
log = logging.getLogger(__name__)
__all__ = [
"noRound",
"otRound",
"maybeRound",
"roundFunc",
]
def noRound(value):
return value
def otRound(value):
"""Round float value to nearest integer towards ``+Infinity``.
The Open... |
office365/sharepoint/tenant/administration/sharing_capabilities.py | wreiner/Office365-REST-Python-Client | 544 | 12781902 | class SharingCapabilities:
def __init__(self):
pass
Disabled = 0
ExternalUserSharingOnly = 1
ExternalUserAndGuestSharing = 2
ExistingExternalUserSharingOnly = 3
|
Classification/LibLinear/src/test/scripts/generate_test_data.py | em3ndez/tribuo | 1,091 | 12781942 | # Copyright (c) 2015-2020, Oracle and/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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
parsers/api_check.py | Bassem95/Test26 | 105 | 12781950 | <reponame>Bassem95/Test26
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""
"""
import requests
import time
from raven import Client
client = Client(
'https://aee9ceb609b549fe8a85339e69c74150:8604fd36d8b04fbd9a70a81bdada5cdf@sentry.io/1223891')
key = "<KEY>"
def check_api(word):
query_string = { 'api-key': key, ... |
hydrachain/examples/native/fungible/test_fungible_contract.py | bts/hydrachain | 406 | 12781954 | from ethereum import tester
import hydrachain.native_contracts as nc
from fungible_contract import Fungible, Transfer, Approval
import ethereum.slogging as slogging
log = slogging.get_logger('test.fungible')
def test_fungible_instance():
state = tester.state()
creator_address = tester.a0
creator_key = tes... |
bpy_utilities/material_loader/shaders/source1_shaders/refract.py | tltneon/SourceIO | 199 | 12781969 | <reponame>tltneon/SourceIO<filename>bpy_utilities/material_loader/shaders/source1_shaders/refract.py
import numpy as np
from typing import Iterable
from ...shader_base import Nodes
from ..source1_shader_base import Source1ShaderBase
class Refract(Source1ShaderBase):
SHADER: str = 'refract'
@property
def... |
python_modules/libraries/dagster-papertrail/dagster_papertrail/loggers.py | rpatil524/dagster | 4,606 | 12781980 | <gh_stars>1000+
import logging
import socket
from dagster import Field, IntSource, StringSource, logger
class ContextFilter(logging.Filter):
hostname = socket.gethostname()
def filter(self, record):
record.hostname = ContextFilter.hostname
return True
@logger(
{
"log_level": Fi... |
angr/knowledge_plugins/patches.py | Kyle-Kyle/angr | 6,132 | 12781988 | from typing import Optional, List, Dict
from cle.address_translator import AddressTranslator
from sortedcontainers import SortedDict
from .plugin import KnowledgeBasePlugin
# TODO: Serializable
class Patch:
def __init__(self, addr, new_bytes, comment: Optional[str]=None):
self.addr = addr
self.n... |
fuzzing/kernel/syzkaller-configs/generate_config.py | DBGilles/retrowrite | 478 | 12781992 | <reponame>DBGilles/retrowrite<gh_stars>100-1000
#!/usr/bin/python3
import argparse
import json
import os
def main():
parser = argparse.ArgumentParser(
description='Generate a configuration file for syzkaller')
parser.add_argument('--workdir', help='workdir for syzkaller', required=True)
parser... |
lectures/solutions/tile_rectify.py | ritamonteiroo/scikit | 453 | 12782008 | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from skimage import transform
from skimage.transform import estimate_transform
source = np.array([(129, 72),
(302, 76),
(90, 185),
(326, 193)])
target = np.array([[0, 0... |
python/fleetx/dataset/ctr_data_generator.py | hutuxian/FleetX | 170 | 12782026 | <filename>python/fleetx/dataset/ctr_data_generator.py
#!/usr/bin/python
# Copyright (c) 2019 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
#
# ... |
solutions/problem_108.py | ksvr444/daily-coding-problem | 1,921 | 12782034 | def can_shift(target, string):
return \
target and string and \
len(target) == len(string) and \
string in target * 2
assert can_shift("abcde", "cdeab")
assert not can_shift("abc", "acb")
|
src/amuse/ext/cloud.py | rknop/amuse | 131 | 12782075 | <reponame>rknop/amuse<filename>src/amuse/ext/cloud.py<gh_stars>100-1000
import inspect
import numpy
from amuse.units import generic_unit_system
from amuse import datamodel
def fill_grid_with_cloud_and_medium(
grid,
center = None,
radius = None,
rho_medium = 1.0 | generic_unit_system.m... |
zkstark/quadratic_prover_test.py | kevaundray/research | 1,351 | 12782116 | import quadratic_provers as q
data = q.eval_across_field([1, 2, 3, 4], 11)
qproof = q.mk_quadratic_proof(data, 4, 11)
assert q.check_quadratic_proof(data, qproof, 4, 5, 11)
data2 = q.eval_across_field(range(36), 97)
cproof = q.mk_column_proof(data2, 36, 97)
assert q.check_column_proof(data2, cproof, 36, 10, 97)
|
fairseq/modules/multibranch.py | ishine/lite-transformer | 543 | 12782205 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from . import MultiheadAttention
class MultiBranch(nn.Module):
def __init__(self, branches, embed_dim_list):
super().__init__()
self.branches = nn.ModuleList(branches)
self.embed_dim_list = embed_dim_lis... |
VSR/DataLoader/Dataset.py | Kadantte/VideoSuperResolution | 1,447 | 12782238 | <reponame>Kadantte/VideoSuperResolution
# Copyright (c) 2017-2020 <NAME>.
# Author: <NAME>
# Email: <EMAIL>
# Update: 2020 - 2 - 7
import re
from concurrent import futures
from pathlib import Path
import copy
import yaml
from .VirtualFile import ImageFile, RawFile
from ..Util import Config, to_list
try:
from ... |
tests/casefiles/toplevel_extracode.py | ardovm/wxGlade | 225 | 12782258 | <reponame>ardovm/wxGlade
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade
#
import wx
# begin wxGlade: dependencies
# end wxGlade
# begin wxGlade: extracode
# frame extra code
# dialog extra code
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxG... |
utils/utils.py | luowensheng/MCN | 130 | 12782272 | """Miscellaneous utility functions."""
from functools import reduce
from PIL import Image
import numpy as np
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
import spacy
import re
import cv2
import time
from keras_bert.tokenizer import Tokenizer
from keras_bert.loader import load_trained_model_from_checkpoint, l... |
saleor/shipping/utils.py | fairhopeweb/saleor | 15,337 | 12782301 | <gh_stars>1000+
from typing import TYPE_CHECKING, Optional
from django_countries import countries
from .interface import ShippingMethodData
if TYPE_CHECKING:
from .models import ShippingMethod
def default_shipping_zone_exists(zone_pk=None):
from .models import ShippingZone
return ShippingZone.objects.... |
salt/modules/mod_random.py | tomdoherty/salt | 9,425 | 12782321 | <filename>salt/modules/mod_random.py
"""
Provides access to randomness generators.
=========================================
.. versionadded:: 2014.7.0
"""
import base64
import hashlib
import random
import salt.utils.pycrypto
from salt.exceptions import SaltInvocationError
ALGORITHMS_ATTR_NAME = "algorithms_guaran... |
tests/r/test_friendship.py | hajime9652/observations | 199 | 12782442 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.friendship import friendship
def test_friendship():
"""Test module friendship.py by downloading
friendship.csv and testing shape of
extrac... |
DS&Algo Programs in Python/inserting_heap.py | prathimacode-hub/HacktoberFest-2020 | 386 | 12782452 | <reponame>prathimacode-hub/HacktoberFest-2020
import heapq
H = [21,1,45,78,3,5]
# Covert to a heap
heapq.heapify(H)
print(H)
# Add element
heapq.heappush(H,8)
print(H) |
Scripts/sims4communitylib/utils/sims/common_buff_utils.py | ColonolNutty/Sims4CommunityLibrary | 118 | 12782469 | """
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from typing import Union, List, Tuple, Iterator
from buffs... |
tests/recipes/test_libffi.py | syrykh/python-for-android | 6,278 | 12782529 | import unittest
from tests.recipes.recipe_lib_test import BaseTestForMakeRecipe
class TestLibffiRecipe(BaseTestForMakeRecipe, unittest.TestCase):
"""
An unittest for recipe :mod:`~pythonforandroid.recipes.libffi`
"""
recipe_name = "libffi"
sh_command_calls = ["./autogen.sh", "autoreconf", "./confi... |
examples/demo_purge.py | shirui-japina/tensorboardX | 5,378 | 12782537 | from time import sleep
from tensorboardX import SummaryWriter
with SummaryWriter(logdir='runs/purge') as w:
for i in range(100):
w.add_scalar('purgetest', i, i)
sleep(1.0)
with SummaryWriter(logdir='runs/purge', purge_step=42) as w:
# event 42~99 are removed (inclusively)
for i in range(42, 100):... |
asset/test.py | 745184532/cmdb | 251 | 12782542 | <reponame>745184532/cmdb
import time
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) |
quspin/basis/basis_1d/_check_1d_symm.py | anton-buyskikh/QuSpin | 195 | 12782575 | <gh_stars>100-1000
from __future__ import print_function, division
import warnings
def flip_sublat(opstr,indx,lat=0):
sign = 1
opstr = [str(s) for s in opstr]
for s,i,j in zip(opstr,indx,range(len(indx))):
if ((i % 2) == (lat % 2)):
if (s in ['z','y']):
sign *= -1
elif (s == "+"):
opstr[j] = '-... |
asana/resources/project_memberships.py | FiyaFly/python-asana | 266 | 12782626 | <filename>asana/resources/project_memberships.py
from .gen.project_memberships import _ProjectMemberships
class ProjectMemberships(_ProjectMemberships):
"""Project Memberships resource"""
def find_by_project(self, project, params={}, **options):
"""Returns the compact project membership records for t... |
amlb/utils/serialization.py | PGijsbers/automlbenchmark | 282 | 12782644 | <filename>amlb/utils/serialization.py
import logging
import math
import os
import pickle
import re
from typing import Optional
from .core import Namespace as ns, json_dump, json_load
from .process import profile
log = logging.getLogger(__name__)
def _import_data_libraries():
try:
import numpy as np
... |
lib/galaxy/job_metrics/formatting.py | rikeshi/galaxy | 1,085 | 12782656 | <reponame>rikeshi/galaxy
"""Utilities related to formatting job metrics for human consumption."""
class JobMetricFormatter:
"""Format job metric key-value pairs for human consumption in Web UI."""
def format(self, key, value):
return (str(key), str(value))
def seconds_to_str(value):
"""Convert ... |
aliyun-python-sdk-nlp-automl/aliyunsdknlp_automl/__init__.py | yndu13/aliyun-openapi-python-sdk | 1,001 | 12782660 | __version__ = '0.0.9' |
sdk/attestation/azure-security-attestation/tests/preparers_async.py | rsdoherty/azure-sdk-for-python | 2,728 | 12782663 | <filename>sdk/attestation/azure-security-attestation/tests/preparers_async.py<gh_stars>1000+
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
... |
mrec/evaluation/__init__.py | imall100/mrec | 392 | 12782669 | class Evaluator(object):
"""
Compute metrics for recommendations that have been written to file.
Parameters
----------
compute_metrics : function(list,list)
The evaluation function which should accept two lists of predicted
and actual item indices.
max_items : int
The nu... |
Data Structures/Linked Lists/Singly Linked List/Single-linked-list-operations.py | siddhi-244/CompetitiveProgrammingQuestionBank | 931 | 12782676 | # A pythom program for all operations performed on singly linked-list.
# Time-Complexity = O(n)
# Space-Complexity = O(n)
class Node:
def __init__(self, data=None, next=None): # Creation of Node
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None ... |
opennre/tokenization/word_piece_tokenizer.py | WinterSoHot/OpenNRE | 3,284 | 12782735 | <filename>opennre/tokenization/word_piece_tokenizer.py
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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.... |
PyEngine3D/Utilities/Config.py | ubuntunux/PyEngine3D | 121 | 12782761 | <reponame>ubuntunux/PyEngine3D<gh_stars>100-1000
import os
import configparser
import traceback
from . import Logger
# util class
class Empty:
pass
def evaluation(value):
# find value type
try:
evalValue = eval(value)
if type(evalValue) in [int, float, list, tuple, dict]:
re... |
test/binaries/foo_v1.py | drmikecrowe/cod | 405 | 12782809 | #!/usr/bin/env python3
"""
Usage: foo [OPTION]...
--foo1 useful option foo
--bar1 useful option bar
"""
import sys
if __name__ == "__main__":
print(__doc__, file=sys.stderr)
|
tests/integration/helper.py | covx/graypy_v6 | 181 | 12782811 | <filename>tests/integration/helper.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""helper functions for testing graypy with a local Graylog instance"""
from time import sleep
from uuid import uuid4
import requests
def get_unique_message():
return str(uuid4())
DEFAULT_FIELDS = [
"message",
"full_m... |
tests/test_installation_commands.py | figufema/TesteClone | 1,521 | 12782823 | # -*- coding: utf-8 -*-
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
sfn-log-export/src/functions/export_status_check/index.py | Domt301/serverless-patterns | 883 | 12782875 | <gh_stars>100-1000
import boto3
log_client = boto3.client('logs')
def handler(event, context):
task_id = event['taskId']
result = log_client.describe_export_tasks(taskId=task_id)
# per documentation, only one export can run at a time per account,
# therefore ensure none are running in this account
... |
scripts/gen_chainercv_test.py | disktnk/chainer-compiler | 116 | 12782999 | <reponame>disktnk/chainer-compiler
"""Tests for ChainerCV related custom ops."""
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
import onnx
import onnx_script
import test_case
_has_chnainercv = True
try:
import chainercv_rpn
except ImportError:
_has_chnainercv = F... |
events/migrations/0001_initial.py | Akash1S/meethub | 428 | 12783016 | # Generated by Django 2.0.4 on 2018-04-21 15:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
packs/reamaze/actions/article_create.py | userlocalhost2000/st2contrib | 164 | 12783028 | <gh_stars>100-1000
from lib.actions import BaseAction
class ArticleCreate(BaseAction):
def run(self, title, body, topic=None, status=0):
if topic:
topic = self._convert_slug(topic)
path = '/topics/%s/articles' % topic
else:
path = '/articles'
payload = s... |
kitsune/questions/urls_api.py | AndrewDVXI/kitsune | 929 | 12783040 | from rest_framework import routers
from kitsune.questions.api import QuestionViewSet, AnswerViewSet
router = routers.SimpleRouter()
router.register(r"question", QuestionViewSet)
router.register(r"answer", AnswerViewSet)
urlpatterns = router.urls
|
desktop/core/ext-py/urllib3-1.25.8/test/appengine/test_urlfetch.py | yetsun/hue | 5,079 | 12783052 | <reponame>yetsun/hue
"""These tests ensure that when running in App Engine standard with the
App Engine sandbox enabled that urllib3 appropriately uses the App
Engine-patched version of httplib to make requests."""
import httplib
import StringIO
from mock import patch
import pytest
from ..test_no_ssl import TestWith... |
RecoEcal/EgammaClusterProducers/python/egammaRechitFilter_cfi.py | ckamtsikis/cmssw | 852 | 12783079 | <filename>RecoEcal/EgammaClusterProducers/python/egammaRechitFilter_cfi.py
import FWCore.ParameterSet.Config as cms
#
# module for filtering of rechits. user provides noise threshold in GeV units
# Author: <NAME>, University of Rome & INFN
#
rechitFilter = cms.EDProducer("RecHitFilter",
noiseEnergyThreshold = cm... |
tools/launch_tensorboard.py | isn-dev/imagenet18 | 716 | 12783081 | <filename>tools/launch_tensorboard.py
#!/usr/bin/env python
# Usage:
# ./launch_tensorboard.py
#
# This will launch r5.large machine on AWS with tensoboard, and print URL
# in the console
import ncluster
ncluster.use_aws()
task = ncluster.make_task('tensorboard',
instance_type='r5.large',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.