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 |
|---|---|---|---|---|
host/greatfet/interfaces/jtag.py | grvvy/greatfet | 328 | 12743196 | #
# This file is part of GreatFET
#
from __future__ import print_function
import sys
from warnings import warn
from ..interface import GreatFETInterface
from ..support.bits import bits
from ..protocol.jtag_svf import SVFParser, SVFEventHandler
class JTAGPatternError(IOError):
""" Class for errors that come fro... |
zulip/zulip/send.py | dimisjim/python-zulip-api | 351 | 12743223 | #!/usr/bin/env python3
# zulip-send -- Sends a message to the specified recipients.
import argparse
import logging
import sys
from typing import Any, Dict
import zulip
logging.basicConfig()
log = logging.getLogger("zulip-send")
def do_send_message(client: zulip.Client, message_data: Dict[str, Any]) -> bool:
"... |
src/stage1/data_generator.py | gathierry/FashionAI-KeyPointsDetectionOfApparel | 174 | 12743226 | <reponame>gathierry/FashionAI-KeyPointsDetectionOfApparel
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
from stage1.label_encoder import DataEncoder
class DataGenerator(Dataset):
def __init__(self, config, data, phase='train'):
self.phase = phase
self.... |
scripts/emu/simple_ipv6.py | timgates42/trex-core | 956 | 12743237 | from trex.emu.api import *
import argparse
import get_args
class Prof1():
def __init__(self):
self.mac = Mac('00:00:00:70:00:01')
self.def_ns_plugs = {'ipv6' : {'dmac':self.mac.V()}}
self.def_c_plugs = None
def create_profile(self, ns_size, clients_size):
ns_list = []
... |
metrics/hybridqa/evaluator.py | HKUNLP/UnifiedSKG | 191 | 12743272 | import re
import collections
import string
# copy from https://github.com/wenhuchen/HybridQA/blob/master/evaluate_script.py
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
regex = re.compile(r"\b(a|an|the)\b", re.... |
pxr/usdImaging/bin/testusdview/testenv/testUsdviewDeactivate/testUsdviewDeactivate.py | DougRogers-DigitalFish/USD | 3,680 | 12743296 | #!/pxrpythonsubst
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
lib/models/modules/projection.py | littleSunlxy/contrastive-seg-lin | 398 | 12743304 | import torch
import torch.nn as nn
import torch.nn.functional as F
from lib.models.tools.module_helper import ModuleHelper
from lib.utils.tools.logger import Logger as Log
class ProjectionHead(nn.Module):
def __init__(self, dim_in, proj_dim=256, proj='convmlp', bn_type='torchsyncbn'):
super(ProjectionHead... |
deepspeaker/embedding.py | ishine/Cross-Speaker-Emotion-Transfer | 147 | 12743308 | import numpy as np
from deepspeaker.audio_ds import read_mfcc
from deepspeaker.batcher import sample_from_mfcc
from deepspeaker.constants import SAMPLE_RATE, NUM_FRAMES, WIN_LENGTH
from deepspeaker.conv_models import DeepSpeakerModel
import tensorflow as tf
def build_model(ckpt_path):
model = DeepSpeakerModel()
... |
airflow/plugins_manager.py | ChaseKnowlden/airflow | 15,947 | 12743325 | #
# 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
# "License"); you may not... |
src/gausskernel/dbmind/tools/xtuner/tuner/algorithms/rl_agent.py | opengauss-mirror/openGauss-graph | 360 | 12743329 | """
Copyright (c) 2020 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WI... |
adaptive/learner/sequence_learner.py | Davide-sd/adaptive | 720 | 12743344 | from copy import copy
import cloudpickle
from sortedcontainers import SortedDict, SortedSet
from adaptive.learner.base_learner import BaseLearner
class _IgnoreFirstArgument:
"""Remove the first argument from the call signature.
The SequenceLearner's function receives a tuple ``(index, point)``
but the ... |
tests/models/test_models_utils.py | rohanshad/pycox | 449 | 12743360 | import pytest
import numpy as np
import torch
from pycox.models.utils import pad_col, make_subgrid, cumsum_reverse
@pytest.mark.parametrize('val', [0, 1, 5])
def test_pad_col_start(val):
x = torch.ones((2, 3))
x_pad = pad_col(x, val, where='start')
pad = torch.ones(2, 1) * val
assert (x_pad == torch.ca... |
mmdet/core/loss/losses.py | escapist2019/AugFPN | 144 | 12743378 | <filename>mmdet/core/loss/losses.py
# TODO merge naive and weighted loss.
import torch
import torch.nn.functional as F
from ..bbox import bbox_overlaps
def weighted_nll_loss(pred, label, weight, avg_factor=None):
if avg_factor is None:
avg_factor = max(torch.sum(weight > 0).float().item(), 1.)
raw = F.... |
TextGenerator/core/element/TextImg.py | yinhaoxs/CharacterRecognition-CRNN | 166 | 12743433 | <gh_stars>100-1000
import cv2
from typing import List
from core.element.BaseImg import BaseImg
from core.element.CharImg import CharImg
from PIL import Image, ImageFont, ImageDraw
import os
import numpy as np
import json
from utils import time_util as tu
import math
import traceback
from utils import log
TYPE_ORIENTAT... |
tushare/stock/indictor.py | lixianjian/tushare | 12,490 | 12743459 | # -*- coding:utf-8 -*-
"""
股票技术指标接口
Created on 2018/05/26
@author: <NAME>
@group : **
@contact: <EMAIL>
"""
def ma(data, n=10, val_name="close"):
import numpy as np
'''
移动平均线 Moving Average
Parameters
------
data:pandas.DataFrame
通过 get_h_data 取得的股票数据
n:int
... |
pyatv/protocols/mrp/protobuf/NowPlayingClient_pb2.py | Jacobs4/pyatv | 532 | 12743481 | <reponame>Jacobs4/pyatv
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pyatv/protocols/mrp/protobuf/NowPlayingClient.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google... |
ansible/roles/test/files/ptftests/fg_ecmp_test.py | lolyu/sonic-mgmt | 132 | 12743489 | <reponame>lolyu/sonic-mgmt
# PTF test contains the test cases for fine grained ecmp, the scenarios of test are as follows:
# create_flows: Sends NUM_FLOWS flows with varying src_Ip and creates a tuple to port map
# initial_hash_check: Checks the the flows from create_flows still end up at the same port
# hash_check_war... |
jesse/models/__init__.py | noenfugler/jesse | 3,999 | 12743492 | <reponame>noenfugler/jesse
from .Candle import Candle
from .CompletedTrade import CompletedTrade
from .Exchange import Exchange
from .FuturesExchange import FuturesExchange
from .Order import Order
from .Position import Position
from .Route import Route
from .SpotExchange import SpotExchange
from .Ticker import Ticker
... |
lldb/third_party/Python/module/unittest2/unittest2/collector.py | medismailben/llvm-project | 2,338 | 12743511 | <gh_stars>1000+
import os
import sys
from unittest2.loader import defaultTestLoader
def collector():
# import __main__ triggers code re-execution
__main__ = sys.modules['__main__']
setupDir = os.path.abspath(os.path.dirname(__main__.__file__))
return defaultTestLoader.discover(setupDir)
|
Python/antivirus_type_utility.py | PushpneetSingh/Hello-world | 1,428 | 12743518 | <reponame>PushpneetSingh/Hello-world
import os
import hashlib
import time
from sys import exit
dirName=os.path.dirname(os.path.realpath(__file__))
yesAnswers=['yes','Yes','YES','Y','y','']
noAnswers=['No','no','n','N','NO']
ENILfilePath=''
def getListOfFiles(dirName):
# create a list of file and sub directories
... |
python_web/models/post.py | LouisYZK/Frodo | 123 | 12743524 | <filename>python_web/models/post.py
import re
import ast
import types
import random
import inspect
from datetime import datetime, timedelta
from aioredis.errors import RedisError
from html.parser import HTMLParser
from sqlalchemy import Column, SmallInteger, String, Integer, Boolean, DateTime
from sqlalchemy.sql import... |
Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/set_extractor_config.py | AhmedLeithy/Recognizers-Text | 688 | 12743545 | <reponame>AhmedLeithy/Recognizers-Text
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Pattern
from recognizers_text import RegExpUtility
from ...resources.chinese_date_time import ChineseDateTime
from ..base_set import SetExtractorConfiguration
from... |
rasa/cli/run.py | jeanveau/rasa_core | 2,433 | 12743562 | <gh_stars>1000+
import argparse
import logging
import os
import shutil
from typing import List
from rasa import model
from rasa.cli.default_arguments import add_model_param
from rasa.cli.utils import get_validated_path
from rasa.constants import (
DEFAULT_ACTIONS_PATH, DEFAULT_CREDENTIALS_PATH, DEFAULT_ENDPOINTS_P... |
tests/conftest.py | simonvh/genomepy | 112 | 12743568 | """
Global fixtures and functions for pytest
pytest can only share fixtures between modules if they are declared here.
"""
import logging
import os
import pytest
from loguru import logger
import genomepy.providers
from genomepy.providers.base import BaseProvider
from genomepy.providers.ensembl import EnsemblProvider
... |
spleeter/model/__init__.py | au-deps/spleeter | 19,827 | 12743595 | <reponame>au-deps/spleeter
#!/usr/bin/env python
# coding: utf8
""" This package provide an estimator builder as well as model functions. """
import importlib
# pyright: reportMissingImports=false
# pylint: disable=import-error
import tensorflow as tf
from tensorflow.signal import hann_window, inverse_stft, stft
fr... |
third_party/tests/Opentitan/util/dvsim/FlowCfg.py | parzival3/Surelog | 156 | 12743596 | #!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
r"""
Class describing a flow configuration object
"""
import datetime
import logging as log
import pprint
from shutil import which
from .utils impor... |
uncertainties/unumpy/__init__.py | AdityaSavara/uncertainties | 364 | 12743600 | <filename>uncertainties/unumpy/__init__.py
"""
Utilities for NumPy arrays and matrices that contain numbers with
uncertainties.
This package contains:
1) utilities that help with the creation and manipulation of NumPy
arrays and matrices of numbers with uncertainties;
2) generalizations of multiple NumPy functions s... |
nonebot/notice_request.py | remiliacn/nonebot | 1,101 | 12743606 | from typing import List, Optional, Union
from aiocqhttp import Event as CQEvent
from aiocqhttp.bus import EventBus
from . import NoneBot
from .log import logger
from .exceptions import CQHttpError
from .session import BaseSession
from .typing import NoticeHandler_T, RequestHandler_T
class EventHandler:
"""INTE... |
examples/maml_regression/evjang_transforms.py | onlyrico/functorch | 279 | 12743631 | <gh_stars>100-1000
# This example code was modified from https://github.com/ericjang/maml-jax .
#
# The original code comes with the following license:
# https://github.com/ericjang/maml-jax/blob/master/LICENSE
# Copyright <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f... |
kws_streaming/layers/conv1d_transpose.py | deepneuralmachine/google-research | 23,901 | 12743638 | <reponame>deepneuralmachine/google-research
# coding=utf-8
# Copyright 2021 The Google Research 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... |
source/vsm-dashboard/vsm_dashboard/dashboards/vsm/openstackconnect/forms.py | ramkrsna/virtual-storage-manager | 172 | 12743639 |
# Copyright 2014 Intel Corporation, 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 ... |
tests/simple/arith.py | parag-hub/arrayfire-python | 420 | 12743718 | <gh_stars>100-1000
#!/usr/bin/env python
#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
############... |
util/cpt_upgraders/multiple-event-queues.py | hyu-iot/gem5 | 765 | 12743726 | # Add support for multiple event queues
def upgrader(cpt):
cpt.set('Globals', 'numMainEventQueues', '1')
legacy_version = 12
|
alipay/aop/api/domain/ConsumerNotifyIstd.py | antopen/alipay-sdk-python-all | 213 | 12743736 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ConsumerNotifyIstd(object):
def __init__(self):
self._goods_count = None
self._goods_img = None
self._goods_name = None
self._merchant_mobile = None
self._... |
ryu/app/network_awareness/__init__.py | hiArvin/ryu | 269 | 12743755 | <gh_stars>100-1000
"For loading module"
|
tests/test_providers/test_hardware.py | chinghwayu/mimesis | 2,619 | 12743783 | # -*- coding: utf-8 -*-
import re
import pytest
from mimesis import Hardware
from mimesis.data import (
CPU,
CPU_CODENAMES,
CPU_MODEL_CODES,
GENERATION,
GRAPHICS,
HDD_SSD,
MANUFACTURERS,
PHONE_MODELS,
RAM_SIZES,
RAM_TYPES,
RESOLUTIONS,
SCREEN_SIZES,
)
from . import patt... |
openstackclient/compute/v2/server_backup.py | efrat-elimelech/python-openstackclient | 262 | 12743790 | # Copyright 2012-2013 OpenStack Foundation
#
# 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 la... |
hermione/module_templates/__IMPLEMENTED_BASE__/src/ml/analysis/dimensionality_reduction.py | karenstemartins/hermione | 183 | 12743825 | from sklearn.decomposition import FactorAnalysis
from sklearn.decomposition import FastICA
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.decomposition import TruncatedSVD
from sklearn.decomposition import NMF
from sklearn.manifold import Isomap
from sklearn.manifold import MDS
from sklearn.ma... |
alipay/aop/api/domain/KoubeiAdvertCommissionAdvertQueryModel.py | snowxmas/alipay-sdk-python-all | 213 | 12743832 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class KoubeiAdvertCommissionAdvertQueryModel(object):
def __init__(self):
self._identifies = None
self._identify_type = None
@property
def identifies(self):
return self... |
degiro_connector/quotecast/actions/action_subscribe.py | Chavithra/degiro-connector | 107 | 12743836 | # IMPORTATION STANDARD
import requests
import logging
from typing import Optional
# IMPORTATION THIRD PARTY
# IMPORTATION INTERNAL
import degiro_connector.core.constants.urls as urls
from degiro_connector.quotecast.models.quotecast_pb2 import (
Quotecast,
)
from degiro_connector.core.abstracts.abstract_action impo... |
seahub/share/utils.py | samuelduann/seahub | 420 | 12743861 | <filename>seahub/share/utils.py<gh_stars>100-1000
import logging
from seahub.group.utils import is_group_admin
from seahub.constants import PERMISSION_ADMIN, PERMISSION_READ_WRITE, CUSTOM_PERMISSION_PREFIX
from seahub.share.models import ExtraSharePermission, ExtraGroupsSharePermission, CustomSharePermissions
from sea... |
src/lib/pyclbr.py | DTenore/skulpt | 2,671 | 12743865 | import _sk_fail; _sk_fail._("pyclbr")
|
pandas/stats/plm.py | certik/pandas | 652 | 12743867 | <reponame>certik/pandas<gh_stars>100-1000
"""
Linear regression objects for panel data
"""
# pylint: disable-msg=W0231
# pylint: disable-msg=E1101,E1103
from __future__ import division
from pandas.compat import range
from pandas import compat
import warnings
import numpy as np
from pandas.core.panel import Panel
fr... |
sources_non_forked/vim-minimap/autoload/drawille/examples/basic.py | bodhitreestudio/vimrc | 677 | 12743880 | <reponame>bodhitreestudio/vimrc<filename>sources_non_forked/vim-minimap/autoload/drawille/examples/basic.py
from __future__ import print_function
from drawille import Canvas
import math
s = Canvas()
for x in range(1800):
s.set(x/10, math.sin(math.radians(x)) * 10)
print(s.frame())
s.clear()
for x in range(0, ... |
tests/components/media_player/test_async_helpers.py | mtarjoianu/core | 30,023 | 12743888 | <reponame>mtarjoianu/core
"""The tests for the Async Media player helper functions."""
import pytest
import homeassistant.components.media_player as mp
from homeassistant.const import (
STATE_IDLE,
STATE_OFF,
STATE_ON,
STATE_PAUSED,
STATE_PLAYING,
)
class ExtendedMediaPlayer(mp.MediaPlayerEntity)... |
datadog/api/service_level_objectives.py | cclauss/datadogpy | 520 | 12743889 | <gh_stars>100-1000
# Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2015-Present Datadog, Inc
from datadog.util.format import force_to_epoch_seconds
from datadog.... |
cleverhans_v3.1.0/cleverhans/dataset.py | xu-weizhen/cleverhans | 4,333 | 12743899 | <gh_stars>1000+
"""Dataset class for CleverHans
"""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import array
import functools
import gzip
import operator
import os
import struc... |
tests/basics/tuple1.py | LabAixBidouille/micropython | 303 | 12743933 | # basic tuple functionality
x = (1, 2, 3 * 4)
print(x)
try:
x[0] = 4
except TypeError:
print("TypeError")
print(x)
try:
x.append(5)
except AttributeError:
print("AttributeError")
print(x[1:])
print(x[:-1])
print(x[2:3])
print(x + (10, 100, 10000))
|
recipes/Python/66009_Converting_Between_Different_Naming/recipe-66009.py | tdiprima/code | 2,023 | 12743947 | <filename>recipes/Python/66009_Converting_Between_Different_Naming/recipe-66009.py
import re
def cw2us(x): # capwords to underscore notation
return re.sub(r'(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', r"_\g<0>", x).lower()
def mc2us(x): # mixed case to underscore notation
return cw2us(x)
def us2mc(x): # underscor... |
applications/aci-diagram/diagram.py | richardstrnad/acitoolkit | 351 | 12743961 | <filename>applications/aci-diagram/diagram.py<gh_stars>100-1000
#!/usr/bin/env python
from acitoolkit.acitoolkit import *
import pygraphviz as pgv
import sys
import logging
creds = Credentials('apic',
"Generate logical diagrams of a running Cisco ACI Application Policy Infrastructure Controller")
... |
qrcode/LUT.py | cbalfour/python-qrcode | 2,651 | 12743968 | <gh_stars>1000+
# Store all kinds of lookup table.
# # generate rsPoly lookup table.
# from qrcode import base
# def create_bytes(rs_blocks):
# for r in range(len(rs_blocks)):
# dcCount = rs_blocks[r].data_count
# ecCount = rs_blocks[r].total_count - dcCount
# rsPoly = base.Polynomial([1... |
cli/sawtooth_cli/sawset.py | EddyKIL/sawtooth-core | 1,530 | 12743991 | <filename>cli/sawtooth_cli/sawset.py
# Copyright 2017 Intel Corporation
#
# 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 ... |
tests/python/kivaloo/servers.py | Tarsnap/kivaloo | 176 | 12744004 | #!/usr/bin/env python3
""" Launch and organize servers for the python tests. """
import logging
import os
import shutil
import subprocess
import threading
import queue
import psutil
# ### Private constants
_KIVALOO_TEST_DIR = "/tmp/kivaloo-test/"
# - this is relative to TEST_DIR
# - this may be subjected to rm -rf... |
grip/assets.py | botleague-results/grip | 5,502 | 12744008 | from __future__ import print_function, unicode_literals
import errno
import os
import posixpath
import re
import sys
import shutil
from abc import ABCMeta, abstractmethod
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
import requests
from flask import safe_join
from .c... |
samples/python/06.using-cards/bots/rich_cards_bot.py | Aliacf21/BotBuilder-Samples | 1,998 | 12744009 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import MessageFactory, TurnContext
from botbuilder.schema import ChannelAccount
from .dialog_bot import DialogBot
class RichCardsBot(DialogBot):
"""
RichCardsBot prompts a user to select a Rich ... |
catboost/benchmarks/training_speed/plot.py | jochenater/catboost | 6,989 | 12744049 | <reponame>jochenater/catboost
import argparse
import json
import os
import numpy as np
from matplotlib import pyplot as plt
from log_parser import read_results
FONT_DICT = {'fontsize': 20}
FIGURE_SIZE = (10, 5)
def plot_time_per_iter(tracks, figsize=FIGURE_SIZE, title=None, save_path='time_per_iter.png'):
fig ... |
h2o-py/tests/testdir_algos/rulefit/pyunit_titanic_rulefit.py | vishalbelsare/h2o-3 | 6,098 | 12744119 | <reponame>vishalbelsare/h2o-3<gh_stars>1000+
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.rulefit import H2ORuleFitEstimator
def titanic():
df = h2o.import_file(pyunit_utils.locate("smalldata/gbm_test/titanic.csv"),
col_types={'pcla... |
evaluation_matrix.py | gsygsygsy123/SOTA-on-monocular-3D-pose-and-shape-estimation | 183 | 12744126 | import torch
import numpy as np
def mpjpe(predicted, target):
"""
Mean per-joint position error (i.e. mean Euclidean distance),
often referred to as "Protocol #1" in many papers.
"""
assert predicted.shape == target.shape
return torch.mean(torch.norm(predicted - target, dim=len(target.shape)-1)... |
src/accelerate/deepspeed_utils.py | Pandinosaurus/accelerate | 2,313 | 12744133 | <filename>src/accelerate/deepspeed_utils.py<gh_stars>1000+
# Copyright 2021 The HuggingFace Team. 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.apach... |
edu/class0/dataset.py | haribhutanadhu/PaddleViT | 993 | 12744150 | <filename>edu/class0/dataset.py
from paddle.io import Dataset
from paddle.io import DataLoader
from paddle.vision import datasets
from paddle.vision import transforms
def get_transforms(mode='train'):
if mode == 'train':
data_transforms = transforms.Compose([
transforms.RandomCrop(32, padding=... |
generalizationTests/python2_double_curly/src/test.py | IMULMUL/websitesVulnerableToSSTI | 288 | 12744158 | import re
person = "xx{{\"asdasd\"+\"lala\"}} }} {1+1}xxx"
regex = r"{{(.*?)}}"
matches = re.finditer(regex, person, re.MULTILINE)
for matchNum, match in enumerate(matches):
eval_result = eval(match.group(1))
person = person.replace(str(match.group()),str(eval_result))
print(person) |
accounts/forms.py | annevandalfsen/screenbird | 121 | 12744171 | <reponame>annevandalfsen/screenbird<filename>accounts/forms.py
from django.conf import settings
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import get_current_site
from django.core.validators import... |
sdk/python/pulumi_azure/loganalytics/linked_service.py | henriktao/pulumi-azure | 109 | 12744185 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
test cases/unit/68 test env value/test.py | iinuwa/meson | 4,047 | 12744211 | #!/usr/bin/env python3
import os
import sys
assert os.environ['TEST_VAR'] == sys.argv[1]
|
nengo/builder/tests/test_processes.py | gokhanagma/nengo | 762 | 12744229 | <reponame>gokhanagma/nengo<filename>nengo/builder/tests/test_processes.py
import pytest
from nengo.builder.processes import SimProcess
from nengo.builder.tests.test_operator import _test_operator_arg_attributes
def test_simprocess():
argnames = ["process", "input", "output", "t"]
non_signals = ["process"]
... |
src/yggdrasil/cython-0.25.2/tests/run/ass2global.py | fengjixuchui/hydra | 110 | 12744231 | """
>>> getg()
5
>>> setg(42)
>>> getg()
42
"""
g = 5
def setg(a):
global g
g = a
def getg():
return g
class Test(object):
"""
>>> global_in_class
9
>>> Test.global_in_class
Traceback (most recent call last):
AttributeError: type object 'Test' has no attrib... |
venv/Lib/site-packages/jedi/inference/utils.py | ajayiagbebaku/NFL-Model | 4,213 | 12744281 | <reponame>ajayiagbebaku/NFL-Model<filename>venv/Lib/site-packages/jedi/inference/utils.py
""" A universal module with functions / classes without dependencies. """
import functools
import re
import os
_sep = os.path.sep
if os.path.altsep is not None:
_sep += os.path.altsep
_path_re = re.compile(r'(?:\.[^{0}]+|[{0... |
Validation/EcalClusters/test/macro/plotMeanVsET.py | ckamtsikis/cmssw | 852 | 12744286 | import re, sys, os
file = open("output", "r")
lines = file.readlines()
file.close()
variable = []
eta1 = []
eta2 = []
mean = []
error= []
effS = []
for line in lines:
elements = re.split("\t", line)
variable += [elements[1],]
eta1 += [re.split(">", re.split("&&", elements[2])[0])[1],]
eta2 += [... |
pip_audit/_dependency_source/__init__.py | westonsteimel/pip-audit | 447 | 12744294 | <reponame>westonsteimel/pip-audit
"""
Dependency source interfaces and implementations for `pip-audit`.
"""
from .interface import (
DependencyFixError,
DependencyResolver,
DependencyResolverError,
DependencySource,
DependencySourceError,
)
from .pip import PipSource, PipSourceError
from .requireme... |
setup.py | aaltay/apitools | 143 | 12744297 | #!/usr/bin/env python
#
# Copyright 2013 Google 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 ... |
scispacy/base_project_code.py | rajeshkppt/scispacy | 1,139 | 12744317 | <reponame>rajeshkppt/scispacy
from typing import Optional, Callable, Iterable, Iterator
from pathlib import Path
import random
import itertools
import spacy
import warnings
from spacy.training import Corpus, Example
from spacy.language import Language
from scispacy.custom_tokenizer import combined_rule_toke... |
tests/refresh_reference_files.py | hgroll/tikzplotlib | 646 | 12744319 | <filename>tests/refresh_reference_files.py
import argparse
import importlib.util
import pathlib
import matplotlib.pyplot as plt
import tikzplotlib as tpl
def _main():
parser = argparse.ArgumentParser(description="Refresh all reference TeX files.")
parser.parse_args()
this_dir = pathlib.Path(__file__).r... |
adblockparser/__init__.py | rriemann/adblockparser | 162 | 12744332 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .parser import AdblockRules, AdblockRule, AdblockParsingError
|
tests/test_kernels.py | RevanMacQueen/HpBandSter | 546 | 12744339 | <filename>tests/test_kernels.py
import os
import unittest
import numpy as np
#from scipy.integrate import quadrature as quadrature
from scipy.integrate import quad as quadrature
from statsmodels.nonparametric import kernels as sm_kernels
from hpbandster.optimizers.kde import kernels as hp_kernels
import ConfigSp... |
functions/update_weight/update_weight.py | MarkAtwood/aws-lambda-deploy | 121 | 12744367 | <filename>functions/update_weight/update_weight.py<gh_stars>100-1000
"""
Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import boto3
def handler(event, context):
print(event)
weights = event['weights']
func_name = event['function-name']
versi... |
src/keybindings.py | maiki/k3x | 188 | 12744376 | <filename>src/keybindings.py
# keybindings.py
#
# MIT License
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# 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 ... |
exercises/zh/solution_03_16_02.py | Jette16/spacy-course | 2,085 | 12744378 | import spacy
nlp = spacy.load("zh_core_web_sm")
text = (
"在300多年的风雨历程中,历代同仁堂人始终恪守“炮制虽繁必不敢省人工,品味虽贵必不敢减物力”的古训,"
"树立“修合无人见,存心有天知”的自律意识,造就了制药过程中兢兢小心、精益求精的严细精神。"
)
# 关闭tagger和parser
with nlp.disable_pipes("tagger", "parser"):
# 处理文本
doc = nlp(text)
# 打印doc中的实体
print(doc.ents)
|
tests/test_wsgi_spec.py | skrytebane/meinheld | 1,186 | 12744387 | <filename>tests/test_wsgi_spec.py<gh_stars>1000+
# -*- coding: utf-8 -*-
from collections import OrderedDict
import os
import sys
from base import *
import requests
ASSERT_RESPONSE = b"Hello world!"
RESPONSE = [b"Hello ", b"world!"]
class App(BaseApp):
environ = None
def __call__(self, environ, start_respo... |
lightreid/data/datamanager.py | nataliamiccini/light-reid | 296 | 12744405 | <reponame>nataliamiccini/light-reid
"""
@author: wangguanan
@contact: <EMAIL>
"""
import numpy as np
import copy
from PIL import Image
import torch.utils.data as data
from .samplers import PKSampler
class ReIDDataset:
def __init__(self, samples, transform):
self.samples = samples
self.tran... |
CertToESP32.py | berniew/HTTPS-for-Makers | 167 | 12744412 | <reponame>berniew/HTTPS-for-Makers<gh_stars>100-1000
#MIT License(MIT)
# CertToHex.py Version 1.0.0 #
# Copyright(c) 2018 <NAME> #
#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 S... |
autoload/splice.py | mathstuf/vim-splice | 134 | 12744423 | <reponame>mathstuf/vim-splice
import vim, os, sys
# Add the library to the Python path.
for p in vim.eval("&runtimepath").split(','):
plugin_dir = os.path.join(p, "autoload")
if os.path.exists(os.path.join(plugin_dir, "splicelib")):
if plugin_dir not in sys.path:
sys.path.append(plugin_dir)
... |
python/glow/gwas/tests/test_approx_firth.py | bcajes/glow | 214 | 12744438 | from dataclasses import dataclass
import functions as fx
import glow.gwas.log_reg as lr
import glow.gwas.approx_firth as af
import pandas as pd
from nptyping import Float, NDArray
import numpy as np
import pytest
from typing import Any
@dataclass
class TestData:
phenotypes: NDArray[(Any, ), Float]
covariates:... |
custom_components/smartweather/weather.py | briis/smartweather | 112 | 12744443 | """Support for the SmartWeather weather service."""
import logging
from typing import Dict, List
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION,
ATTR_FORECAST_PRECIPITATION_PROBABILITY,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST... |
Src/StdLib/Lib/test/test_setcomps.py | cwensley/ironpython2 | 2,209 | 12744457 | doctests = """
########### Tests mostly copied from test_listcomps.py ############
Test simple loop with conditional
>>> sum({i*i for i in range(100) if i&1 == 1})
166650
Test simple case
>>> {2*y + x + 1 for x in (0,) for y in (1,)}
set([3])
Test simple nesting
>>> list(sorted({(i,j) for i in... |
docker/site/wsgi.py | timgates42/django-leonardo | 102 | 12744460 | <gh_stars>100-1000
#!/usr/bin/env python
import os
import sys
from os.path import abspath, dirname, join, normpath
import django
import django.core.handlers.wsgi
from django.core.management import execute_from_command_line
sys.path.append('/app/site')
sys.path.append('/app/module')
sys.path.append('/app/settings')
... |
lib-other/deterministiclib/svd.py | endolith/Truthcoin | 161 | 12744461 |
# Almost exact translation of the ALGOL SVD algorithm published in
# Numer. Math. 14, 403-420 (1970) by <NAME> and <NAME>
#
# by <NAME>, helicity314-stitch <at> yahoo <dot> com
#
# Pure Python SVD algorithm.
# Input: 2-D list (m by n) with m >= n
# Output: U,W V so that A = U*W*VT
# Note this program returns V not ... |
tests/unit/objects/test_vendor.py | varunbheemaiah/python-quickbooks | 234 | 12744487 | import unittest
from quickbooks import QuickBooks
from quickbooks.objects.vendor import Vendor, ContactInfo
class VendorTests(unittest.TestCase):
def test_unicode(self):
vendor = Vendor()
vendor.DisplayName = "test"
self.assertEquals(str(vendor), "test")
def test_to_ref(self):
... |
src/hca/hcat/mysite/hcat/urls.py | andypohl/kent | 171 | 12744500 | from django.urls import path
from . import views
from . import api
app_name = 'hcat'
urlpatterns = [
path('', views.index, name='index'),
path('project/<int:pk>/', views.ProjectDetailView.as_view(), name='project_detail'),
path('project', views.ProjectListView.as_view(), name='project_list'),
path('pr... |
pytest.py | nanjekyejoannah/pypy | 333 | 12744533 | #!/usr/bin/env python2
# PYTHON_ARGCOMPLETE_OK
"""
pytest: unit and functional testing with Python.
"""
__all__ = [
'main',
'UsageError',
'cmdline',
'hookspec',
'hookimpl',
'__version__',
]
if __name__ == '__main__': # if run as a script or by 'python -m pytest'
# we trigger the below "else... |
pycaption/__init__.py | vpaul-dev/pycaption-github-release-notes | 183 | 12744616 | from .base import (
CaptionConverter, CaptionNode, Caption, CaptionList, CaptionSet,
)
from .dfxp import DFXPWriter, DFXPReader
from .microdvd import MicroDVDReader, MicroDVDWriter
from .sami import SAMIReader, SAMIWriter
from .srt import SRTReader, SRTWriter
from .scc import SCCReader, SCCWriter
from .scc.translat... |
osf/migrations/0136_add_ember_auth_register_waffle_flag.py | gaybro8777/osf.io | 628 | 12744631 | <reponame>gaybro8777/osf.io
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-10-08 13:01
from __future__ import unicode_literals
from django.db import migrations
from osf import features
from osf.utils.migrations import AddWaffleFlags
class Migration(migrations.Migration):
dependencies = [
(... |
data_collection/gazette/spiders/sc_correia_pinto.py | kaiocp/querido-diario | 454 | 12744646 | <filename>data_collection/gazette/spiders/sc_correia_pinto.py
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScCorreiaPintoSpider(FecamGazetteSpider):
name = "sc_correia_pinto"
FECAM_QUERY = "cod_entidade:77"
TERRITORY_ID = "4204558"
|
test/nnUNetV1/network_training/nnUNetTrainer_DiceBD.py | jianhuasong/medical-image-segmentation2 | 2,774 | 12744653 | <filename>test/nnUNetV1/network_training/nnUNetTrainer_DiceBD.py
from nnunet.training.loss_functions.boundary_loss import DC_and_BD_loss
from nnunet.training.network_training.nnUNetTrainer import nnUNetTrainer
class nnUNetTrainer_DiceBD(nnUNetTrainer):
def __init__(self, plans_file, fold, output_folder=None, data... |
build/go/gen_library_metadata.py | wwjiang007/fuchsia-1 | 210 | 12744656 | <filename>build/go/gen_library_metadata.py
#!/usr/bin/env python3.8
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import json
import os
import sys
class Source(object):
def __init__... |
lambdaguard/utils/arnparse.py | CGarces/LambdaGuard | 354 | 12744661 | <filename>lambdaguard/utils/arnparse.py
"""
Copyright 2020 Skyscanner Ltd
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 l... |
205 Isomorphic Strings.py | ChiFire/legend_LeetCode | 872 | 12744667 | <reponame>ChiFire/legend_LeetCode
"""
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two
characters may map to t... |
pydruid/async_client.py | trakru/pydruid | 444 | 12744691 | <reponame>trakru/pydruid<filename>pydruid/async_client.py
#
# Copyright 2016 Metamarkets Group 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/LICE... |
python/paddle/fluid/tests/unittests/test_dataset_dataloader.py | zmxdream/Paddle | 17,085 | 12744695 | <filename>python/paddle/fluid/tests/unittests/test_dataset_dataloader.py
# 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
#
# ... |
artemis/experiments/decorators.py | wouterkool/artemis | 235 | 12744712 | <filename>artemis/experiments/decorators.py
from collections import OrderedDict
from artemis.experiments.experiment_record_view import show_record, compare_experiment_records
from artemis.experiments.experiments import Experiment
from artemis.general.display import sensible_str
from artemis.general.should_be_builtins ... |
td4a/controllers/validate.py | cidrblock/td4a | 171 | 12744720 | <filename>td4a/controllers/validate.py
""" /retrieve
"""
import json
from flask import current_app as app
from flask import request, jsonify, Blueprint
from td4a.models.exception_handler import ExceptionHandler, HandledException
from td4a.models.td4ayaml import Td4aYaml
from jsonschema import validate
from jsonschema i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.