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 |
|---|---|---|---|---|
leetcode.com/python/389_Find_the_Difference.py | XSoyOscar/Algorithms | 713 | 11169570 | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
ans = 0
for char in s + t:
ans ^= char
return char(ans)
sol = Solution()
out = sol.findTheDifference("abcd", "abcde")
print('Res: '... |
detection/object_detection/obj_4_efficientdet/WindowObj4EfficientdetDataParam.py | THEFASHIONGEEK/Monk_Gui | 129 | 11169593 | import os
import sys
import json
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class WindowObj4EfficientdetDataParam(QtWidgets.QWidget):
backward_4_efficientdet = QtCore.pyqtSignal();
forward_valdata_param = QtCore.pyqtSignal();
def __init__(self):
s... |
deploy/scripts/aphros/vtk.py | cselab/aphros | 252 | 11169617 | #!/usr/bin/env python3
try:
import numpy as np
except ImportError:
pass
import re
import sys
import inspect
import os
def printerr(m):
sys.stderr.write(str(m) + "\n")
def ReadVtkPoly(f, verbose=False):
"""
Reads vtk points, polygons and fields from legacy VTK file.
f: `str` or file-like
... |
src/sage/symbolic/complexity_measures.py | bopopescu/sage | 1,742 | 11169637 | """
Complexity Measures
Some measures of symbolic expression complexity. Each complexity
measure is expected to take a symbolic expression as an argument, and
return a number.
"""
def string_length(expr):
"""
Returns the length of ``expr`` after converting it to a string.
INPUT:
- ``expr`` -- the ex... |
joints_detectors/hrnet/pose_estimation/utilitys.py | rcourivaud/video-to-pose3D | 574 | 11169649 | import torch
import torchvision.transforms as transforms
from lib.utils.transforms import *
joint_pairs = [[0, 1], [1, 3], [0, 2], [2, 4],
[5, 6], [5, 7], [7, 9], [6, 8], [8, 10],
[5, 11], [6, 12], [11, 12],
[11, 13], [12, 14], [13, 15], [14, 16]]
colors = [[255, 0, 0], [... |
lib/hachoir/metadata/csv.py | 0x20Man/Watcher3 | 320 | 11169658 | from hachoir.parser import createParser
from hachoir.core.tools import makePrintable
from hachoir.metadata import extractMetadata
from hachoir.core.i18n import initLocale
from sys import argv, stderr, exit
from os import walk
from os.path import join as path_join
from fnmatch import fnmatch
import codecs
OUTPUT_FILENA... |
tests/test_token.py | federicoemartinez/Flask-HTTPAuth | 1,082 | 11169667 | import base64
import unittest
from flask import Flask
from flask_httpauth import HTTPTokenAuth
class HTTPAuthTestCase(unittest.TestCase):
def setUp(self):
app = Flask(__name__)
app.config['SECRET_KEY'] = 'my secret'
token_auth = HTTPTokenAuth('MyToken')
token_auth2 = HTTPTokenAuth... |
LeetCode/python3/914.py | ZintrulCre/LeetCode_Archiver | 279 | 11169672 | class Solution:
def hasGroupsSizeX(self, deck):
"""
:type deck: List[int]
:rtype: bool
"""
from fractions import gcd
from collections import Counter
from functools import reduce
vals = Counter(deck).values()
g = reduce(gcd, vals)
return... |
tests/tgan/test_launcher.py | HDI-Project/TGAN | 131 | 11169721 | <filename>tests/tgan/test_launcher.py
'''
from unittest import TestCase, skip
from unittest.mock import MagicMock, patch
# from tgan import launcher
launcher = None
@skip()
class TestLauncher(TestCase):
@patch('tgan.launcher.subprocess.call', autospec=True)
@patch('tgan.launcher.multiprocessing.current_proc... |
pyx12/errh_xml.py | azoner/pyx12 | 120 | 11169751 | <reponame>azoner/pyx12
######################################################################
# Copyright (c)
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file LICENSE.txt, which
# you should have received as part of this distribution.
#
#################################... |
utime/preprocessing/dataset_preparation/phys/phys.py | learning310/U-Time | 138 | 11169753 | <reponame>learning310/U-Time
import os
from glob import glob
from utime.preprocessing.dataset_preparation.utils import download_dataset
# Get path to current module file
_FILE_PATH = os.path.split(__file__)[0]
# Server base URL
_SERVER_URL = "https://physionet.org/files/challenge-2018/1.0.0"
_CHECKSUM_FILE = "{}/phys... |
src/mceditlib/structure.py | elcarrion06/mcedit2 | 673 | 11169780 | """
structure
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from math import floor
from mceditlib import nbt
log = logging.getLogger(__name__)
def exportStructure(filename, dim, selection, author=None, excludedBlocks=None):
"""
Parameters
----... |
sen/tui/views/disk_usage.py | lachmanfrantisek/sen | 956 | 11169785 | """
TODO:
* nicer list
* summary
* clickable items
* enable deleting volumes
"""
import urwid
from sen.util import humanize_bytes, graceful_chain_get
from sen.tui.views.base import View
from sen.tui.widgets.list.util import SingleTextRow
from sen.tui.widgets.table import assemble_rows
from sen.tui.constants import... |
tutorial/ctc_loss.py | sailist/ASRFrame | 223 | 11169807 | <filename>tutorial/ctc_loss.py
import numpy as np
import keras.backend as K
import tensorflow as tf
a = [1,2,3,1,2,4,6,6,6,6]
b = [3,1,2,3,5,1,6,6,6,6]
c = [2,1,0,2,3,4,6,6,6,6]
y_true = np.stack([a,b,c])
y_pred = np.random.rand(3,15,7).astype(np.float32)
input_length = np.stack([[7],[8],[9]])
label_length = np.st... |
astrality/tests/conftest.py | JakobGM/Astrality | 111 | 11169851 | """Application wide fixtures."""
import os
from pathlib import Path
import shutil
import pytest
import astrality
from astrality.actions import ActionBlock
from astrality.config import GlobalModulesConfig, user_configuration
from astrality.context import Context
from astrality.module import Module, ModuleManager
@py... |
airflow/providers/amazon/aws/operators/emr_containers.py | ChaseKnowlden/airflow | 15,947 | 11169867 | <gh_stars>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
# "License"... |
neupy/layers/activations.py | FrostByte266/neupy | 801 | 11169884 | import numpy as np
import tensorflow as tf
from neupy import init
from neupy.utils import asfloat, as_tuple, tf_utils
from neupy.exceptions import LayerConnectionError, WeightInitializationError
from neupy.core.properties import (
NumberProperty, TypedListProperty,
ParameterProperty, IntProperty,
)
from .base ... |
loaner/web_app/backend/lib/sync_users_test.py | gng-demo/travisfix | 175 | 11169893 | <gh_stars>100-1000
# Copyright 2018 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 by ... |
AIDog/serving/test_client_v1.py | BaranovArtyom/aiexamples | 119 | 11169926 | <gh_stars>100-1000
#!/usr/bin/env python
import argparse
import requests
import json
import tensorflow as tf
import numpy as np
def read_tensor_from_image_file(file_name,
input_height=299,
input_width=299,
input_mean=0,
... |
tests/utils/test_tree.py | graingert/py-backwards | 338 | 11169927 | from typed_ast import ast3 as ast
from astunparse import unparse
from py_backwards.utils.snippet import snippet
from py_backwards.utils.tree import (get_parent, get_node_position,
find, insert_at, replace_at)
def test_get_parent(as_ast):
@as_ast
def tree():
x = 1
... |
python/phonenumbers/data/region_FM.py | rodgar-nvkz/python-phonenumbers | 2,424 | 11169933 | """Auto-generated file, do not edit by hand. FM metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_FM = PhoneMetadata(id='FM', country_code=691, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[39]\\d\\d|820)\\d{4}', possible_leng... |
2020/06/19/Intro to Flask Blueprints/flask_blueprint_example/myapp/site/routes.py | kenjitagawa/youtube_video_code | 492 | 11169962 | <gh_stars>100-1000
from flask import Blueprint
site = Blueprint('site', __name__)
@site.route('/')
def index():
return '<h1>Welcome to the home page!</h1>'
|
tests/test_audio_tag.py | TUT-ARG/sed_eval | 113 | 11169990 | """
Unit tests for audio tag metrics
"""
import nose.tools
import sed_eval
import os
import numpy
import dcase_util
def test_direct_use():
reference_tag_list = dcase_util.containers.MetaDataContainer([
{
'filename': 'test1.wav',
'tags': 'cat,dog'
},
{
... |
util/clustergen/cluster.py | mfkiwl/snitch | 105 | 11169996 | #!/usr/bin/env python3
# Copyright 2020 ETH Zurich and University of Bologna.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
from dataclasses import dataclass
from enum import Enum
from jsonschema import ValidationError, RefResolver, Draft7Validator, va... |
pypower/loadcase.py | Bengt/PYPOWER | 221 | 11170021 | <reponame>Bengt/PYPOWER
# Copyright (c) 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Loads a PYPOWER case dictionary.
"""
import sys
from os.path import basename, splitext, exists
from copy import deepcopy
from numpy ... |
cfgov/mega_menu/tests/test_models.py | Colin-Seifer/consumerfinance.gov | 156 | 11170082 | <filename>cfgov/mega_menu/tests/test_models.py
from django.db import IntegrityError
from django.test import TestCase
from mega_menu.models import Menu
class MenuTests(TestCase):
def test_str(self):
self.assertEqual(str(Menu("en")), "English")
self.assertEqual(str(Menu("es")), "Spanish")
def ... |
fletcher/string_mixin.py | sthagen/fletcher | 225 | 11170097 | import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
from pandas.core.arrays import ExtensionArray
try:
# Only available in pandas 1.2+
from pandas.core.strings.object_array import ObjectStringArrayMixin
class _IntermediateExtensionArray(ExtensionArray, ObjectStringArrayMixin):
pas... |
build.py | ferrandinand/bombardier | 3,557 | 11170121 | import argparse
import os
import subprocess
platforms = [
("darwin", "amd64"),
("darwin", "arm64"),
("freebsd", "386"),
("freebsd", "amd64"),
("freebsd", "arm"),
("linux", "386"),
("linux", "amd64"),
("linux", "arm"),
("linux", "arm64"),
("netbsd", "386"),
("netbsd", "amd64"... |
modules/data.remote/inst/RpTools/RpTools/biophys_xarray.py | CFranc22/pecan | 151 | 11170133 | # -*- coding: utf-8 -*-
"""
Created on Mon May 11 14:34:08 2020
@author: <NAME> (<EMAIL>),
Finnish Meteorological Institute)
Olli's python implementation of ESA SNAP s2toolbox biophysical processor and
computation of vegetation indices.
See ATBD at https://step.esa.int/docs/extra/ATBD_S2ToolBox_L2B_V1.1.pdf
And java... |
public-engines/iris-species-engine/tests/training/test_trainer.py | tallandroid/incubator-marvin | 101 | 11170144 | <filename>public-engines/iris-species-engine/tests/training/test_trainer.py<gh_stars>100-1000
#!/usr/bin/env python
# coding=utf-8
try:
import mock
except ImportError:
import unittest.mock as mock
import pandas as pd
from marvin_iris_species_engine.training import Trainer
@mock.patch('marvin_iris_species_e... |
src/poetry/repositories/__init__.py | pkoch/poetry | 7,258 | 11170162 | from __future__ import annotations
from poetry.repositories.pool import Pool
from poetry.repositories.repository import Repository
__all__ = ["Pool", "Repository"]
|
atlas/foundations_sdk/src/test/local_run/test_initialize_default_environment.py | DeepLearnI/atlas | 296 | 11170187 |
from foundations_spec import *
from foundations.local_run.initialize_default_environment import create_config_file
class TestInitializeDefaultEnvironment(Spec):
mock_open = let_patch_mock_with_conditional_return('builtins.open')
mock_mkdirs = let_patch_mock('os.makedirs')
mock_typed_config_klass = let_pa... |
Python/Algorithms/DeepLearningAlgorithms/Layers.py | m-payal/AlgorithmsAndDataStructure | 195 | 11170221 | """
__FileCreationDate__ : //2020
__Author__ : CodePerfectPlus
__Package__ : Python 3
__GitHub__ : https://www.github.com/codeperfectplus
"""
|
tools/nntool/quantization/symmetric/kernels/softmax.py | 00-01/gap_sdk | 118 | 11170226 | # Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
scripts/gdrive_scanner.py | alaaseeku/rusty-hog | 281 | 11170229 | # A python script to "scan" a GDrive folder containing docs and binaries.
# You will need the Google Python API libraries:
# pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
from __future__ import print_function
import csv
import io
import json
import os.path
import random
im... |
Installer/create_version_file.py | MrTimbones/ed-scout | 116 | 11170298 | import os
import re
from jinja2 import Environment, FileSystemLoader
def extract_version_parts(git_response):
regex = r"v(\d)\.(\d)\.(\d)(?:-(\d+)-([a-z0-9]+)(?:-([a-z0-9]+))?)?"
matches = re.finditer(regex, git_response, re.MULTILINE)
groups = list(matches)[0].groups()
if len(groups) > 3... |
sponsors/migrations/0035_auto_20210826_1929.py | ewjoachim/pythondotorg | 911 | 11170340 | # Generated by Django 2.0.13 on 2021-08-26 19:29
from django.db import migrations, models
import sponsors.models
class Migration(migrations.Migration):
dependencies = [
('sponsors', '0034_contract_document_docx'),
]
operations = [
migrations.AlterField(
model_name='contract'... |
examples/newtons_cradle.py | conductiveIT/pymunk-1 | 670 | 11170389 | """A screensaver version of Newton's Cradle with an interactive mode.
"""
__docformat__ = "reStructuredText"
import os
import random
import sys
description = """
---- Newton's Cradle ----
A screensaver version of Newton's Cradle with an interactive mode
/s - Run in fullscreen screensaver mode
/p #### - Display a pr... |
cherry/models/robotics.py | acse-yl27218/cherry | 160 | 11170391 | #!/usr/bin/env python3
import torch as th
import torch.nn as nn
from cherry.nn import RoboticsLinear
class RoboticsMLP(nn.Module):
"""
[[Source]](https://github.com/seba-1511/cherry/blob/master/cherry/models/robotics.py)
**Description**
A multi-layer perceptron with proper initialization for robo... |
train_folder.py | dibyanshu0525/scenescoop | 120 | 11170412 | # This is a script to train a bunch of videos and leave it running for ever
import os
from glob import glob
import argparse
from argparse import Namespace
from os import getcwd, path
from scenescoop import main as scenescoop
def start(options):
# get all the videos in the input folder
videos = glob(options.input... |
tests/seahub/utils/test_normalize_file_path.py | weimens/seahub | 420 | 11170424 | <reponame>weimens/seahub<filename>tests/seahub/utils/test_normalize_file_path.py
import posixpath
from random import randint
from tests.common.utils import randstring
from seahub.test_utils import BaseTestCase
from seahub.utils import normalize_file_path
class NormalizeDirPathTest(BaseTestCase):
def test_normali... |
marrow/mailer/manager/dynamic.py | cynepiaadmin/mailer | 166 | 11170437 | <filename>marrow/mailer/manager/dynamic.py
# encoding: utf-8
import atexit
import threading
import weakref
import sys
import math
from functools import partial
from marrow.mailer.manager.futures import worker
from marrow.mailer.manager.util import TransportPool
try:
import queue
except ImportError:
import Q... |
airmozilla/manage/views/email_sending.py | mozilla/airmozilla | 115 | 11170474 | from django.shortcuts import render
from django.conf import settings
from .decorators import superuser_required
from airmozilla.manage import forms
from airmozilla.manage import sending
@superuser_required
def home(request):
context = {
'EMAIL_BACKEND': settings.EMAIL_BACKEND,
'EMAIL_FILE_PATH': ... |
tests/test_distributions.py | determinant-io/aboleth | 117 | 11170520 | <gh_stars>100-1000
"""Test distributions.py functionality."""
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from scipy.linalg import cho_solve
from scipy.stats import wishart
from aboleth.distributions import kl_sum, _chollogdet
from .conftest import SEED
def test_kl_normal_normal()... |
developer/cgi/check_url_redirect.py | dlawde/homebrew-cask | 7,155 | 11170538 | <reponame>dlawde/homebrew-cask
#!/usr/bin/python
from __future__ import print_function
import sys
import cgi
try: # Python 3
from urllib.request import Request, urlopen
except NameError: # Python 2
from urllib2 import Request, urlopen
url = sys.argv[1]
headers = {'User-Agent': 'Mozilla'}
if len(sys.argv) > 2:
... |
lldb/test/API/lang/cpp/class-loading-via-member-typedef/TestClassLoadingViaMemberTypedef.py | LaudateCorpus1/llvm-project | 605 | 11170539 | """
Tests loading of classes when the loading is triggered via a typedef inside the
class (and not via the normal LLDB lookup that first resolves the surrounding
class).
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestCase(Te... |
vultr/v1_backup.py | nickruhl/python-vultr | 117 | 11170549 | <filename>vultr/v1_backup.py<gh_stars>100-1000
'''Partial class to handle Vultr Backup API calls'''
from .utils import VultrBase
class VultrBackup(VultrBase):
'''Handles Vultr Backup API calls'''
def __init__(self, api_key):
VultrBase.__init__(self, api_key)
def list(self, params=None):
'... |
CSES_Problems/Repetitions/solution.py | gbrls/CompetitiveCode | 165 | 11170558 | <filename>CSES_Problems/Repetitions/solution.py
def repeat_counts(n):
if len(n)==1: # checking for the length of n. If it is 1 then returns 1
return 1
maxx=c=0 # initializing maxx and c as 0. maxx is used for maximum check and c is used for counting
for i in range(1,len(n)... |
egs/csj/align1/local/gather_transcript.py | texpomru13/espnet | 5,053 | 11170598 | <gh_stars>1000+
#!/usr/bin/env python3
import sys
if __name__ == "__main__":
texts = {}
with open(sys.argv[1], "r", encoding="utf-8") as f:
line = f.readline()
while line:
entry = line.split(" ")
eid = entry[0]
trans = " ".join(entry[1:]).rstrip()
... |
server/intrinsic/management/commands/intrinsic_generate_legend.py | paulu/opensurfaces | 137 | 11170620 | from django.core.management.base import BaseCommand
import numpy as np
from photos.utils import numpy_to_pil
from colormath.color_objects import LabColor
class Command(BaseCommand):
args = ''
help = ''
def handle(self, *args, **options):
height = 16
bar = np.zeros((256, height, 3))
... |
todo/parser/subparsers/list_todos.py | tomasdanjonsson/td-cli | 154 | 11170630 | from todo.constants import COMMANDS
from todo.parser.base import BaseParser, set_value
class ListTodosParser(BaseParser):
"""
usage: td [--completed] [--uncompleted] [--group GROUP] [--interactive]
td l [-c] [-u] [-g GROUP] [-i]
td ls [-c] [-u] [-g GROUP] [-i]
td list [-c] [-u... |
test/tools/pca_test.py | Edelweiss35/deep-machine-learning | 708 | 11170649 | <reponame>Edelweiss35/deep-machine-learning<gh_stars>100-1000
from __future__ import division
import numpy as np
import scipy as sp
from scipy.io import loadmat
from dml.tool import pca,featurenormal,projectData,recoverData,displayData
import matplotlib.pyplot as plt
data = loadmat("../data/face/ex7data1.mat")
X = data... |
shipshape/cli/testdata/workspace1/bad.py | google/shipshape | 283 | 11170652 | class foo:
def bla(x):
pass
|
examples/csg.py | ssebs/pg | 151 | 11170675 | <filename>examples/csg.py
import pg
class Window(pg.Window):
def setup(self):
self.wasd = pg.WASD(self, speed=5)
self.wasd.look_at((-2, 2, 2), (0, 0, 0))
self.context = pg.Context(pg.DirectionalLightProgram())
self.context.sampler = pg.Texture(0, 'examples/bronze.jpg')
self.... |
utils/utility.py | xhl1993/multi_pairs_martingle_bot | 351 | 11170687 | <reponame>xhl1993/multi_pairs_martingle_bot
"""
General utility functions.
币安推荐码: 返佣10%
https://www.binancezh.pro/cn/register?ref=AIR1GC70
币安合约推荐码: 返佣10%
https://www.binancezh.com/cn/futures/ref/51bitquant
if you don't have a binance account, you can use the invitation link to register one:... |
settings.py | liaopeiyuan/ml-arsenal-public | 280 | 11170699 | from datetime import datetime
PATH= "kail"
"""
Local
"""
if PATH=='kail':
print("Using paths on kail-main")
CHECKPOINTS='/data/kaggle/salt/checkpoints'
DATA='/data/kaggle/salt/'
RESULT='/data/ml-arsenal/projects/TGS_salt'
CODE='/data/ml-arsenal'
CUDA_DEVICES='0,1'
MODE='gpu'
GRAPHICS=T... |
flaskshop/account/utils.py | maquinuz/flask-shop | 141 | 11170712 | from functools import wraps
import phonenumbers
from flask import flash, abort
from flask_login import current_user
from phonenumbers.phonenumberutil import is_possible_number
from wtforms import ValidationError
from flaskshop.constant import Permission
class PhoneNumber(phonenumbers.PhoneNumber):
"""
A ext... |
src/chap10-InfraAsCode/pulumi/__main__.py | VestiDev/python_devops_2019-book | 294 | 11170724 | <filename>src/chap10-InfraAsCode/pulumi/__main__.py
import json
import mimetypes
import os
from pulumi import export, FileAsset
from pulumi_aws import s3, route53, acm, cloudfront
import pulumi
config = pulumi.Config('proj1') # proj1 is project name defined in Pulumi.yaml
content_dir = config.require('local_webdir... |
components/isceobj/Pause/__init__.py | vincentschut/isce2 | 1,133 | 11170769 | #!/usr/bin/env python3
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2012 California Institute of Technology. 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... |
wsgi.py | Yamtt/zmirror | 2,550 | 11170775 | <filename>wsgi.py
#!/usr/bin/env python3
# coding=utf-8
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
if os.path.dirname(__file__) != '':
os.chdir(os.path.dirname(__file__))
from zmirror.zmirror import app as application
__author__ = 'Aploium <<EMAIL>>'
def main():
from zmirror.zmirror ... |
examples/excalibur_detector_modules.py | acolinisi/h5py | 1,657 | 11170789 | <filename>examples/excalibur_detector_modules.py
'''Virtual datasets: The 'Excalibur' use case
https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''
import h5py
raw_files = ["stripe_%d.h5" % stripe for stripe in range(1,7)]# get these names
in_key = 'data' # where is... |
moto/elasticache/responses.py | symroe/moto | 5,460 | 11170816 | <reponame>symroe/moto
from moto.core.responses import BaseResponse
from .exceptions import PasswordTooShort, PasswordRequired
from .models import elasticache_backends
class ElastiCacheResponse(BaseResponse):
"""Handler for ElastiCache requests and responses."""
@property
def elasticache_backend(self):
... |
example.py | wangxiaoying/python-flamegraph | 404 | 11170831 | <filename>example.py
"""
Example usage of flamegraph.
To view a flamegraph run these commands:
$ python example.py
$ flamegraph.pl perf.log > perf.svg
$ inkview perf.svg
"""
import time
import sys
import flamegraph
def foo():
time.sleep(.1)
bar()
def bar():
time.sleep(.05)
if __name__ == "__main__":
... |
docs3/source/conf.py | jmscslgroup/rosbagpy | 107 | 11170881 | <reponame>jmscslgroup/rosbagpy
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup ----------------------------------------... |
bsonvspb/test.py | yutiansut/opentick | 147 | 11170901 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Python client for opentick.'''
import time
import json
from bson import BSON
import message_pb2
value = [99999999, 1.22222, 1.3222222, 1.422222]
values = []
for x in range(10):
values.append(value)
msg = {'0': 'test', '1': 1, '2': values}
print('json')
now = time.t... |
test/run/t275.py | timmartin/skulpt | 2,671 | 11170905 | class X:
pass
x = X()
print x.__class__
print str(x.__class__)
print repr(x.__class__)
|
locations/spiders/aurecongroup.py | nbeecher/alltheplaces | 297 | 11170918 | # -*- coding: utf-8 -*-
import scrapy
from locations.items import GeojsonPointItem
class AureconGroupSpider(scrapy.Spider):
name = "aurecongroup"
allowed_domains = ["www.aurecon.com"]
download_delay = 0.1
start_urls = (
"https://www.aurecongroup.com/locations",
)
def parse(self, respon... |
kansha/security.py | AnomalistDesignLLC/kansha | 161 | 11170923 | <gh_stars>100-1000
# -*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
from base64 import b64encode, b64decode
from Crypto impo... |
semtorch/models/modules/basic.py | WaterKnight1998/SemTorch | 145 | 11170933 | """Basic Module for Semantic Segmentation"""
import torch
import torch.nn as nn
from collections import OrderedDict
__all__ = ['_ConvBNPReLU', '_ConvBN', '_BNPReLU', '_ConvBNReLU', '_DepthwiseConv', 'InvertedResidual',
'SeparableConv2d']
_USE_FIXED_PAD = False
def _pytorch_padding(kernel_size, stride=1,... |
test/unit/awsume/awsumepy/lib/test_aws_files.py | ignatenkobrain/awsume | 654 | 11170937 | <filename>test/unit/awsume/awsumepy/lib/test_aws_files.py
import os
import json
import pytest
import argparse
from io import StringIO
from pathlib import Path
from unittest.mock import patch, MagicMock, mock_open
from awsume.awsumepy.lib import constants
from awsume.awsumepy.lib import aws_files
def test_get_aws_fil... |
plugins/services/api.py | ajenti/ajen | 3,777 | 11170950 | from jadi import interface
class Service():
"""
Basic class to store service informations.
"""
def __init__(self, manager):
self.id = None
self.name = None
self.manager = manager
self.state = None
self.running = None
class ServiceOperationError(Exception):
... |
test/unit/conftest.py | jurecuhalev/snowflake-connector-python | 311 | 11170956 | <reponame>jurecuhalev/snowflake-connector-python
#
# Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved.
#
import pytest
from snowflake.connector.telemetry_oob import TelemetryService
@pytest.fixture(autouse=True, scope="session")
def disable_oob_telemetry():
oob_telemetry_service = TelemetrySe... |
libsaas/services/uservoice/articles.py | MidtownFellowship/libsaas | 155 | 11170964 | from libsaas import http, parsers
from libsaas.services import base
from . import resource
class ArticlesBase(resource.UserVoiceResource):
path = 'articles'
def wrap_object(self, obj):
return {'article': obj}
class Articles(ArticlesBase):
@base.apimethod
def search(self, page=None, per_p... |
Chapter_10/ch10_ex2.py | pauldevos/Mastering-Object-Oriented-Python-Second-Edition | 108 | 11170991 | <filename>Chapter_10/ch10_ex2.py
#!/usr/bin/env python3.7
"""
Mastering Object-Oriented Python 2e
Code Examples for Mastering Object-Oriented Python 2nd Edition
Chapter 10. Example 2. YAML. Base Definitions
"""
# Persistence Classes
# ========================================
from typing import List, Optional, Dict,... |
contrib/tvmop/opdef.py | mchoi8739/incubator-mxnet | 211 | 11170996 | # 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 u... |
tests/test_praw_scrapers/test_live_scrapers/test_Livestream.py | JosephLai241/Reddit-Scraper | 318 | 11170997 | <filename>tests/test_praw_scrapers/test_live_scrapers/test_Livestream.py
"""
Testing `Livestream.py`.
"""
import argparse
import os
import praw
import types
from dotenv import load_dotenv
from urs.praw_scrapers.live_scrapers import Livestream
from urs.utils.Global import date
class MakeArgs():
"""
Making ... |
tests/system/scripts/pinger.py | fquesnel/marathon | 3,556 | 11171014 | <filename>tests/system/scripts/pinger.py
#!/usr/bin/env python
""" This app "pinger" responses to /ping with pongs and will
response to /relay by pinging another app and respond with it's response
"""
import sys
import logging
import os
import platform
# Ensure compatibility with Python 2 and 3.
# See https://gi... |
core/dbt/events/stubs.py | f1fe/dbt | 3,156 | 11171036 | from typing import (
Any,
List,
NamedTuple,
Optional,
Dict,
)
# N.B.:
# These stubs were autogenerated by stubgen and then hacked
# to pieces to ensure we had something other than "Any" types
# where using external classes to instantiate event subclasses
# in events/types.py.
#
# This goes away whe... |
algorithms/appo/policy_manager.py | magicly/sample-factory | 320 | 11171056 | import random
import numpy as np
class PolicyManager:
"""
This class currently implements the most simple mapping between agents in the envs and their associated policies.
We just pick a random policy from the population for every agent at the beginning of the episode.
Methods of this class can pote... |
src/deutschland/strahlenschutz/__init__.py | andreasbossard/deutschland | 445 | 11171059 | <reponame>andreasbossard/deutschland
# flake8: noqa
"""
ODL-Info API
Daten zur radioaktiven Belastung in Deutschland # noqa: E501
The version of the OpenAPI document: 0.0.1
Generated by: https://openapi-generator.tech
"""
__version__ = "1.0.0"
# import ApiClient
from deutschland.strahlenschutz.ap... |
plenum/server/consensus/primary_selector.py | IDunion/indy-plenum | 148 | 11171067 | from abc import ABCMeta, abstractmethod
from typing import List
from common.exceptions import LogicError
from plenum.server.batch_handlers.node_reg_handler import NodeRegHandler
from stp_core.common.log import getlogger
logger = getlogger()
class PrimariesSelector(metaclass=ABCMeta):
@abstractmethod
def se... |
dnachisel/builtin_specifications/codon_optimization/MaximizeCAI.py | simone-pignotti/DnaChisel | 124 | 11171070 | <reponame>simone-pignotti/DnaChisel
import numpy as np
from .BaseCodonOptimizationClass import BaseCodonOptimizationClass
from ...Specification.SpecEvaluation import SpecEvaluation
class MaximizeCAI(BaseCodonOptimizationClass):
"""Codon-optimize a coding sequence for a given species. Maximizes the CAI.
To b... |
graph__networkx__d3__dot_graphviz/custom_graph.py | DazEB2/SimplePyScripts | 117 | 11171072 | <filename>graph__networkx__d3__dot_graphviz/custom_graph.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://networkx.readthedocs.io/en/stable/examples/drawing/weighted_graph.html
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge('a', 'b')
G.ad... |
Lib/test/test_compiler/testcorpus/02_expr_attr.py | diogommartins/cinder | 1,886 | 11171074 | <gh_stars>1000+
a.b
a.b.c.d
|
tests/test_utils.py | edouard-lopez/colorful | 517 | 11171077 | # -*- coding: utf-8 -*-
"""
colorful
~~~~~~~~
Terminal string styling done right, in Python.
:copyright: (c) 2017 by <NAME> <<EMAIL>>
:license: MIT, see LICENSE for more details.
"""
import os
import pytest
# do not overwrite module
os.environ['COLORFUL_NO_MODULE_OVERWRITE'] = '1'
import colo... |
social/apps/flask_app/template_filters.py | raccoongang/python-social-auth | 1,987 | 11171079 | from social_flask.template_filters import backends, login_redirect
|
plugins/normalise/setup.py | eesprit/alerta-contrib | 114 | 11171087 |
from setuptools import setup, find_packages
version = '5.3.1'
setup(
name="alerta-normalise",
version=version,
description='Alerta plugin for alert normalisation',
url='https://github.com/alerta/alerta-contrib',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
packages=find_pac... |
asv/benchmarks/benchmarks.py | karban8/tardis | 176 | 11171091 | # Write the benchmarking functions here.
# See "Writing benchmarks" in the asv docs for more information.
import numpy as np
from tardis.tests import montecarlo_test_wrappers as montecarlo
LINE_SIZE = 10000000
class TimeSuite:
"""
An example benchmark that times the performance of various kinds
of itera... |
capstone/capweb/templatetags/api_url.py | rachelaus/capstone | 134 | 11171095 | from django import template
from capapi import api_reverse
register = template.Library()
@register.simple_tag()
def api_url(url_name, *args, **kwargs):
""" Like the {% url %} tag, but output includes the full domain. """
return api_reverse(url_name, args=args, kwargs=kwargs) |
tests/unit/test_utils.py | 0xflotus/xfer | 244 | 11171142 | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in th... |
conf/config.py | bopopescu/pspider | 168 | 11171163 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Created on : 2019-03-12 15:44
# @Author : zpy
# @Software: PyCharm
dev = True
if dev:
from conf.dev_config import *
else:
from conf.product_config import * |
bootcamp/messenger/tests.py | elviva404/bootcamp | 115 | 11171173 | <reponame>elviva404/bootcamp
from django.test import TestCase, Client
from django.contrib.auth.models import User
class MessengerViewsTest(TestCase):
def setUp(self):
self.client = Client()
User.objects.create_user(
username='test_user',
email='<EMAIL>',
passwor... |
pyjswidgets/pyjamas/ui/TextBoxBase.ie6.py | takipsizad/pyjs | 739 | 11171218 | <gh_stars>100-1000
class TextBoxBase:
def getCursorPos(self):
JS("""
try {
var elem = this['getElement']();
var tr = elem['document']['selection']['createRange']();
if (tr['parentElement']()['uniqueID'] != elem['uniqueID'])
return -1;
r... |
software/glasgow/applet/interface/jtag_probe/__init__.py | whitequark/glasgow | 280 | 11171246 | # Ref: IEEE Std 1149.1-2001
# Accession: G00018
# Transport layers
# ----------------
#
# The industry has defined a number of custom JTAG transport layers, such as cJTAG, Spy-Bi-Wire,
# and so on. As long as these comprise a straightforward serialization of the four JTAG signals,
# it is possible to reuse most of thi... |
scripts/examples/Arduino/Portenta-H7/04-Image-Filters/cartoon_filter.py | jiskra/openmv | 1,761 | 11171263 | # Cartoon Filter
#
# This example shows off a simple cartoon filter on images. The cartoon
# filter works by joining similar pixel areas of an image and replacing
# the pixels in those areas with the area mean.
import sensor, image, time
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE) # or GRAYSCALE...
sensor.s... |
tests/modelwrapper_test.py | llv22/baal_tf2.4_mac | 575 | 11171281 | <gh_stars>100-1000
import math
import unittest
from unittest.mock import Mock
import numpy as np
import pytest
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from baal.modelwrapper import ModelWrapper, mc_inference
from baal.utils.metrics import ClassificationReport
class DummyDa... |
sonarqube/tests/test_check.py | vbarbaresi/integrations-core | 663 | 11171296 | # (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import pytest
from .common import PROJECT
from .metrics import WEB_METRICS
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures('dd_environment')]
def test_check(aggregator, dd_run... |
bh_modules/rubykeywords.py | jfcherng-sublime/ST-BracketHighlighter | 1,047 | 11171297 | """
BracketHighlighter.
Copyright (c) 2013 - 2016 <NAME> <<EMAIL>>
License: MIT
"""
import re
RE_DEF = re.compile(r"\s*(?:(?:private|public|protected)\s+)?(def).*?")
RE_KEYWORD = re.compile(r"(\s*\b)[\w\W]*")
SPECIAL_KEYWORDS = ('do',)
NORMAL_KEYWORDS = ('for', 'until', 'unless', 'while', 'class', 'module', 'if', 'be... |
libs/ConfigHelpers.py | JanSkalny/RootTheBox | 635 | 11171302 | import logging
import imghdr
import hashlib
from base64 import b64decode
from tornado.options import options
from datetime import datetime
from past.builtins import basestring
from libs.XSSImageCheck import is_xss_image
from libs.ValidationError import ValidationError
def save_config():
logging.info("Saving cur... |
pymde/preprocess/test_data_matrix.py | kruus/pymde | 379 | 11171315 | <filename>pymde/preprocess/test_data_matrix.py
import numpy as np
import scipy.sparse as sp
import torch
from pymde import preprocess
import pymde.testing as testing
@testing.cpu_and_cuda
def test_all_distances_numpy(device):
del device
np.random.seed(0)
data_matrix = np.random.randn(4, 2)
graph = pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.