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 |
|---|---|---|---|---|
Calibration/HcalAlCaRecoProducers/test/AlCaHBHEMuonProducer_cfg.py | ckamtsikis/cmssw | 852 | 12693727 | import FWCore.ParameterSet.Config as cms
process = cms.Process("AlCaHBHEMuon")
process.load('Configuration.StandardSequences.Services_cff')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load("Configuration.StandardSequences.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.MagneticF... |
plugins/dbnd-test-scenarios/src/dbnd_test_scenarios/scenarios_repo.py | busunkim96/dbnd | 224 | 12693758 | <reponame>busunkim96/dbnd
import datetime
import logging
from dbnd._core.utils.project.project_fs import abs_join, relative_path
from dbnd_test_scenarios.utils.data_chaos_monkey.client_scoring_chaos import (
is_chaos_column_10,
)
from targets import target
logger = logging.getLogger(__name__)
_PLUGIN_ROOT = rela... |
models/slimmable/__init__.py | haolibai/dmcp | 119 | 12693769 | # -*- coding:utf-8 -*-
from models.slimmable.us_resnet import us_resnet18, us_resnet50
from models.slimmable.us_mobilenet import us_mobilenet_v2
|
tests/formatter/to_python_test.py | terencehonles/bravado-core | 122 | 12693780 | # -*- coding: utf-8 -*-
from datetime import date
from datetime import datetime
import six
from mock import patch
from bravado_core.formatter import SwaggerFormat
from bravado_core.formatter import to_python
from bravado_core.spec import Spec
if not six.PY2:
long = int
def test_none(minimal_swagger_spec):
... |
deployment/docker flask fit predict/train_model.py | Diyago/ML-DL-scripts | 142 | 12693820 | <reponame>Diyago/ML-DL-scripts
import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA
np.random.seed(0)
# import some data to play with
iris_X, iris_y = datasets.load_iris(return_X_y=True)
indices = np.random.permutation(len(iris_X))
iris_X_train = iris_X[indices[:-10]]
iris_y_train = i... |
saspy/SASLogLexer.py | metllord/saspy | 317 | 12693829 | <filename>saspy/SASLogLexer.py
#
# Copyright SAS Institute
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
setup.py | xlotlu/weresync | 206 | 12693833 | #! /usr/bin/env python3
import os
from setuptools import setup, find_packages
import subprocess
import shutil
class InvalidSetupError(Exception):
pass
def create_mo_files():
"""Converts .po templates to readble .mo files using msgfmt."""
# Avoids this code running on read the docs, since gettext is not... |
test/test_posetrack.py | collector-m/UniTrack | 240 | 12693858 | import os
import pdb
import os.path as osp
import sys
sys.path[0] = os.getcwd()
import cv2
import copy
import json
import yaml
import logging
import argparse
from tqdm import tqdm
from itertools import groupby
import pycocotools.mask as mask_utils
import numpy as np
import torch
from torchvision.trans... |
tests/datatypes/totest-anyURI.py | eLBati/pyxb | 123 | 12693871 | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import unittest
import pyxb.binding.datatypes as xsd
class Test_anyURI (unittest.TestCase):
def testRange (self):
self.fail("Datatype anyURI test not implemented")
if __name__ == ... |
localgraphclustering/GraphLocal.py | vishalbelsare/LocalGraphClustering | 106 | 12693873 | import networkx as nx
import csv
from scipy import sparse as sp
from scipy.sparse import csgraph
import scipy.sparse.linalg as splinalg
import numpy as np
import pandas as pd
import warnings
import collections as cole
from .cpp import *
import random
import gzip
import bz2
import lzma
import multiprocessing as mp
im... |
skidl/netlist_to_skidl_main.py | vkleen/skidl | 700 | 12693878 | <reponame>vkleen/skidl
# -*- coding: utf-8 -*-
# The MIT License (MIT) - Copyright (c) 2016-2021 <NAME>.
"""
Command-line program to convert a netlist into an equivalent SKiDL program.
"""
from __future__ import ( # isort:skip
absolute_import,
division,
print_function,
unicode_literals,
)
import ar... |
njunmt/decoders/transformer_decoder.py | whr94621/NJUNMT-tf | 111 | 12693883 | <filename>njunmt/decoders/transformer_decoder.py
# Copyright 2017 Natural Language Processing Group, Nanjing University, <EMAIL>.
#
# 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... |
migrations/versions/55c778dd35ab_add_default_notebook_to_users.py | snowdensb/braindump | 631 | 12693886 | <gh_stars>100-1000
"""add default notebook to users
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2016-12-17 21:24:03.788486
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by A... |
src/genie/libs/parser/iosxe/tests/ShowPolicyMapType/empty/golden_output10_expected.py | balmasea/genieparser | 204 | 12693913 | expected_output = {
"GigabitEthernet0/1/1": {
"service_policy": {
"output": {
"policy_name": {
"shape-out": {
"class_map": {
"class-default": {
"bytes": 0,
... |
starfish/core/spots/DetectPixels/_base.py | haoxusci/starfish | 164 | 12693916 | <gh_stars>100-1000
from abc import abstractmethod
from typing import Callable, Sequence, Tuple
import numpy as np
from starfish.core.imagestack.imagestack import ImageStack
from starfish.core.intensity_table.decoded_intensity_table import DecodedIntensityTable
from starfish.core.pipeline.algorithmbase import Algorith... |
anima/exc.py | MehmetErer/anima | 101 | 12693928 | # -*- coding: utf-8 -*-
"""This module contains exceptions
"""
class PublishError(RuntimeError):
"""Raised when the published version is not matching the quality
"""
pass
|
src/losses/center_loss.py | Talgin/facerec | 269 | 12693938 | <filename>src/losses/center_loss.py
import os
# MXNET_CPU_WORKER_NTHREADS must be greater than 1 for custom op to work on CPU
#os.environ['MXNET_CPU_WORKER_NTHREADS'] = '2'
import mxnet as mx
# define metric of accuracy
class Accuracy(mx.metric.EvalMetric):
def __init__(self, num=None):
super(Accuracy, s... |
misc/rando.py | jamesray1/casper | 752 | 12693986 | <reponame>jamesray1/casper
from ethereum.tools import tester
from ethereum.utils import sha3, normalize_address
c = tester.Chain()
x = c.contract(open('rando.v.py').read(), language='vyper')
for i in range(10):
x.deposit(sender=tester.keys[i], value=(i+1)*10**15)
c.mine(1)
o = [0] * 10
for i in range(550):
... |
15Flask/day04/demo/demo6_unit_test.py | HaoZhang95/PythonAndMachineLearning | 937 | 12694000 | <filename>15Flask/day04/demo/demo6_unit_test.py
import unittest
from demo.demo5 import app
class DatabaseTestCase(unittest.TestCase):
"""
测试数据库的添加i和删除,需要设置一个单独的数据库,不能使用真实的数据库
"""
def setUp(self):
"""单元测试开始之前执行的操作"""
app.config['TESTING'] = True
app.config['SQLALCHEMY_DAT... |
pypowerbi/imports.py | MoorsTech/pypowerbi | 101 | 12694012 | <reponame>MoorsTech/pypowerbi
# -*- coding: future_fstrings -*-
import requests
import json
import urllib
import re
from requests.exceptions import HTTPError
from .import_class import Import
class Imports:
# url snippets
groups_snippet = 'groups'
imports_snippet = 'imports'
dataset_displayname_snippe... |
tests/__init__.py | robin-173/sayn | 105 | 12694093 | from contextlib import contextmanager
import os
from pathlib import Path
import subprocess
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from ruamel.yaml import YAML
from sayn.database.creator import create as create_db
@contextmanager
def inside_dir(dirpath, fs=dict()):
"""
Execute code... |
packages/syft/src/syft/core/tensor/smpc/mpc_tensor_ancestor.py | vishalbelsare/PySyft | 8,428 | 12694101 | <filename>packages/syft/src/syft/core/tensor/smpc/mpc_tensor_ancestor.py
# stdlib
from typing import Any
from typing import List
# relative
from ..manager import TensorChainManager
from .mpc_tensor import MPCTensor
from .utils import ispointer
class MPCTensorAncestor(TensorChainManager):
def share(self, *parties... |
glad/lang/volt/loader/gl.py | solarane/glad | 2,592 | 12694134 | <filename>glad/lang/volt/loader/gl.py
from glad.lang.common.loader import BaseLoader
from glad.lang.volt.loader import LOAD_OPENGL_DLL
from glad.lang.d.loader.gl import _OPENGL_HAS_EXT as _D_OPENGL_HAS_EXT
_OPENGL_LOADER = \
LOAD_OPENGL_DLL % {'pre':'private', 'init':'open_gl',
'proc':'get_... |
builder/compat.py | f1oat/platform-atmelmegaavr | 515 | 12694215 | <filename>builder/compat.py
# Copyright 2014-present PlatformIO <<EMAIL>>
#
# 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/pytests/unit/states/virt/test_helpers.py | babs/salt | 9,425 | 12694220 | from tests.support.mock import call
def network_update_call(
name,
bridge,
forward,
vport=None,
tag=None,
ipv4_config=None,
ipv6_config=None,
connection=None,
username=None,
password=<PASSWORD>,
mtu=None,
domain=None,
nat=None,
interfaces=None,
addresses=Non... |
tests/views/test_meta_static_pages.py | priyanshu-kumar02/personfinder | 561 | 12694225 | # encoding: utf-8
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
locobot/agent/perception/perception_helpers.py | kandluis/droidlet | 669 | 12694231 | <filename>locobot/agent/perception/perception_helpers.py<gh_stars>100-1000
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import colorsys
import random
import numpy as np
import base64
import io
import torch
import torchvision
import webcolors
from PIL import Image, ImageDraw
from torchvision import transfor... |
Python/Interfacing_C_C++_Fortran/Pybind11/Stats/test.py | Gjacquenot/training-material | 115 | 12694271 | <reponame>Gjacquenot/training-material
#!/usr/bin/env python
import numpy as np
from stats import Statistics, compute_stats
n = 10
data = np.empty(n)
my_stats = Statistics()
for i in range(n):
value = 0.3*i
my_stats.add(value)
data[i] = value
print(my_stats.mean())
my_stats = compute_stats(data)
print(my_... |
webCrawler_scrapy/pipelines.py | lawlite19/PythonCrawler-Scrapy-Mysql-File-Template | 197 | 12694282 | <filename>webCrawler_scrapy/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
import MySQLdb
import MySQLdb.cursors
import code... |
scripts/gt_mots_eval.py | zhuhu00/MOTSFusion_modify | 154 | 12694293 | <reponame>zhuhu00/MOTSFusion_modify
from file_io.import_utils import import_detections, import_segmentations
from file_io.export_utils import export_tracking_result_in_mots_format
from eval.mots_eval.eval import run_mots_eval
from eval.mots_eval.mots_common.io import load_seqmap
from config import Config
from tracker.t... |
torch/testing/_internal/opinfo_helper.py | vuanvin/pytorch | 183 | 12694295 | <reponame>vuanvin/pytorch<filename>torch/testing/_internal/opinfo_helper.py
import collections
import warnings
from functools import partial
import torch
from torch.testing._internal.common_cuda import (TEST_CUDA)
from torch.testing._internal.common_dtype import (
all_types_and_complex_and,
all_types_and_compl... |
docs/conf.py | parth-choudhary/drum | 265 | 12694302 | <reponame>parth-choudhary/drum
from __future__ import unicode_literals
# This file is automatically generated via sphinx-me
from sphinx_me import setup_conf; setup_conf(globals())
|
cointrol/core/models.py | fakegit/cointrol | 967 | 12694320 | <gh_stars>100-1000
from collections import OrderedDict
from django.db import models
from django.db.models import Sum
from django.db.models.signals import post_save
from django.utils import timezone
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
from django.utils.functional imp... |
Chapter08/adding_legend_and_annotations.py | carltyndall/Python-Automation-Cookbook-Second-Edition | 155 | 12694369 | <gh_stars>100-1000
import matplotlib.pyplot as plt
# STEP 2
LEGEND = ('ProductA', 'ProductB', 'ProductC')
DATA = (
('Q1 2017', 100, 30, 3),
('Q2 2017', 105, 32, 15),
('Q3 2017', 125, 29, 40),
('Q4 2017', 115, 31, 80),
)
# STEP 3
POS = list(range(len(DATA)))
VALUESA = [valueA for label, valueA, valueB,... |
PhysicsTools/NanoAOD/python/btagWeightTable_cff.py | Purva-Chaudhari/cmssw | 852 | 12694383 | <filename>PhysicsTools/NanoAOD/python/btagWeightTable_cff.py
import FWCore.ParameterSet.Config as cms
from PhysicsTools.NanoAOD.common_cff import *
from PhysicsTools.NanoAOD.nano_eras_cff import *
btagSFdir="PhysicsTools/NanoAOD/data/btagSF/"
btagWeightTable = cms.EDProducer("BTagSFProducer",
src = cms.InputTag(... |
textbox/evaluator/meteor_evaluator.py | StevenTang1998/TextBox | 347 | 12694395 | <filename>textbox/evaluator/meteor_evaluator.py
# @Time : 2021/4/19
# @Author : <NAME>
# @Email : <EMAIL>
"""
textbox.evaluator.meteor_evaluator
#######################################
"""
import numpy as np
from nltk.translate.meteor_score import meteor_score
from textbox.evaluator.abstract_evaluator import Abstr... |
cmsplugin_cascade/admin.py | teklager/djangocms-cascade | 139 | 12694400 | <filename>cmsplugin_cascade/admin.py
from urllib.parse import urlparse
import requests
from django.contrib import admin
from django.contrib.sites.shortcuts import get_current_site
from django.forms import Media, widgets
from django.db.models import Q
from django.http import JsonResponse, HttpResponseForbidden, HttpRes... |
qt_material/resources/__init__.py | 5yutan5/qt-material | 692 | 12694405 | <reponame>5yutan5/qt-material<gh_stars>100-1000
from .generate import ResourseGenerator, RESOURCES_PATH
|
test/test_extractor.py | Usama0121/flashtext | 5,330 | 12694453 | <reponame>Usama0121/flashtext
from flashtext import KeywordProcessor
import logging
import unittest
import json
logger = logging.getLogger(__name__)
class TestKeywordExtractor(unittest.TestCase):
def setUp(self):
logger.info("Starting...")
with open('test/keyword_extractor_test_cases.json') as f:... |
aat/core/data/trade.py | mthomascarcamo/aat | 305 | 12694456 | <filename>aat/core/data/trade.py
from datetime import datetime
from typing import Any, Dict, List, Optional, Type, Union
from .cpp import _CPP, _make_cpp_trade
from .order import Order
from ..instrument import Instrument
from ..exchange import ExchangeType
from ...config import DataType, Side
class Trade(object):
... |
.evergreen/ocsp/mock_ocsp_responder.py | tanlisu/mongo-php-library | 3,370 | 12694475 | #
# This file has been modified in 2019 by MongoDB Inc.
#
# OCSPBuilder is derived from https://github.com/wbond/ocspbuilder
# OCSPResponder is derived from https://github.com/threema-ch/ocspresponder
# Copyright (c) 2015-2018 <NAME> <<EMAIL>>
# Permission is hereby granted, free of charge, to any person obtaining a... |
posthog/migrations/0051_precalculate_cohorts.py | avoajaugochukwu/posthog | 7,409 | 12694480 | <filename>posthog/migrations/0051_precalculate_cohorts.py
# Generated by Django 3.0.5 on 2020-05-07 18:22
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("post... |
tripletloss/tripletlosslayer.py | YoungerGao/tripletloss | 283 | 12694502 | <reponame>YoungerGao/tripletloss
# --------------------------------------------------------
# TRIPLET LOSS
# Copyright (c) 2015 Pinguo Tech.
# Written by <NAME>
# --------------------------------------------------------
"""The data layer used during training a VGG_FACE network by triplet loss.
"""
import caffe
import ... |
sleepypuppy/admin/models.py | hexlism/css_platform | 952 | 12694530 | # Copyright 2015 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
Algo and DSA/LeetCode-Solutions-master/Python/relative-sort-array.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 12694535 | <reponame>Sourav692/FAANG-Interview-Preparation<gh_stars>1000+
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def relativeSortArray(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: List[int]
"""
lookup = {v: i for i, v in enumerate(... |
corehq/apps/cleanup/management/commands/purge_docs.py | dimagilg/commcare-hq | 471 | 12694543 | import sys
from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from corehq.util.couch import get_db_by_doc_type
class Command(BaseCommand):
help = "Purge ALL documents of a particular type. E.g. purge_docs MyDocType,AnotherOne"
def handle(self, doc_types, *args,... |
scripts/autosample.py | bcnoexceptions/mtgencode | 159 | 12694565 | <gh_stars>100-1000
#!/usr/bin/env python
import sys
import os
import subprocess
import random
def extract_cp_name(name):
# "lm_lstm_epoch50.00_0.1870.t7"
if not (name[:13] == 'lm_lstm_epoch' and name[-3:] == '.t7'):
return None
name = name[13:-3]
(epoch, vloss) = tuple(name.split('_'))
retu... |
tensorflow_addons/rnn/peephole_lstm_cell.py | leondgarse/addons | 1,560 | 12694568 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
Source/prj/main/ProjectConfigChanger.py | fairhopeweb/Projeny | 752 | 12694574 |
import mtm.util.YamlSerializer as YamlSerializer
from mtm.util.Assert import *
import mtm.ioc.Container as Container
from mtm.ioc.Inject import Inject
from mtm.ioc.Inject import InjectMany
import mtm.ioc.IocAssertions as Assertions
from mtm.util.Platforms import Platforms
from prj.main.ProjenyConstants import Proj... |
pybotters/models/experimental/__init__.py | maruuuui/pybotters | 176 | 12694581 | from typing import Tuple
from .bybit import BybitInverseDataStore, BybitUSDTDataStore
__all__: Tuple[str, ...] = (
'BybitInverseDataStore',
'BybitUSDTDataStore',
)
|
tests/test_issue_11.py | alekseyl1992/pyrobuf | 578 | 12694607 | def test_before_overflow():
from issue_11_proto import A
a = A()
a.a0 = 0x7FFFFFFF
assert A.FromString(a.SerializeToString()).a0 == 2147483647
def test_after_overflow():
from issue_11_proto import A
a = A()
a.a0 = 0x80000000
assert A.FromString(a.SerializeToString()).a0 == 2147483648
|
platypush/plugins/zigbee/mqtt/__init__.py | BlackLight/platypush | 228 | 12694622 | import json
import threading
from queue import Queue
from typing import Optional, List, Any, Dict, Union
from platypush.message.response import Response
from platypush.plugins.mqtt import MqttPlugin, action
from platypush.plugins.switch import SwitchPlugin
class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin): # lgtm ... |
dsebm/svhn_utilities.py | leyiweb/Adversarially-Learned-Anomaly-Detection | 125 | 12694623 | # TensorFlow implementation of a DCGAN model for SVHN
import tensorflow as tf
init_kernel = tf.contrib.layers.xavier_initializer()
image_size = 32
learning_rate = 0.003
batch_size = 32
kernel_conv_size = 3
filters_conv = 64
filters_fc = 128
strides_conv = 2
def UnPooling2x2ZeroFilled(x):
# https://github.com/te... |
adb/systrace/catapult/systrace/systrace/monitor_unittest.py | mohanedmoh/TBS | 2,151 | 12694638 | # Copyright 2016 The Chromium 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 os
import unittest
from systrace import decorators
from systrace import update_systrace_trace_viewer
SCRIPT_DIR = os.path.dirname(os.path.abspath(__... |
mmd_tools/panels/prop_bone.py | lsr123/PX4-loacl_code | 822 | 12694643 | # -*- coding: utf-8 -*-
from bpy.types import Panel
class MMDBonePanel(Panel):
bl_idname = 'BONE_PT_mmd_tools_bone'
bl_label = 'MMD Bone Tools'
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = 'bone'
@classmethod
def poll(cls, context):
return context.mode == 'E... |
server/tests-py/test_schema_duplication.py | gh-oss-contributor/graphql-engine-1 | 27,416 | 12694646 | #!/usrbin/env python3
import pytest
from validate import check_query_f
@pytest.mark.usefixtures('per_method_tests_db_state')
class TestSchemaDuplication:
@classmethod
def dir(cls):
return "queries/schema/duplication/"
def test_create_action_followed_by_track_table(self, hge_ctx):
check_q... |
phy/cluster/__init__.py | fjflores/phy | 118 | 12694650 | # -*- coding: utf-8 -*-
# flake8: noqa
"""Manual clustering facilities."""
from ._utils import ClusterMeta, UpdateInfo
from .clustering import Clustering
from .supervisor import Supervisor, ClusterView, SimilarityView
from .views import * # noqa
|
sdk/python/pulumi_azure/iot/time_series_insights_event_source_eventhub.py | henriktao/pulumi-azure | 109 | 12694654 | # 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... |
examples/Cuda/ReconstructionSystem/profile/scripts/draw_mc_time.py | devshank3/Open3D | 113 | 12694660 | import matplotlib.pyplot as plt
import numpy as np
def draw_text(ax, x, y):
max_y = np.max(y)
for i, v in enumerate(y):
text = str(y[i])
ax.text(x[i] - 0.045 * len(text), y[i],
r'\textbf{' + text + '}')
def draw_error_bar(ax, x, xticks, y_gpu, e_gpu, title, ylabel):
offse... |
cookbook/gravmag_transform_rtp.py | XuesongDing/fatiando | 179 | 12694664 | <gh_stars>100-1000
"""
GravMag: Reduction to the pole of a total field anomaly using FFT
"""
from fatiando import mesher, gridder, utils
from fatiando.gravmag import prism, transform
from fatiando.vis import mpl
# Direction of the Geomagnetic field
inc, dec = -60, 0
# Make a model with only induced magnetization
model... |
legacy/backends/processing/processing_base_backend.py | ParikhKadam/zenml | 1,275 | 12694670 | # Copyright (c) ZenML GmbH 2020. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
build/util/lastchange.py | zealoussnow/chromium | 14,668 | 12694693 | <gh_stars>1000+
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
lastchange.py -- Chromium revision fetching utility.
"""
from __future__ import print_function
import argparse... |
Testing/elx_compare_overlap.py | eliseemond/elastix | 318 | 12694700 | <reponame>eliseemond/elastix
import sys, subprocess
import os
import os.path
import shutil
import re
import glob
from optparse import OptionParser
#-------------------------------------------------------------------------------
# the main function
# Below we deform the moving image segmentation by the current result a... |
plenum/test/metrics/helper.py | andkononykhin/plenum | 148 | 12694710 | <reponame>andkononykhin/plenum
from datetime import datetime, timedelta
from numbers import Number
from random import choice, uniform, gauss, random, randint
from typing import List, Union
from plenum.common.metrics_collector import MetricsName, MetricsEvent, MetricsCollector
from plenum.common.value_accumulator impor... |
src/0485.max-consecutive-ones/max-consecutive-ones.py | lyphui/Just-Code | 782 | 12694737 | <gh_stars>100-1000
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
res = cnt = 0
for i in nums:
if i:
cnt += 1
else:
if cnt:
res = max(res, cnt)
cnt = 0
return max(res, c... |
albu/src/carvana_eval.py | chritter/kaggle_carvana_segmentation | 447 | 12694747 | <filename>albu/src/carvana_eval.py
import os
import cv2
import numpy as np
from utils import get_config, get_csv_folds
from dataset.h5like_interface import H5LikeFileInterface
from eval import Evaluator, flip
from dataset.carvana_dataset import CarvanaDataset
class FullImageEvaluator(Evaluator):
def __init__(se... |
plugins/input-syslog/examples/kafka_comsumer.py | andrei-hanciu/open-nti | 229 | 12694764 | <gh_stars>100-1000
import argparse
import json
from kafka import KafkaConsumer, KafkaProducer
parser = argparse.ArgumentParser(description='user input')
parser.add_argument("--kafka", dest="kafka_addr",
help="Provide Kafka Addr : localhost:9092")
parser.add_argument("--topic", dest="topic", defaul... |
PokerRL/eval/rl_br/_util.py | m0n0l0c0/PokerRL | 247 | 12694795 | <reponame>m0n0l0c0/PokerRL<filename>PokerRL/eval/rl_br/_util.py
from PokerRL.game._.rl_env.poker_types.DiscretizedPokerEnv import DiscretizedPokerEnv
from PokerRL.game._.rl_env.poker_types.LimitPokerEnv import LimitPokerEnv
from PokerRL.rl.rl_util import get_builder_from_str, get_env_cls_from_str
def get_env_builder_... |
flaskblog/md/extensions.py | cnxue/Flog | 202 | 12694803 | import re
from marko import block, HTMLRenderer
class PhotoSet(block.BlockElement):
pattern = re.compile(
r' {,3}(!\[([^\[\]\n]+)?\]\(([^)\n]+)\))'
r'( {,3}(!\[([^\[\]\n]+)?\]\(([^)\n]+)\)))*[^\n\S]*$\n?', re.M
)
inline_children = True
def __init__(self, match):
self.children ... |
tests/cli/test_heartbeat.py | nicolasiltis/prefect | 8,633 | 12694810 | <filename>tests/cli/test_heartbeat.py
import pytest
from click.testing import CliRunner
from unittest.mock import MagicMock
from prefect.cli.heartbeat import heartbeat, flow_run
from prefect.utilities.configuration import set_temporary_config
def test_heartbeat_init():
runner = CliRunner()
result = runner.in... |
search/tests/unit/proxy/__init__.py | defendercrypt/amundsen | 2,072 | 12694812 | # Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
|
social_auth/backends/contrib/flickr.py | merutak/django-social-auth | 863 | 12694816 | <reponame>merutak/django-social-auth
from social.backends.flickr import FlickrOAuth as FlickrBackend
|
modules/nltk_contrib/classifier/basicimports.py | h4ck3rm1k3/NLP-project | 123 | 12694863 | <filename>modules/nltk_contrib/classifier/basicimports.py
from nltk_contrib.classifier.attribute import Attribute, Attributes
from nltk_contrib.classifier.confusionmatrix import ConfusionMatrix
from nltk_contrib.classifier.decisionstump import DecisionStump
from nltk_contrib.classifier.decisiontree import DecisionTree
... |
sandbox/grist/test_match_counter.py | nataliemisasi/grist-core | 2,667 | 12694885 | import random
import string
import timeit
import unittest
from collections import Hashable
import six
from six.moves import xrange
import match_counter
from testutil import repeat_until_passes
# Here's an alternative implementation. Unlike the simple one, it never constructs a new data
# structure, or modifies dicti... |
docqa/scripts/show_parameters.py | Willyoung2017/doc-qa | 422 | 12694886 | import argparse
import tensorflow as tf
from docqa.model_dir import ModelDir
import numpy as np
def main():
parser = argparse.ArgumentParser(description='')
parser.add_argument("model")
args = parser.parse_args()
model_dir = ModelDir(args.model)
checkpoint = model_dir.get_best_weights()
print... |
DS&Algo Programs in Python/prime.py | prathimacode-hub/HacktoberFest-2020 | 386 | 12694905 | <reponame>prathimacode-hub/HacktoberFest-2020<gh_stars>100-1000
n = int(input("Enter a number: "))
for i in range(1, n+1):
count = 0
for j in range(1, n+1):
if i%j==0:
count= count+1
if count==2:
print(i)
|
lib/passlib/handlers/postgres.py | Rudi9719/booksearch-web | 674 | 12694921 | """passlib.handlers.postgres_md5 - MD5-based algorithm used by Postgres for pg_shadow table"""
#=============================================================================
# imports
#=============================================================================
# core
from hashlib import md5
import re
import logging; ... |
waymo_open_dataset/latency/examples/2d_challenge/pytorch/wod_latency_submission/__init__.py | mirtaheri/waymo-open-dataset | 1,814 | 12694924 | <reponame>mirtaheri/waymo-open-dataset<filename>waymo_open_dataset/latency/examples/2d_challenge/pytorch/wod_latency_submission/__init__.py
# Copyright 2021 The Waymo Open Dataset Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in comp... |
neutron/common/coordination.py | congnt95/neutron | 1,080 | 12694948 | <gh_stars>1000+
#
# 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 writin... |
allennlp/data/dataset_readers/multitask.py | MSLars/allennlp | 11,433 | 12694962 | from os import PathLike
from typing import Dict, Iterator, Union, Optional
from allennlp.data.instance import Instance
from allennlp.data.dataset_readers.dataset_reader import (
DatasetReader,
WorkerInfo,
DatasetReaderInput,
)
@DatasetReader.register("multitask")
class MultiTaskDatasetReader(DatasetReade... |
biggan_discovery/there_and_back.py | andreasjansson/OroJaR | 199 | 12694973 | <gh_stars>100-1000
"""
Functions to smooth-out interpolations performed in Z-space. These are based on
<NAME>'s corresponding functions in manim. These are only used for
the purpose of visualization; they do not affect training.
"""
import torch
def smooth(t):
error = torch.sigmoid(torch.tensor(-5.))
return ... |
desktop/core/ext-py/Django-1.11/tests/messages_tests/test_middleware.py | kokosing/hue | 5,079 | 12695000 | import unittest
from django import http
from django.contrib.messages.middleware import MessageMiddleware
class MiddlewareTests(unittest.TestCase):
def setUp(self):
self.middleware = MessageMiddleware()
def test_response_without_messages(self):
"""
MessageMiddleware is tolerant of me... |
integration-tests/r_integration_test/deploy_query_test_model.py | DNCoelho/clipper | 1,403 | 12695010 | <filename>integration-tests/r_integration_test/deploy_query_test_model.py<gh_stars>1000+
from __future__ import absolute_import, division, print_function
import sys
import os
import time
import requests
import json
import logging
import numpy as np
if sys.version_info < (3, 0):
import subprocess32 as subprocess
els... |
bf3s/algorithms/fewshot/imagenet_lowshot.py | alisure-fork/BF3S | 130 | 12695031 | <filename>bf3s/algorithms/fewshot/imagenet_lowshot.py
import os
import numpy as np
import torch
from tqdm import tqdm
import bf3s.algorithms.fewshot.fewshot as fewshot
import bf3s.utils as utils
def compute_top1_and_top5_accuracy(scores, labels):
_, topk_labels = scores.topk(5, 1, True, True)
label_ind = la... |
helpers.py | cubean/ImageSimilarityUsingCntk | 130 | 12695041 | # -*- coding: utf-8 -*-
import sys, os, importlib, pdb, random, datetime, collections, pickle, cv2, requests
import matplotlib.pyplot as plt, numpy as np, scipy.spatial.distance
from sklearn import svm, metrics, calibration
from PIL import Image, ExifTags
random.seed(0)
################################
# ImageInfo c... |
saas/aiops/api/aiops-server/ai_lib/time_series_prediction/algorithm/preprocess/DataPreprocessor.py | iuskye/SREWorks | 407 | 12695042 | <filename>saas/aiops/api/aiops-server/ai_lib/time_series_prediction/algorithm/preprocess/DataPreprocessor.py
# -*- coding: utf-8 -*-
# @author: 丛戎
# @target: 时序预测算法的预处理逻辑
import sys
from ai_lib.time_series_prediction.algorithm.preprocess.data_preprocess_utils import DataPreprocessUtils
PY2 = sys.version_info[0] == ... |
example/geopage_nospatial/models.py | eduardocp/wagtail-geo-widget | 105 | 12695047 | from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from wagtail.core.models import Page
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import StreamFie... |
sample.py | sphh/python-colorlog | 745 | 12695058 | <gh_stars>100-1000
import logging
import colorlog
fmt = "{log_color}{levelname} {name}: {message}"
colorlog.basicConfig(level=logging.DEBUG, style="{", format=fmt, stream=None)
log = logging.getLogger()
log.warning("hello")
|
Python/Collection/CloneList.py | piovezan/SOpt | 148 | 12695071 | <reponame>piovezan/SOpt
current = [0, 1]
someList = []
while True:
for n in range(0, 2):
current[n] += 1
print(current)
someList.append(current[:]) #aqui faz uma cópia da lista e usa referêwncia para esta cópia, não a original
if current == [2, 3]:
break
print(someList)
#https://pt.stac... |
src/olympia/bandwagon/migrations/0001_initial.py | covariant/addons-server | 843 | 12695084 | # Generated by Django 2.2.5 on 2019-09-12 13:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import olympia.amo.fields
import olympia.amo.models
import olympia.translations.fields
class Migration(migrations.Migration):
in... |
xam/model_selection/ordered_cross_validation.py | vishalbelsare/xam | 357 | 12695105 | import numpy as np
import pandas as pd
from sklearn.model_selection import BaseCrossValidator
class OrderedCV(BaseCrossValidator):
"""Cross-validation procedure with order of indexes taken into account.
Say you have an interval [a, b] and you want to make n splits with d test
indexes at each split -- for... |
Presentations/WG2_11/GlassBR_Code/generated/python/Interpolation.py | Danki567/Drasil | 114 | 12695111 | <filename>Presentations/WG2_11/GlassBR_Code/generated/python/Interpolation.py
from __future__ import print_function
import sys
import math
def lin_interp(x1, y1, x2, y2, x):
y = (((y2 - y1) / (x2 - x1)) * (x - x1)) + y1
return y
def indInSeq(arr, v):
for i in range(len(arr) - 1):
if ((arr[i] <= v... |
angr/procedures/linux_kernel/brk.py | Kyle-Kyle/angr | 6,132 | 12695122 | import angr
import logging
l = logging.getLogger(name=__name__)
class brk(angr.SimProcedure):
"""
This implements the brk system call.
"""
#pylint:disable=arguments-differ
def run(self, new_brk):
r = self.state.posix.set_brk(new_brk)
l.debug('brk(%s) = %s', new_brk, r)
re... |
tests/validation/schema/test_enum_validation.py | maroux/flex | 160 | 12695133 | import six
import pytest
from flex.exceptions import ValidationError
from flex.constants import EMPTY
from flex.error_messages import MESSAGES
from tests.utils import (
generate_validator_from_schema,
assert_error_message_equal,
)
#
# minLength validation tests
#
@pytest.mark.parametrize(
'letters',
... |
tests/em/nsem/inversion/test_Problem1D_Adjoint.py | Prithwijit-Chak/simpeg | 358 | 12695135 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
import unittest
from scipy.constants import mu_0
from SimPEG.electromagnetics import natural_source as nsem
from SimPEG import maps
TOL = 1e-4
FLR = 1e-20 # "zero", so if residual below t... |
utils.py | dionysio/haveibeenpwned_lastpass | 101 | 12695139 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import monkeypatch_lastpass
import lastpass
def get_lastpass_vault(username, password, multifactor_password=None):
return lastpass.Vault.open_remote(username, password, multifactor_password) |
tests/xgboost/test_hook_save_scalar_xgboost.py | NRauschmayr/sagemaker-debugger | 133 | 12695154 | # Standard Library
import os
import time
from datetime import datetime
# Third Party
import numpy as np
import pytest
import xgboost
from tests.core.utils import check_tf_events, delete_local_trials, verify_files
# First Party
from smdebug.core.modes import ModeKeys
from smdebug.core.save_config import SaveConfig, Sa... |
lldb/test/API/lang/swift/foundation_value_types/global/TestSwiftFoundationTypeGlobal.py | LaudateCorpus1/llvm-project | 605 | 12695168 | <reponame>LaudateCorpus1/llvm-project
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
import os
import unittest2
class TestSwiftFoundationValueTypeGlobal(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
... |
graphene_sqlalchemy/fields.py | oneome-llc/graphene-sqlalchemy | 947 | 12695183 | <reponame>oneome-llc/graphene-sqlalchemy
import enum
import warnings
from functools import partial
from promise import Promise, is_thenable
from sqlalchemy.orm.query import Query
from graphene import NonNull
from graphene.relay import Connection, ConnectionField
from graphene.relay.connection import connection_adapte... |
examples/plot_calibration_curve.py | leozhoujf/scikit-plot | 2,360 | 12695191 | """
An example showing the plot_calibration_curve method
used by a scikit-learn classifier
"""
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.datasets import make_classifica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.