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 |
|---|---|---|---|---|
code/python/src/vm/lua_type.py | ShakeM/luago-book | 723 | 11171327 | <gh_stars>100-1000
from enum import Enum, unique
@unique
class LuaType(Enum):
NONE = -1
NIL = 0
BOOLEAN = 1
LIGHT_USER_DATA = 2
NUMBER = 3
STRING = 4
TABLE = 5
FUNCTION = 6
USER_DATA = 7
THREAD = 8
|
examples/fetchDebianDependencyGraph.py | woehrer12/pyArango | 126 | 11171335 | #!/usr/bin/python
import sys
from pyArango.connection import *
from pyArango.graph import *
from asciitree import *
conn = Connection(username="USERNAME", password="<PASSWORD>")
db = conn["ddependencyGrahp"]
if not db.hasGraph('debian_dependency_graph'):
raise Exception("didn't find the debian dependency graph, ... |
casper4/griefing_one_third_offline_simulator.py | kevaundray/research | 1,351 | 11171361 | import math
# Length of an epoch in seconds
epoch_len = 1400
# In-protocol penalization parameter
increment = 0.00002
# Parameters
NFP = 0
NCP = 3
NCCP = 3
NPP = 3
NPCP = 3
def sim_offline(p):
online, offline = 1-p, p
for i in range(1, 999999):
# Lost by offline validators
offline_loss = NFP ... |
SuperReads_RNA/global-1/jellyfish/swig/python/test_string_mers.py | wrf/stringtie | 255 | 11171394 | import unittest
import sys
import random
import jellyfish
class TestStringMers(unittest.TestCase):
def setUp(self):
bases = "ACGTacgt"
self.str = ''.join(random.choice(bases) for _ in range(1000))
self.k = random.randint(10, 110)
jellyfish.MerDNA.k(self.k)
def test_all_mers(sel... |
tests/test_memory_merge.py | r4b3rt/angr | 6,132 | 11171421 | # pylint:disable=isinstance-second-argument-not-valid-type
import claripy
from angr.storage.memory_mixins import (
DataNormalizationMixin,
SizeNormalizationMixin,
AddressConcretizationMixin,
UltraPagesMixin,
ListPagesMixin,
PagedMemoryMixin,
SymbolicMergerMixin,
ConvenientMappingsMixin... |
venv/Lib/site-packages/statsmodels/base/tests/test_transform.py | EkremBayar/bayar | 6,931 | 11171423 | import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_raises)
from statsmodels.base.transform import (BoxCox)
from statsmodels.datasets import macrodata
class TestTransform:
@classmethod
def setup_class(cls):
data = macrodata.load_pandas()
cls.x = data.data['... |
chatbotv2/my_seq2seq_v2.py | drpreetyrai/ChatBotCourse | 5,087 | 11171437 | <filename>chatbotv2/my_seq2seq_v2.py
# -*- coding: utf-8 -*-
import sys
import math
import tflearn
import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import rnn
import chardet
import numpy as np
import struct
question_seqs = []
answer_seqs = []
max_w = 50
float_size = 4
wor... |
backend/app/app/schemas/reponse.py | jimorsm/vue-element-admin-fastapi | 137 | 11171448 | from typing import Optional, Any
from pydantic import BaseModel
# Shared properties
class Response(BaseModel):
code: Optional[int] = None
data : Optional[Any] = None
message: Optional[str] = None
|
ciphey/basemods/Resources/__init__.py | emadfuel/Ciphey | 9,908 | 11171449 | from . import cipheydists, files
|
utils/logger.py | bfortuner/VOCdetect | 336 | 11171462 | <reponame>bfortuner/VOCdetect<gh_stars>100-1000
import os
import logging
import imp
import time
def get_logger(log_path='',
logger_name='logger',
ch_log_level=logging.ERROR,
fh_log_level=logging.INFO):
logging.shutdown()
imp.reload(logging)
logger = logging.get... |
tests/__init__.py | rexyeah/jira-cli | 125 | 11171463 | """
"""
import types
import unittest
if not hasattr(unittest.TestCase, "assertIsNotNone"):
def assertIsNotNone(self, value, message=""):
self.assertNotEqual(value, None, message)
unittest.TestCase.assertIsNotNone = types.MethodType(assertIsNotNone, None, unittest.TestCase)
|
Chapter5/ex_5_19.py | zxjzxj9/PyTorchIntroduction | 205 | 11171534 | """ 该代码仅为演示函数签名和所用方法,并不能实际运行
"""
class torch.nn.TransformerEncoder(encoder_layer, num_layers, norm=None)
# TransformerEncoder对应的forward方法定义
forward(src, mask=None, src_key_padding_mask=None)
class torch.nn.TransformerDecoder(decoder_layer, num_layers, norm=None)
# TransformerDecoder对应的forward方法定义
forward(tgt, memory,... |
Benchmarks/scripts/bench_batch_streaming_ingest.py | Pahandrovich/omniscidb | 868 | 11171552 | <gh_stars>100-1000
import sys
import pymapd
import pyarrow as pa
import pandas as pd
import numpy as np
import time
import argparse
def getOptions(args=None):
parser = argparse.ArgumentParser(description='Benchmark OmniSci batch and streaming table ingest')
parser.add_argument('-s','--host', help='OmniSci ser... |
samples/aci-create-vmw-domain.py | richardstrnad/acitoolkit | 351 | 11171569 | #!/usr/bin/env python
################################################################################
# _ ____ ___ _____ _ _ _ _ #
# / \ / ___|_ _| |_ _|__ ___ | | | _(_) |_ #
# / _ \| | | | | |/ _ \ / _ \| | |/... |
tests/generators/merkle/main.py | jacobkaufmann/consensus-specs | 2,161 | 11171588 | <gh_stars>1000+
from eth2spec.test.helpers.constants import ALTAIR, MERGE
from eth2spec.gen_helpers.gen_from_tests.gen import run_state_test_generators
if __name__ == "__main__":
altair_mods = {key: 'eth2spec.test.altair.merkle.test_' + key for key in [
'single_proof',
]}
merge_mods = altair_mods
... |
serieswatcher/sqlobject/tests/test_comparison.py | lightcode/SeriesWatcher | 303 | 11171603 | <gh_stars>100-1000
from sqlobject import *
from sqlobject.tests.dbtest import *
class TestComparison(SQLObject):
pass
def test_eq():
setupClass(TestComparison)
t1 = TestComparison()
t2 = TestComparison()
TestComparison._connection.cache.clear()
t3 = TestComparison.get(1)
t4 = TestComparis... |
tests/trac/trac-0033/tread.py | eLBati/pyxb | 123 | 11171626 | # -*- coding: utf-8 -*-
from __future__ import print_function
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import time
import pyxb.binding.generate
import pyxb.utils.domutils
from pyxb.utils.six.moves import xrange
max_reps = 20
def buildTest (num_reps, constr... |
Python3/68.py | rakhi2001/ecom7 | 854 | 11171632 | __________________________________________________________________________________________________
sample 20 ms submission
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
n = len(words)
if n == 0:
return []
res = []
cur, num_letters = ... |
notebooks/Ch03_Processing_Wrangling_and_Visualizing_Data/matplotlib_viz.py | baoqt2/practical-machine-learning-with-python | 1,989 | 11171634 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 11 09:56:39 2017
@author: <NAME>
"""
"""
This script visualizes data using matplotlib
``Execute``
$ python matplotlib_viz.py
"""
import numpy as np
import matplotlib.pyplot as plt
if __name__=='__main__':
# sample plot
x = np.linspace(-10, 10... |
corehq/apps/accounting/migrations/0051_hubspot_restrictions.py | dimagilg/commcare-hq | 471 | 11171655 | <reponame>dimagilg/commcare-hq
# Generated by Django 2.2.16 on 2020-10-15 17:48
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0050_app_user_profiles'),
]
operations = [
migrations.Ad... |
draw_pic.py | wu546300070/weiboanalysis | 685 | 11171713 | # SVM 准确率
from pylab import mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.sans-serif'] = ['SimHei']
fig, ax = plt.subplots()
x = [i for i in range(0, 21)]
array = [
0.850000, 0.825000, 0.818750, 0.800000, 0.843750, 0.812500, 0.775000, 0.831250, 0.850000, 0.850000, 0.850000,
0.806250, 0.875000, 0.8500... |
library/oci_file_system_facts.py | slmjy/oci-ansible-modules | 106 | 11171727 | <reponame>slmjy/oci-ansible-modules<filename>library/oci_file_system_facts.py
#!/usr/bin/python
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://... |
test/test_timer.py | Scartography/mapchete | 161 | 11171734 | from mapchete import Timer
def test_timer():
timer1 = Timer(elapsed=1000)
timer2 = Timer(elapsed=2000)
timer3 = Timer(elapsed=1000)
assert timer1 < timer2
assert timer1 <= timer2
assert timer2 > timer3
assert timer2 >= timer3
assert timer1 == timer3
assert timer1 != timer2
ass... |
backend/category/ssh/ssh_operation.py | zerlee/open-cmdb | 126 | 11171748 | <filename>backend/category/ssh/ssh_operation.py
import json
import os
from django.conf import settings
from rest_framework.exceptions import ParseError
from category.models import Server
from .ssh_connection import SSHConnection
class SSHOperation(object):
def __init__(self, host, port, user):
self.ho... |
climlab/process/implicit.py | nfeldl/climlab | 160 | 11171764 | from __future__ import division
from climlab.process.time_dependent_process import TimeDependentProcess
class ImplicitProcess(TimeDependentProcess):
"""A parent class for modules that use implicit time discretization.
During initialization following attributes are intitialized:
:ivar time_type: i... |
tests/r/test_sp500.py | hajime9652/observations | 199 | 11171778 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.sp500 import sp500
def test_sp500():
"""Test module sp500.py by downloading
sp500.csv and testing shape of
extracted data has 2783 rows an... |
.github/CI_MISC/pre_qt_universal_build.py | Croden1999/Play- | 1,720 | 11171811 | <gh_stars>1000+
import sys
import os
import shutil
import glob
def fix_id(lib_name, is_fw):
if(lib_name.count("HOMEBREW_PREFIX") == 0):
return ""
if(is_fw):
lib_name = "/".join(lib_name.split(" (c")[0].strip().split("/")[4:])
new_lib_path = f"@rpath/{lib_name}"
return f"-add_rp... |
monitoring/grafana/grr_grafanalib_dashboards/config.py | tsehori/grr | 4,238 | 11171812 | from grr_grafanalib_dashboards import reusable_panels
# The data source names are specified after Grafana is set up
# and it can be visited at localhost:3000.
# In GRR Monitoring docs, we suggest naming the data sources "grr-server"
# and "grrafana" respectively, but if it's not the case, change it here.
# For referen... |
setup.py | thavelick/summarize | 175 | 11171820 | #!/usr/bin/env python
# http://docs.python.org/2/distutils/setupscript.html
from distutils.core import setup
setup(
name='summarize',
version='20121029',
# ...
py_modules=['summarize'],
# ...
)
|
beautifultable/beautifultable.py | onmeac/beautifultable | 137 | 11171847 | <gh_stars>100-1000
"""This module provides BeautifulTable class
It is intended for printing Tabular data to terminals.
Example
-------
>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.columns.header = ['1st column', '2nd column']
>>> for i in range(5):
... table.rows.apppend([i,... |
libtbx/queuing_system_utils/__init__.py | rimmartin/cctbx_project | 155 | 11171849 | <filename>libtbx/queuing_system_utils/__init__.py<gh_stars>100-1000
from __future__ import absolute_import, division, print_function
import sys
from libtbx import Auto
class chunk_manager(object):
def __init__(self, n, i):
assert n > 0
assert i >= 0
assert i < n
self.n = n
self.i = i
self.... |
electrumsv/keystore.py | electrumsv/electrumsv | 136 | 11171923 | # Electrum - lightweight Bitcoin client
# Copyright (C) 2016 The Electrum developers
#
# 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... |
tests/validate/common/test_repository_topics_check.py | Chriserus/integration | 2,039 | 11171940 | import pytest
from custom_components.hacs.validate.repository_topics import Validator
@pytest.mark.asyncio
async def test_repository_no_topics(repository):
repository.data.topics = []
check = Validator(repository)
await check.execute_validation()
assert check.failed
@pytest.mark.asyncio
async def t... |
collection/cp/codelibrary-master/python/plot.py | daemonslayer/Notebook | 1,727 | 11171971 | <reponame>daemonslayer/Notebook
from cmath import sin
import matplotlib.pyplot as plt
plt.plot([sin(x) for x in range(100)])
plt.show()
|
tests/test_primitive_data/test_tag.py | amih90/bacpypes | 240 | 11171986 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test Primitive Data Tag
-----------------------
"""
import unittest
from bacpypes.errors import InvalidTag
from bacpypes.debugging import bacpypes_debugging, ModuleLogger, xtob, btox
from bacpypes.primitivedata import Tag, ApplicationTag, ContextTag, \
OpeningTag... |
tests/unit/profiles/test_plone.py | jdufresne/isort | 3,043 | 11171987 | from functools import partial
from ..utils import isort_test
plone_isort_test = partial(isort_test, profile="plone")
def test_plone_code_snippet_one():
plone_isort_test(
"""# -*- coding: utf-8 -*-
from plone.app.multilingual.testing import PLONE_APP_MULTILINGUAL_PRESET_FIXTURE # noqa
from plone.app.rob... |
Python/Tests/TestData/Grammar/Literals.py | techkey/PTVS | 695 | 11172022 | <gh_stars>100-1000
"abc"
r"raw string"
R"raw string"
"""abc"""
r"""raw string"""
R"""raw string"""
'abc'
r'raw string'
R'raw string'
'''abc'''
r'''raw string'''
R'''raw string'''
1000
2147483647
3.14
10.
.001
1e100
3.14e-10
0e0
3.14j
10.j
10j
.001j
1e100j
3.14e-10j
-2147483648
-100 |
release/stubs.min/System/Windows/Forms/__init___parts/ToolStripSystemRenderer.py | htlcnn/ironpython-stubs | 182 | 11172027 | <reponame>htlcnn/ironpython-stubs<gh_stars>100-1000
class ToolStripSystemRenderer(ToolStripRenderer):
"""
Handles the painting functionality for System.Windows.Forms.ToolStrip objects,using system colors and a flat visual style.
ToolStripSystemRenderer()
"""
|
cliport/tasks/__init__.py | wx-b/cliport | 110 | 11172050 | """Ravens tasks."""
from cliport.tasks.align_box_corner import AlignBoxCorner
from cliport.tasks.assembling_kits import AssemblingKits
from cliport.tasks.assembling_kits import AssemblingKitsEasy
from cliport.tasks.assembling_kits_seq import AssemblingKitsSeqSeenColors
from cliport.tasks.assembling_kits_seq import Ass... |
challenge_9/python/system123/challenge_9.py | YearOfProgramming/2017Challenges | 271 | 11172053 | <filename>challenge_9/python/system123/challenge_9.py<gh_stars>100-1000
from collections import deque
def squared_sort(input_list):
negs = deque([])
pos = deque([])
sorted = []
for x in input_list: #O(n)
if x < 0:
negs.append(x**2)
else:
pos.append(x**2)
n = None
p = None
for i in range(0, len(input... |
tests/test_remote.py | irina694/earth-science-notebook | 1,076 | 11172080 | <reponame>irina694/earth-science-notebook
import pytest
from geonotebook.kernel import Remote
@pytest.fixture
def remote(mocker):
protocols = [{'procedure': 'no_args',
'required': [],
'optional': []},
{'procedure': 'required_only',
'required... |
tests/utils/test_pydantic.py | 0scarB/piccolo | 750 | 11172091 | <filename>tests/utils/test_pydantic.py<gh_stars>100-1000
import decimal
from unittest import TestCase
import pydantic
from pydantic import ValidationError
from piccolo.columns import JSON, JSONB, Array, Numeric, Secret, Text, Varchar
from piccolo.columns.column_types import ForeignKey
from piccolo.table import Table
... |
Alignment/CommonAlignmentProducer/python/ALCARECOTkAlCosmicsInCollisions_Output_cff.py | ckamtsikis/cmssw | 852 | 11172098 | # Author : <NAME>
# Date : July 1st, 2010
# last update: $Date: 2010/07/06 11:48:22 $ by $Author: mussgill $
import FWCore.ParameterSet.Config as cms
# AlCaReco for track based alignment using Cosmic muon events
OutALCARECOTkAlCosmicsInCollisions_noDrop = cms.PSet(
SelectEvents = cms.untracked.PSet(
... |
pottery/executor.py | brainix/pottery | 625 | 11172126 | <filename>pottery/executor.py
# --------------------------------------------------------------------------- #
# executor.py #
# #
# Copyright © 2015-2021, <NAME>, original author... |
lib/python/treadmill/appenv/__init__.py | vrautela/treadmill | 133 | 11172163 | <filename>lib/python/treadmill/appenv/__init__.py<gh_stars>100-1000
"""Treadmill application environment.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
if os.name == 'nt':
from ._windows import Wi... |
zcls/model/layers/dbb_util.py | ZJCV/PyCls | 110 | 11172168 | <filename>zcls/model/layers/dbb_util.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
@date: 2021/7/28 下午5:50
@file: ddb_util.py
@author: zj
@description:
"""
from .dbb_transforms import transI_fusebn, transII_addbranch, transIII_1x1_kxk, \
transVI_multiscale, transV_avg, transVI_multiscale
from .diverse_branch... |
Medium/Alphabets in order with numbers/alphabets.py | anishsingh42/CodeChef | 127 | 11172183 | def alpha(a):
c = 0
for i in range(len(a)):
if i==ord(a[i])-97 or i==ord(a[i])-65:
c+=1
return c
a = input()
print(alpha(a))
|
client/pac_websrv.py | HackademicsForum/pacdoor | 162 | 11172190 | <reponame>HackademicsForum/pacdoor<filename>client/pac_websrv.py
#!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sour... |
nuplan/planning/training/modeling/objectives/test/test_agents_imitation_objective.py | motional/nuplan-devkit | 128 | 11172205 | import unittest
from typing import List
import numpy as np
import numpy.typing as npt
import torch
from nuplan.planning.training.modeling.objectives.agents_imitation_objective import AgentsImitationObjective
from nuplan.planning.training.preprocessing.features.agents_trajectories import AgentsTrajectories
class Tes... |
warehouse/tests/unit/test_on_order_events.py | Al-bambino/aws-serverless-ecommerce-platform | 758 | 11172211 | import copy
import datetime
import random
import uuid
from botocore import stub
import pytest
from fixtures import context, lambda_module, get_order, get_product # pylint: disable=import-error
from helpers import mock_table # pylint: disable=import-error,no-name-in-module
METADATA_KEY = "__metadata"
lambda_module =... |
genomepy/plugins/star.py | tilschaef/genomepy | 146 | 11172244 | <reponame>tilschaef/genomepy<filename>genomepy/plugins/star.py<gh_stars>100-1000
import os
from loguru import logger
from genomepy.files import extracted_file
from genomepy.plugins import Plugin
from genomepy.utils import cmd_ok, mkdir_p, rm_rf, run_index_cmd
class StarPlugin(Plugin):
def after_genome_download(... |
scale/node/test/test_views.py | kaydoh/scale | 121 | 11172265 | <filename>scale/node/test/test_views.py<gh_stars>100-1000
from __future__ import unicode_literals
import json
import django
from rest_framework import status
import node.test.utils as node_test_utils
from rest_framework.test import APITransactionTestCase
from scheduler.models import Scheduler
from util import rest
... |
ctpn_crnn_ocr/demo.py | shijieS/Scene-Text-Understanding | 380 | 11172272 | from ctpnport import *
from crnnport import *
#ctpn
text_detector = ctpnSource()
#crnn
model,converter = crnnSource()
timer=Timer()
print "\ninput exit break\n"
while 1 :
im_name = raw_input("\nplease input file name:")
if im_name == "exit":
break
im_path = "./img/" + im_name
im = cv2.imread(i... |
pytorch_wrapper/modules/transformer_encoder_block.py | skatsaounis/pytorch-wrapper | 111 | 11172280 | import torch.nn as nn
from . import LayerNorm, MultiHeadAttention
from .. import functional as pwF
class TransformerEncoderBlock(nn.Module):
"""
Transformer Encoder Block (https://arxiv.org/pdf/1706.03762.pdf).
"""
def __init__(self, time_step_size, heads, out_mlp, dp=0, is_end_padded=True):
... |
tests/test_evpn_tunnel_p2mp.py | gfreewind/sonic-swss | 132 | 11172296 | from evpn_tunnel import VxlanTunnel
DVS_ENV = ["HWSKU=Mellanox-SN2700"]
class TestVxlanOrchP2MP(object):
def get_vxlan_obj(self):
return VxlanTunnel()
# Test 1 - Create and Delete SIP Tunnel and Map entries
def test_p2mp_tunnel(self, dvs, testlog):
vxlan_obj = self.get_vxlan_obj()
... |
figures/modeling/arrows.py | patricknaughton01/RoboticSystemsBook | 116 | 11172328 | <gh_stars>100-1000
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from klampt.math import so3,se3,vectorops
class Arrow3D(FancyArrowPatch):
def __init__(self, start, end, shrinkA=0.0, shrinkB=0.0, m... |
eth/vm/forks/berlin/__init__.py | dbfreem/py-evm | 1,641 | 11172345 | from typing import (
Type,
)
from eth.rlp.blocks import BaseBlock
from eth.vm.forks import (
MuirGlacierVM,
)
from eth.vm.state import BaseState
from .blocks import BerlinBlock
from .headers import (
compute_berlin_difficulty,
configure_berlin_header,
create_berlin_header_from_parent,
)
from .stat... |
f5/bigip/tm/sys/test/unit/test_failover.py | nghia-tran/f5-common-python | 272 | 11172350 | <reponame>nghia-tran/f5-common-python<filename>f5/bigip/tm/sys/test/unit/test_failover.py<gh_stars>100-1000
# Copyright 2016 F5 Networks 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
#... |
docs/manual/gears/examples/reduce_xor.py | bogdanvuk/pygears | 120 | 11172353 | from pygears.lib import reduce, drv, check
from pygears.typing import Queue, Uint
drv(t=Queue[Uint[8]], seq=[[0xff, 0xff, 0xff, 0xff]]) \
| reduce(init=Uint[8](0), f=lambda x, y: x ^ y) \
| check(ref=[0])
|
arm/machine.py | kevinyuan/pydgin | 159 | 11172364 | <reponame>kevinyuan/pydgin
#=======================================================================
# machine.py
#=======================================================================
from pydgin.machine import Machine
from pydgin.storage import RegisterFile
from pydgin.debug import pad, pad_hex
from pydgin.utils ... |
wandb/trigger.py | borisgrafx/client | 3,968 | 11172395 | """Module to facilitate adding hooks to wandb actions
Usage:
import trigger
trigger.register('on_something', func)
trigger.call('on_something', *args, **kwargs)
trigger.unregister('on_something', func)
"""
_triggers = {}
def reset():
_triggers.clear()
def register(event, func):
_triggers.... |
app/ch16_mongodb/final/pypi_org/services/user_service.py | tbensonwest/data-driven-web-apps-with-flask | 496 | 11172400 | <filename>app/ch16_mongodb/final/pypi_org/services/user_service.py
from typing import Optional
from passlib.handlers.sha2_crypt import sha512_crypt as crypto
from pypi_org.nosql.users import User
def get_user_count() -> int:
return User.objects().count()
def find_user_by_email(email: str) -> Optional[User]:
... |
all_data_augmentation/clipping_augmenter.py | LuChungYing/yt8mtest | 196 | 11172421 |
import tensorflow as tf
from tensorflow import flags
FLAGS = flags.FLAGS
class ClippingAugmenter:
"""This only works with frame data"""
def augment(self, model_input_raw, num_frames, labels_batch, **unused_params):
assert(FLAGS.frame_feature,
"AugmentationTransformer only works with frame feature"... |
tests/utils.py | odidev/dash-renderer | 109 | 11172493 | import time
TIMEOUT = 5 # Seconds
def invincible(func):
def wrap():
try:
return func()
except:
pass
return wrap
class WaitForTimeout(Exception):
"""This should only be raised inside the `wait_for` function."""
pass
def wait_for(condition_function, get_mes... |
pycaret/tests/test_probability_threshold.py | hanaseleb/pycaret | 5,541 | 11172544 | <gh_stars>1000+
import os, sys
sys.path.insert(0, os.path.abspath(".."))
import pandas as pd
import pytest
import pycaret.classification
import pycaret.datasets
from pycaret.internal.meta_estimators import CustomProbabilityThresholdClassifier
def test():
# loading dataset
data = pycaret.datasets.get_data("j... |
timing/util/cell_timings.py | Keno/prjtrellis | 256 | 11172581 | #!/usr/bin/env python3
import parse_sdf
from os import path
import json
import sys
def include_cell(name, type):
return type.isupper() and "_" not in type
def rewrite_celltype(name, type):
return type
def rewrite_pin(name, type, pin):
return pin
def tupleise(x):
if type(x) is list:
retur... |
aiida/storage/psql_dos/migrations/versions/django_0018_django_1_11.py | mkrack/aiida-core | 153 | 11172590 | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
dbaas/logical/management/commands/remove_quarantineDB.py | didindinn/database-as-a-service | 303 | 11172599 | from django.core.management.base import BaseCommand
import logging
from logical.models import Database
LOG = logging.getLogger(__name__)
class Command(BaseCommand):
'''
remove database automatically when quarantine date expired
'''
def handle(self, *args, **options):
Database.purge_qu... |
vendor-local/lib/python/south/tests/non_managed/models.py | glogiotatidis/affiliates | 285 | 11172617 | # -*- coding: UTF-8 -*-
"""
An app with a model that is not managed for testing that South does
not try to manage it in any way
"""
from django.db import models
class Legacy(models.Model):
name = models.CharField(max_length=10)
size = models.IntegerField()
class Meta:
db_table = "legacy_... |
brawlstats/core.py | SharpBit/brawlstars | 101 | 11172703 | <filename>brawlstats/core.py
import asyncio
import json
import logging
import sys
import time
from typing import Union
import aiohttp
import requests
from cachetools import TTLCache
from .errors import Forbidden, NotFoundError, RateLimitError, ServerError, UnexpectedError
from .models import BattleLog, Brawlers, Club... |
pylsy/pylsy.py | Leviathan1995/Pylsy | 531 | 11172715 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Pylsy Authors
# For a full list of authors, see the AUTHORS file at
# https://github.com/Leviathan1995/Pylsy/blob/master/AUTHORS.
# @license MIT
from __future__ import print_function
from wcwidth import wcwidth
class pylsytable(obje... |
etl/parsers/etw/Microsoft_Windows_BranchCacheMonitoring.py | IMULMUL/etl-parser | 104 | 11172734 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-BranchCacheMonitoring
GUID : a2f55524-8ebc-45fd-88e4-a1b39f169e08
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from... |
alipay/aop/api/response/AlipayCommerceIotSdarttoolPrintSendResponse.py | antopen/alipay-sdk-python-all | 213 | 11172736 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayCommerceIotSdarttoolPrintSendResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceIotSdarttoolPrintSendResponse, self).__init__()
self._print_no = ... |
.github/actions/pr-to-update-go/pr_to_update_go/__main__.py | qtweng/trafficcontrol | 598 | 11172739 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... |
app/models/orm/migrations/env.py | leosussan/fastapi-gino-arq-postgres | 289 | 11172766 | <filename>app/models/orm/migrations/env.py
# isort:skip_file
import sys
sys.path.extend(["./"])
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
from app.settings.globals import ALEMBIC_CONFIG
######################## --- MODELS FOR MIGRATIONS --- #... |
tests/emukit/core/optimization/test_multi_source_acquisition_optimizer.py | ndalchau/emukit | 152 | 11172769 | <gh_stars>100-1000
import numpy as np
from numpy.testing import assert_array_equal
from emukit.core import ContinuousParameter
from emukit.core import InformationSourceParameter
from emukit.core import ParameterSpace
from emukit.core.optimization import GradientAcquisitionOptimizer
from emukit.core.optimization import... |
securitybot/tasker/sql_tasker.py | gurpradeep/securitybot | 1,053 | 11172792 | '''
A tasker on top of a SQL database.
'''
from securitybot.tasker.tasker import Task, Tasker, STATUS_LEVELS
from securitybot.sql import SQLEngine
from typing import List
# Note: this order is provided to match the SQLTask constructor
GET_ALERTS = '''
SELECT HEX(alerts.hash),
title,
ldap,
reason,... |
pfrl/nn/recurrent.py | g-votte/pfrl | 824 | 11172809 | class Recurrent(object):
"""Recurrent module interface.
This class defines the interface of a recurrent module PFRL support.
The interface is similar to that of `torch.nn.LSTM` except that sequential
data are expected to be packed in `torch.nn.utils.rnn.PackedSequence`.
To implement a model with ... |
cacreader/swig-4.0.2/Examples/test-suite/python/python_append_runme.py | kyletanyag/LL-Smartcard | 1,031 | 11172814 | <filename>cacreader/swig-4.0.2/Examples/test-suite/python/python_append_runme.py
from python_append import *
# test not relevant for -builtin
if is_python_builtin():
exit(0)
t = Test()
t.funk()
t.static_func()
if grabpath() != os.path.dirname(mypath):
raise RuntimeError("grabpath failed")
if grabstaticpath... |
recipes/Python/577546_linecountpy/recipe-577546.py | tdiprima/code | 2,023 | 11172825 | <reponame>tdiprima/code
#!/usr/bin/python
# -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 (C) by <NAME> <<EMAIL>i.thebault - at - gmail - dot - com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... |
packs/cloudflare/tests/test_action_get_ips.py | userlocalhost2000/st2contrib | 164 | 11172828 | import yaml
import requests_mock
from mock import patch
from st2tests.base import BaseActionTestCase
from get_ips import GetIPsAction
__all__ = [
'GetIPsActionTestCase'
]
MOCK_CONFIG_BLANK = yaml.safe_load(open(
'packs/cloudflare/tests/fixture/blank.yaml').read())
MOCK_CONFIG_FULL = yaml.safe_load(open(
... |
dumpall.py | nian-hua/dumpall | 625 | 11172872 | <gh_stars>100-1000
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
"""
python3 dumpall.py <url>
"""
import os, sys
_srcdir = "%s/" % os.path.dirname(os.path.realpath(__file__))
_filepath = os.path.dirname(sys.argv[0])
sys.path.insert(1, os.path.join(_filepath, _srcdir))
if sys.version_info[0] == 3:
import dumpal... |
galileo/framework/tf/python/callbacks/metrics_time.py | YaoPu2021/galileo | 115 | 11172901 | # Copyright 2020 JD.com, Inc. Galileo 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 a... |
backend/src/baserow/contrib/database/ws/pages.py | cjh0613/baserow | 839 | 11172913 | from baserow.ws.registries import PageType
from baserow.core.exceptions import UserNotInGroup
from baserow.contrib.database.table.handler import TableHandler
from baserow.contrib.database.table.exceptions import TableDoesNotExist
class TablePageType(PageType):
type = "table"
parameters = ["table_id"]
de... |
sdk/python/pulumi_azure/monitoring/scheduled_query_rules_alert.py | henriktao/pulumi-azure | 109 | 11172918 | <filename>sdk/python/pulumi_azure/monitoring/scheduled_query_rules_alert.py
# 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 ty... |
src/openglgenerator.py | sioliv/University | 210 | 11172954 | """Refactored version of the opengl generator using ctypeslib
"""
try:
from ctypeslib.codegen import codegenerator
from ctypeslib import xml2py
except ImportError, err:
try:
from ctypes_codegen import codegenerator, xml2py
except ImportError, err:
from ctypes.wrap import codegenerator, x... |
idaes/surrogate/helmet/Helmet.py | eyoung55/idaes-pse | 112 | 11172988 | #################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
pynes/cartridge.py | timgates42/pyNES | 1,046 | 11172996 | <gh_stars>1000+
class Cartridge:
def __init__(self):
self.banks = {}
self.bank_id = 0
self.pc = 0
self.inespgr = 1
self.ineschr = 1
self.inesmap = 1
self.inesmir = 1
self.rs = 0
self.path = ''
def nes_id(self):
# NES
retur... |
test/run/t291.py | timmartin/skulpt | 2,671 | 11173005 | <reponame>timmartin/skulpt<filename>test/run/t291.py
print -3 % 2
print 3 % 2
print -3 % 3
print 3 % 3
print
print -3 % -2
print 3 % -2
print -3 % -3
print 3 % -3
print
print 0 % 1
print 0 % -1
|
pycharm2020.1.3/script/TcpConn.py | LaudateCorpus1/realtime-server | 465 | 11173013 | from __future__ import annotations
import time
import asyncio
import struct
import typing
from asyncio import transports
from asyncio.exceptions import CancelledError
from ConnBase import HEARTBEAT_TIMEOUT, HEARTBEAT_INTERVAL, ConnBase, RPC_HANDLER_ID_LEN, RECONNECT_MAX_TIMES, \
RECONNECT_INTERVAL, CONN_STATE_CON... |
dynaconf/vendor/box/from_file.py | RonnyPfannschmidt/dynaconf | 2,293 | 11173032 | from json import JSONDecodeError
from pathlib import Path
from typing import Union
from dynaconf.vendor.toml import TomlDecodeError
from dynaconf.vendor.ruamel.yaml import YAMLError
from .exceptions import BoxError
from .box import Box
from .box_list import BoxList
__all__=['box_from_file']
def _to_json(data):
try:ret... |
src/models/backbones_3d/pfe/__init__.py | reinforcementdriving/SA-Det3D | 134 | 11173074 | <gh_stars>100-1000
from .voxel_set_abstraction import VoxelSetAbstraction
from .sa_voxel_set_abstraction import SAVoxelSetAbstraction
from .def_voxel_set_abstraction import DefVoxelSetAbstraction
__all__ = {
'VoxelSetAbstraction': VoxelSetAbstraction,
'DefVoxelSetAbstraction': DefVoxelSetAbstraction,
'SAVox... |
tests/browser_base.py | petrklus/pyquery | 1,758 | 11173091 |
class TextExtractionMixin():
def _prepare_dom(self, html):
self.last_html = '<html><body>' + html + '</body></html>'
def _simple_test(self, html, expected_sq, expected_nosq, **kwargs):
raise NotImplementedError
def test_inline_tags(self):
self._simple_test(
'Phas<em>el... |
segmentation/models/model.py | dataflowr/evaluating_bdl | 110 | 11173106 | # code-checked
# server-checked
import torch.nn as nn
from torch.nn import functional as F
import torch
import os
import sys
import numpy as np
from torch.autograd import Variable
import functools
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
from resnet_block import co... |
thumbsup/tests.py | annevandalfsen/screenbird | 121 | 11173109 | <gh_stars>100-1000
import logging
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from videos.models import Video
handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
logger = logging.... |
tests/sam.py | SantoshSrinivas79/aws-lambda-r-runtime | 134 | 11173118 | import logging
from subprocess import Popen
import boto3
import botocore
from tests import wait_for_port
class LocalApi:
def __init__(self,
host: str = '127.0.0.1',
port: int = 3000,
template_path: str = None,
parameter_overrides: dict = None,... |
rotkehlchen/exchanges/poloniex.py | rotkehlchenio/rotkehlchen | 137 | 11173131 | <reponame>rotkehlchenio/rotkehlchen<filename>rotkehlchen/exchanges/poloniex.py
import csv
import hashlib
import hmac
import logging
import os
from collections import defaultdict
from json.decoder import JSONDecodeError
from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional, Tuple, Union
from urllib.pa... |
examples/eigenvector_localization.py | jafluri/pygsp | 341 | 11173146 | r"""
Localization of Fourier modes
=============================
The Fourier modes (the eigenvectors of the graph Laplacian) can be localized in
the spacial domain. As a consequence, graph signals can be localized in both
space and frequency (which is impossible for Euclidean domains or manifolds, by
the Heisenberg's ... |
tools/FixIncompleteCrashReport/fixer.py | JiPRA/openlierox | 192 | 11173161 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
if len(sys.argv) != 2:
print "usage:", sys.argv[0], " <mail>"
exit(1)
mail = open(sys.argv[1])
if not mail:
print "cannot open", sys.argv[1]
exit(1)
import os
symsdir = ""
import re
import string
def findSymfile(module):
fn = symsdir + "/" + module + ".x... |
tests/math/soft_one_hot_test.py | claycurry34/e3nn | 385 | 11173163 | <filename>tests/math/soft_one_hot_test.py
import pytest
import torch
from e3nn.math import soft_one_hot_linspace
@pytest.mark.parametrize('basis', ['gaussian', 'cosine', 'fourier', 'bessel', 'smooth_finite'])
def test_zero_out(basis):
x1 = torch.linspace(-2.0, -1.1, 20)
x2 = torch.linspace(2.1, 3.0, 20)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.