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 |
|---|---|---|---|---|
services/core/PlatformDriverAgent/platform_driver/interfaces/modbus_tk/tests/modbus_server.py | cloudcomputingabc/volttron | 406 | 12639420 | <reponame>cloudcomputingabc/volttron
from platform_driver.interfaces.modbus_tk.server import Server
from platform_driver.interfaces.modbus_tk import helpers
from platform_driver.interfaces.modbus_tk.client import Client, Field
from platform_driver.interfaces.modbus_tk.maps import Map, Catalog
import serial
from struct... |
bot/exts/holidays/hanukkah/hanukkah_embed.py | ragr07/sir-lancebot | 122 | 12639437 | import datetime
import logging
from discord import Embed
from discord.ext import commands
from bot.bot import Bot
from bot.constants import Colours, Month
from bot.utils.decorators import in_month
log = logging.getLogger(__name__)
HEBCAL_URL = (
"https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&... |
python/app/thirdparty/oneforall/modules/datasets/qianxun.py | taomujian/linbing | 351 | 12639438 | <filename>python/app/thirdparty/oneforall/modules/datasets/qianxun.py<gh_stars>100-1000
from app.thirdparty.oneforall.common.query import Query
class QianXun(Query):
def __init__(self, domain):
Query.__init__(self)
self.domain = domain
self.module = 'Query'
self.source = 'QianXunQu... |
optunity/tests/test_solvers.py | xrounder/optunity | 401 | 12639459 | <filename>optunity/tests/test_solvers.py<gh_stars>100-1000
#!/usr/bin/env python
# A simple smoke test for all available solvers.
import optunity
def f(x, y):
return x + y
solvers = optunity.available_solvers()
for solver in solvers:
# simple API
opt, _, _ = optunity.maximize(f, 100,
... |
python/definitions.py | netcookies/vim-hyperstyle | 132 | 12639469 | """
A list of CSS properties to expand.
Format:
(property, [aliases], unit, [values])
- property : (String) the full CSS property name.
- aliases : (String list) a list of aliases for this shortcut.
- unit : (String) when defined, assumes that the property has a value with a
unit. When the value is numberless (... |
sponsors/migrations/0009_auto_20201103_1259.py | ewjoachim/pythondotorg | 911 | 12639474 | <filename>sponsors/migrations/0009_auto_20201103_1259.py
# Generated by Django 2.0.13 on 2020-11-03 12:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("sponsors", "0008_auto_20201028_1814"),
]
operations = [
... |
Chapter 03/fare_alerter.py | mdlll/Python-Machine-Learning-Blueprints-master | 352 | 12639485 | <gh_stars>100-1000
import sys
import pandas as pd
import numpy as np
import requests
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.s... |
tests/PySys/log_request_end_to_end/test_log_generator.py | itsyitsy/thin-edge.io | 102 | 12639509 | <filename>tests/PySys/log_request_end_to_end/test_log_generator.py
import os
from datetime import datetime, timedelta
from random import randint, shuffle, seed
from typing import Optional
from retry import retry
# this test will look at the date of current files in /var/log/tedge/agent/
# and create example files with ... |
notebook/itertools_repeat.py | vhn0912/python-snippets | 174 | 12639510 | import itertools
sum_value = 0
for i in itertools.repeat(10):
print(i)
sum_value += i
if sum_value > 40:
break
# 10
# 10
# 10
# 10
# 10
for i in itertools.repeat(10, 3):
print(i)
# 10
# 10
# 10
for l in itertools.repeat([0, 1, 2], 3):
print(l)
# [0, 1, 2]
# [0, 1, 2]
# [0, 1, 2]
for fun... |
Lib/test/test_import/data/circular_imports/rebinding2.py | shawwn/cpython | 52,316 | 12639514 | from .subpkg import util
from . import rebinding
util = util.util
|
tests/test_loading.py | ZSD-tim/dayu_widgets | 157 | 12639545 | """
Test MLoading and MLoadingWrapper class
"""
import pytest
from dayu_widgets import dayu_theme
from dayu_widgets.loading import MLoading, MLoadingWrapper
from dayu_widgets.qt import QLabel, QSize
@pytest.mark.parametrize('cls, size', (
(MLoading.tiny, dayu_theme.tiny),
(MLoading.small, dayu_theme.small),
... |
nsot/models/change.py | comerford/nsot | 387 | 12639564 | from __future__ import unicode_literals
from __future__ import absolute_import
from calendar import timegm
import difflib
import json
from django.apps import apps
from django.conf import settings
from django.db import models
from .. import exc, fields
from . import constants
from .site import Site
class Change(mod... |
codes/models/optim/__init__.py | sanchitvohra/EGVSR | 709 | 12639579 | <gh_stars>100-1000
import torch.nn as nn
import torch.optim as optim
def define_criterion(criterion_opt):
if criterion_opt is None:
return None
# parse
if criterion_opt['type'] == 'MSE':
criterion = nn.MSELoss(reduction=criterion_opt['reduction'])
elif criterion_opt['type'] == 'L1':
... |
data_generation/preprocess_data.py | Gkud/deep-regex | 438 | 12639580 | <reponame>Gkud/deep-regex
import re
import random
import sys
import argparse
import os
import csv
def main(arguments):
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--data_dir',
help='Data directory',... |
autogl/module/nas/space/graph_nas.py | THUMNLab/AutoGL | 824 | 12639583 | <filename>autogl/module/nas/space/graph_nas.py
# codes in this file are reproduced from https://github.com/GraphNAS/GraphNAS with some changes.
import typing as _typ
import torch
import torch.nn.functional as F
from nni.nas.pytorch import mutables
from . import register_nas_space
from .base import BaseSpace
from ...m... |
running_modes/reinforcement_learning/logging/link_logging/local_bond_link_reinforcement_logger.py | lilleswing/Reinvent-1 | 183 | 12639590 | <reponame>lilleswing/Reinvent-1<filename>running_modes/reinforcement_learning/logging/link_logging/local_bond_link_reinforcement_logger.py
import numpy as np
import torch
from reinvent_chemistry.logging import fraction_valid_smiles, padding_with_invalid_smiles, \
check_for_invalid_mols_and_create_legend, find_match... |
paperboy/scheduler/remote.py | datalayer-externals/papermill-paperboy | 233 | 12639650 | <reponame>datalayer-externals/papermill-paperboy<gh_stars>100-1000
import requests
from .base import BaseScheduler
class RemoteScheduler(BaseScheduler):
'''Proxy methods to a remote worker instance'''
def __init__(self, *args, **kwargs):
super(RemoteScheduler, self).__init__(*args, **kwargs)
def... |
codes/models/modules/FlowNet_SR_x4.py | CJWBW/HCFlow | 123 | 12639677 | import numpy as np
import torch
from torch import nn as nn
import torch.nn.functional as F
from utils.util import opt_get
from models.modules import Basic
from models.modules.FlowStep import FlowStep
from models.modules.ConditionalFlow import ConditionalFlow
class FlowNet(nn.Module):
def __init__(self, image_shap... |
models/rank/logistic_regression/static_model.py | ziyoujiyi/PaddleRec | 2,739 | 12639689 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
applications/pytorch/cnns/utils/import_helper.py | payoto/graphcore_examples | 260 | 12639696 | # Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import sys
from pathlib import Path
root_folder = str(Path(__file__).parent.parent.absolute())
sys.path.insert(0, root_folder)
|
prince/svd.py | gkbharathy/FactorAnalysisMixedData | 749 | 12639765 | """Singular Value Decomposition (SVD)"""
try:
import fbpca
FBPCA_INSTALLED = True
except ImportError:
FBPCA_INSTALLED = False
from sklearn.utils import extmath
def compute_svd(X, n_components, n_iter, random_state, engine):
"""Computes an SVD with k components."""
# Determine what SVD engine to u... |
third_party/harfbuzz/contrib/tables/grapheme-break-parse.py | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_skia | 264 | 12639786 | import sys
from unicode_parse_common import *
# http://www.unicode.org/Public/UNIDATA/auxiliary/GraphemeBreakProperty.txt
property_to_harfbuzz = {
'CR': 'HB_Grapheme_CR',
'LF': 'HB_Grapheme_LF',
'Control': 'HB_Grapheme_Control',
'Extend': 'HB_Grapheme_Extend',
'Prepend': 'HB_Grapheme_Other',
'SpacingMark'... |
tests/test_loggers/test_console_logger.py | martins0n/etna | 326 | 12639801 | <reponame>martins0n/etna
from tempfile import NamedTemporaryFile
from typing import Sequence
import pytest
from loguru import logger as _logger
from etna.datasets import TSDataset
from etna.loggers import ConsoleLogger
from etna.loggers import tslogger
from etna.metrics import MAE
from etna.metrics import MSE
from et... |
tests/errors_test.py | EdwardBetts/riprova | 114 | 12639818 | # -*- coding: utf-8 -*-
import pytest
from riprova import (ErrorWhitelist, ErrorBlacklist,
NotRetriableError, add_whitelist_error)
def test_error_whitelist():
whitelist = ErrorWhitelist()
assert type(ErrorWhitelist.WHITELIST) is set
assert len(whitelist._list) > 4
assert type(whi... |
prody/apps/evol_apps/evol_filter.py | grandevelia/ProDy | 210 | 12639857 | """Refine MSA application."""
from ..apptools import DevelApp
__all__ = ['evol_filter']
APP = DevelApp('filter', 'filter an MSA using sequence labels')
APP.setExample(
"""Filter sequences in an MSA based on label data.
Following example will filter human sequences:
$ evol filter piwi_seed.slx HUMAN -e""", [])
... |
lib/cherrypyscheduler.py | 0x20Man/Watcher3 | 320 | 12639871 | import logging
from datetime import datetime, timedelta
from threading import Timer, Lock
import os
import json
from cherrypy.process import plugins
logging = logging.getLogger('CPTaskScheduler')
class _Record(object):
''' Default tasks record handler
Will read/write from/to ./tasks.json
'''
lock = L... |
torchbench/datasets/ade20k.py | xperience-ai/torchbench | 143 | 12639882 | import os
from collections import namedtuple
from PIL import Image
from torchvision.datasets.vision import VisionDataset
from torchbench.datasets.utils import download_and_extract_archive
ARCHIVE_DICT = {
"trainval": {
"url": (
"http://data.csail.mit.edu/places/ADEchallenge/"
"ADE... |
Python/tdw/FBOutput/Raycast.py | felixbinder/tdw | 307 | 12639897 | <reponame>felixbinder/tdw<filename>Python/tdw/FBOutput/Raycast.py
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: FBOutput
import tdw.flatbuffers
class Raycast(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsRaycast(cls, buf, offset):
n = tdw.flatbuffers... |
readthedocs/subscriptions/managers.py | rtfd/readthedocs.org | 4,054 | 12639936 | <reponame>rtfd/readthedocs.org
"""Subscriptions managers."""
from datetime import datetime
import stripe
import structlog
from django.conf import settings
from django.db import models
from django.utils import timezone
from readthedocs.core.history import set_change_reason
from readthedocs.subscriptions.utils import ... |
examples/app-event-loop.py | Frekby/glumpy | 1,074 | 12639967 | # -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 <NAME>. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
""" This example shows how to run the event loop manually """
... |
src/rust/iced-x86-py/src/iced_x86/OpCodeOperandKind.py | clayne/iced | 1,018 | 12639975 | <gh_stars>1000+
# SPDX-License-Identifier: MIT
# Copyright (C) 2018-present iced project and contributors
# ⚠️This file was generated by GENERATOR!🦹♂️
# pylint: disable=invalid-name
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
"""
Operand kind
"""
import typing
if typing.TYPE_CHECKING:
from .... |
kashgari/tasks/classification/__init__.py | SharpKoi/Kashgari | 2,422 | 12639979 | # encoding: utf-8
# author: BrikerMan
# contact: <EMAIL>
# blog: https://eliyar.biz
# file: __init__.py
# time: 4:05 下午
from .abc_model import ABCClassificationModel
from .bi_gru_model import BiGRU_Model
from .bi_lstm_model import BiLSTM_Model
from .cnn_attention_model import CNN_Attention_Model
from .cnn_gru_model ... |
datashape/type_symbol_table.py | quantopian-enterprise/datashape | 140 | 12639980 | """
A symbol table object to hold types for the parser.
"""
from __future__ import absolute_import, division, print_function
import ctypes
from itertools import chain
from . import coretypes as ct
__all__ = ['TypeSymbolTable', 'sym']
_is_64bit = (ctypes.sizeof(ctypes.c_void_p) == 8)
def _complex(tp):
"""Simp... |
examples/custom_bootloader/bootloader_override/example_test.py | lovyan03/esp-idf | 8,747 | 12640007 | from __future__ import print_function
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag='Example_GENERIC', target=['esp32', 'esp32s2', 'esp32c3'])
def test_custom_bootloader_impl_example(env, _): # type: ignore
# Test with default build configurations
dut = env.get_dut('main', 'examples/custom_bootloader/b... |
misc/update/python/nntpproxy.py | sy3kic/nZEDb | 472 | 12640011 | <reponame>sy3kic/nZEDb<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import time
import random
import socket
import SocketServer
import socketpool
from lib.pynntp.nntp import nntp
from lib.info import bcolors
from socketpool import util
class NNTPClientConnector(socketpool.Connector, nn... |
hoomd/data/__init__.py | XT-Lee/hoomd-blue | 204 | 12640017 | """Particle data local access."""
from .array import HOOMDArray, HOOMDGPUArray
from .local_access import (AngleLocalAccessBase, BondLocalAccessBase,
ConstraintLocalAccessBase, DihedralLocalAccessBase,
ImproperLocalAccessBase, PairLocalAccessBase,
... |
linepx/datasets/dataloader.py | moliushang/wireframe_ | 148 | 12640020 | import sys
sys.path.append("..")
import datasets.init_dataset as init_dataset
from torch.utils.data.dataloader import *
class myDataLoader(DataLoader):
def __init__(self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=default_collate, pin_memory=False, drop_last=... |
src/confluent/azext_confluent/tests/latest/test_confluent_term_accept_flow.py | haroonf/azure-cli-extensions | 207 | 12640022 | <filename>src/confluent/azext_confluent/tests/latest/test_confluent_term_accept_flow.py
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information... |
app/grandchallenge/participants/apps.py | njmhendrix/grand-challenge.org | 101 | 12640025 | from django.apps import AppConfig
class ParticipantsConfig(AppConfig):
name = "grandchallenge.participants"
def ready(self):
# noinspection PyUnresolvedReferences
import grandchallenge.participants.signals # noqa: F401
|
facebook_business/test/docs_utils.py | MyrikLD/facebook-python-business-sdk | 576 | 12640029 | # Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
ga/Life.py | zhong110020/TSP | 121 | 12640053 | # -*- encoding: utf-8 -*-
SCORE_NONE = -1
class Life(object):
"""个体类"""
def __init__(self, aGene = None):
self.gene = aGene
self.score = SCORE_NONE
|
chrome/test/functional/chromeos_basic.py | nagineni/chromium-crosswalk | 231 | 12640054 | <reponame>nagineni/chromium-crosswalk
#!/usr/bin/env python
# Copyright (c) 2011 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 pyauto_functional
import pyauto
class ChromeosBasic(pyauto.PyUITest):
"""Basic tes... |
examples/pytorch/hilander/utils/deduce.py | ketyi/dgl | 9,516 | 12640095 | <gh_stars>1000+
"""
This file re-uses implementation from https://github.com/yl-1993/learn-to-cluster
"""
import numpy as np
from sklearn import mixture
import torch
import dgl
from .density import density_to_peaks_vectorize, density_to_peaks
__all__ = ['peaks_to_labels', 'edge_to_connected_graph', 'decode', 'build_n... |
npm/templates/deploy.py | PaulLiang1/bazel-distribution | 275 | 12640101 | <reponame>PaulLiang1/bazel-distribution<filename>npm/templates/deploy.py
#!/usr/bin/env python
#
# 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 ... |
capstone/capdb/migrations/0093_auto_20200226_1948.py | rachelaus/capstone | 134 | 12640106 | <reponame>rachelaus/capstone<filename>capstone/capdb/migrations/0093_auto_20200226_1948.py
# Generated by Django 2.2.10 on 2020-02-26 19:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('capdb', '0092_auto_20200225_1511'),
]
operations = [
... |
support/project.py | rknop/amuse | 131 | 12640108 | <gh_stars>100-1000
DIRECTORIES = ['doc', 'src', 'test', 'examples/applications']
|
compile/make_compile_test.py | fuz-woo/gpython | 520 | 12640121 | #!/usr/bin/env python3.4
# Copyright 2018 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""
Write compile_data_test.go
"""
import sys
import ast
import subprocess
inp = [
# Constants
('''1''', "eval"),
(... |
discomll/tests/tests_regression.py | romanorac/discomll | 103 | 12640124 | <reponame>romanorac/discomll<filename>discomll/tests/tests_regression.py
import unittest
import numpy as np
from disco.core import result_iterator
import datasets
class Tests_Regression(unittest.TestCase):
@classmethod
def setUpClass(self):
import chunk_testdata
from disco import ddfs
... |
cupid/utils.py | wjsi/aliyun-odps-python-sdk | 412 | 12640145 | <reponame>wjsi/aliyun-odps-python-sdk<filename>cupid/utils.py<gh_stars>100-1000
# Copyright 1999-2017 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:... |
tools/perf/page_sets/rendering/top_real_world_desktop.py | zealoussnow/chromium | 14,668 | 12640158 | # Copyright 2018 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.
from telemetry.page import shared_page_state
from telemetry.util import wpr_modes
from page_sets.login_helpers import google_login
from page_sets.login_helpe... |
photologue/tests/test_photosize.py | erdnaxe/django-photologue | 364 | 12640161 | from django.core.exceptions import ValidationError
from .factories import PhotoSizeFactory
from .helpers import PhotologueBaseTest
class PhotoSizeNameTest(PhotologueBaseTest):
def test_valid_name(self):
"""We are restricted in what names we can enter."""
photosize = PhotoSizeFactory()
p... |
outside/commonmark/wrapper.py | PowerOlive/urbit | 318 | 12640168 | #!/usr/bin/env python
# Example for using the shared library from python
from ctypes import CDLL, c_char_p, c_long
import sys
import platform
sysname = platform.system()
if sysname == 'Darwin':
cmark = CDLL("build/src/libcmark.dylib")
else:
cmark = CDLL("build/src/libcmark.so")
markdown = cmark.cmark_markd... |
python-leetcode/laozhang/tree/leetcode_1379_.py | sweeneycai/cs-summary-reflection | 227 | 12640178 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding=utf-8
"""
1379. 找出克隆二叉树中的相同节点
"""
from laozhang import TreeNode
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if original and cloned:
if original.val == target.val:
... |
src/back/tests/test_jsonfile.py | khamidou/kite | 136 | 12640181 | import unittest
import tempfile
import fcntl
import os
import datetime
import kite.jsonfile
import tmpdir
from kite.jsonfile import JsonFile
class TestJsonfile(tmpdir.TestCaseWithTempFile):
def test_locked_loading(self):
fd = os.fdopen(self.tmpfd, "w")
fd.write("{}")
fd.close()
json... |
insights/combiners/tests/test_nginx_conf_parser.py | lhuett/insights-core | 121 | 12640205 | <gh_stars>100-1000
from insights.combiners.nginx_conf import _NginxConf
from insights.tests import context_wrap
NGINXCONF = """
user root;
worker_processes 5;
error_log logs/error.log;
pid logs/nginx.pid;
worker_rlimit_nofile 8192;
events {
worker_connections 4096;
}
mail {
server_name mail.exam... |
boto3_type_annotations/boto3_type_annotations/route53domains/paginator.py | cowboygneox/boto3_type_annotations | 119 | 12640229 | <gh_stars>100-1000
from typing import Dict
from datetime import datetime
from botocore.paginate import Paginator
class ListDomains(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
pass
class ListOperations(Paginator):
def paginate(self, SubmittedSince: datetime = None, Paginati... |
mozi/datasets/imdb.py | hycis/Mozi | 122 | 12640247 | <filename>mozi/datasets/imdb.py
import logging
logger = logging.getLogger(__name__)
import os
import cPickle
import numpy as np
import theano
floatX = theano.config.floatX
from mozi.utils.utils import get_file, make_one_hot, pad_sequences
from mozi.datasets.dataset import SingleBlock
class IMDB(SingleBlock):
de... |
src/oci/artifacts/models/generic_artifact_summary.py | Manny27nyc/oci-python-sdk | 249 | 12640281 | <reponame>Manny27nyc/oci-python-sdk
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache... |
examples/djopenid/server/urls.py | cjwatson/python-openid | 176 | 12640314 | """Server URLs."""
from __future__ import unicode_literals
from django.conf.urls import url
from django.views.generic import TemplateView
from djopenid.server.views import endpoint, idPage, idpXrds, processTrustResult, server
urlpatterns = [
url(r'^$', server, name='index'),
url(r'^xrds/$', idpXrds, name='xr... |
skmultilearn/embedding/skembeddings.py | emrecncelik/scikit-multilearn | 763 | 12640324 | from __future__ import absolute_import
from sklearn.base import BaseEstimator
class SKLearnEmbedder(BaseEstimator):
"""Embed the label space using a scikit-compatible matrix-based embedder
Parameters
----------
embedder : sklearn.base.BaseEstimator
a clonable instance of a scikit-compatible ... |
tests/test_01_dxf_entities/test_114_factory.py | jkjt/ezdxf | 515 | 12640335 | # Copyright (c) 2019-2020 <NAME>
# License: MIT License
# created 2019-02-18
import pytest
import ezdxf
from ezdxf.lldxf.extendedtags import ExtendedTags
from ezdxf.entities import factory
from ezdxf.entities.factory import ENTITY_CLASSES
@pytest.fixture(scope="module")
def doc():
return ezdxf.new()
def test_re... |
examples/NCF/data_utils.py | jessezbj/adaptdl | 294 | 12640350 | <reponame>jessezbj/adaptdl
# Code adapted from https://github.com/guoyang9/NCF
import numpy as np
import pandas as pd
import scipy.sparse as sp
import os
import torch.utils.data as data
import hashlib
import adaptdl.env
from urllib.request import urlretrieve
base_url = "https://raw.githubusercontent.com/hexiangna... |
alipay/aop/api/domain/BizActionConsumedAmountsDTO.py | antopen/alipay-sdk-python-all | 213 | 12640355 | <reponame>antopen/alipay-sdk-python-all<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.BizActionConsumedAmountDTO import BizActionConsumedAmountDTO
from alipay.aop.api.domain.BizActionComsumedAmountDTO import B... |
Python/Algorithm/SumDigits.py | piovezan/SOpt | 148 | 12640370 | <filename>Python/Algorithm/SumDigits.py
def sum_digits(digit):
return sum(int(x) for x in digit if x.isdigit())
print(sum_digits('texto123numero456x7'))
#https://pt.stackoverflow.com/q/42280/101
|
mongodb_consistent_backup/Replication/Replset.py | akira-kurogane/mongodb_consistent_backup | 282 | 12640379 | <reponame>akira-kurogane/mongodb_consistent_backup<filename>mongodb_consistent_backup/Replication/Replset.py
import logging
import pymongo.errors
from math import ceil
from time import mktime
from mongodb_consistent_backup.Common import DB, MongoUri, parse_read_pref_tags
from mongodb_consistent_backup.Errors import E... |
machin/parallel/assigner.py | lorenzosteccanella/machin | 287 | 12640380 | <filename>machin/parallel/assigner.py
from typing import Union, List, Dict, Tuple
from machin.utils.logging import default_logger
import psutil
import GPUtil
import numpy as np
import torch as t
import torch.nn as nn
class ModelSizeEstimator:
"""
Size estimator for pytorch modules.
"""
def __init__(s... |
recipes/Python/579035_UNIXlike_which/recipe-579035.py | tdiprima/code | 2,023 | 12640392 | from __future__ import print_function
# which.py
# A minimal version of the UNIX which utility, in Python.
# Author: <NAME> - www.dancingbison.com
# Copyright 2015 <NAME> - http://www.dancingbison.com
import sys
import os
import os.path
import stat
def usage():
sys.stderr.write("Usage: python which.py name\n")
... |
docs/ssi_server.py | isabella232/dygraphs | 1,843 | 12640415 | #!/usr/bin/python
'''
Use this in the same way as Python's SimpleHTTPServer:
./ssi_server.py [port]
The only difference is that, for files ending in '.html', ssi_server will
inline SSI (Server Side Includes) of the form:
<!-- #include virtual="fragment.html" -->
Run ./ssi_server.py in this directory and visit l... |
src/helper_sent.py | kaue/PyBitmessage | 1,583 | 12640416 | <gh_stars>1000+
"""
Insert values into sent table
"""
import time
import uuid
from addresses import decodeAddress
from bmconfigparser import BMConfigParser
from helper_ackPayload import genAckPayload
from helper_sql import sqlExecute
# pylint: disable=too-many-arguments
def insert(msgid=None, toAddress='[Broadcast s... |
BitTornado/clock.py | crossbrowsertesting/BitTornado | 116 | 12640459 | <filename>BitTornado/clock.py
"""Provide a non-decreasing clock() function.
In Windows, time.clock() provides number of seconds from first call, so use
that.
In Unix, time.clock() is CPU time, and time.time() reports system time, which
may not be non-decreasing."""
import time
import sys
_MAXFORWARD = 100
_FUDGE = ... |
esphome/components/fastled_clockless/light.py | OttoWinter/esphomeyaml | 249 | 12640468 | <filename>esphome/components/fastled_clockless/light.py
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.components import fastled_base
from esphome.const import CONF_CHIPSET, CONF_NUM_LEDS, CONF_PIN, CONF_RGB_ORDER
AUTO_LOAD = ["fastled_base"]
CHIPSETS = [
... |
src/dnc/azext_dnc/vendored_sdks/dnc/aio/_dnc.py | haroonf/azure-cli-extensions | 207 | 12640475 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
data/bangladesh-data/crawler_arcgis.py | HiteshMah-Jan/covid19 | 356 | 12640496 | <filename>data/bangladesh-data/crawler_arcgis.py
import requests
import json
import sys
from datetime import date, timedelta
# source: http://iedcr.gov.bd/
url = 'https://services3.arcgis.com/nIl76MjbPamkQiu8/arcgis/rest/services/corona_time_tracker_bd/FeatureServer/0/query?where=1%3D1&returnGeometry=false&outFields=... |
unittest/scripts/py_devapi/scripts/mysqlx_table.py | mueller/mysql-shell | 119 | 12640517 | # Assumptions: ensure_schema_does_not_exist is available
# Assumes __uripwd is defined as <user>:<pwd>@<host>:<plugin_port>
from __future__ import print_function
from mysqlsh import mysqlx
mySession = mysqlx.get_session(__uripwd)
ensure_schema_does_not_exist(mySession, 'py_shell_test')
schema = mySession.create_sche... |
maha/parsers/rules/time/rule.py | TRoboto/Maha | 152 | 12640521 | <gh_stars>100-1000
__all__ = [
"RULE_TIME_YEARS",
"RULE_TIME_MONTHS",
"RULE_TIME_WEEKS",
"RULE_TIME_DAYS",
"RULE_TIME_HOURS",
"RULE_TIME_MINUTES",
"RULE_TIME_AM_PM",
"RULE_TIME_NOW",
"RULE_TIME",
"parse_time",
]
from datetime import datetime
from maha.parsers.rules.time.templat... |
airmozilla/cronlogger/cron.py | mozilla/airmozilla | 115 | 12640524 | <gh_stars>100-1000
import cronjobs
from .decorators import capture
from . import cleanup
@cronjobs.register
@capture
def purge_old_cronlogs():
cleanup.purge_old(verbose=True)
|
plugins/quetz_mamba_solve/quetz_mamba_solve/utils.py | maresb/quetz | 108 | 12640528 | from datetime import datetime, timedelta
from functools import lru_cache, wraps
def timed_lru_cache(hours: int, maxsize: int = 128):
def wrapper_cache(func):
func = lru_cache(maxsize=maxsize)(func)
func.lifetime = timedelta(hours=hours)
func.expiration = datetime.utcnow() + func.lifetime
... |
examples/highfreq/workflow.py | majiajue/qlib | 8,637 | 12640552 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import fire
import qlib
import pickle
from qlib.config import REG_CN, HIGH_FREQ_CONFIG
from qlib.utils import init_instance_by_config
from qlib.data.dataset.handler import DataHandlerLP
from qlib.data.ops import Operators
from qlib.data.data ... |
gnss_ins_sim/sim/sim_data_plot.py | Chris2L/gnss-ins-sim | 693 | 12640565 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# Fielname = sim_data_plot.py
"""
Simulation data plot.
Created on 2020-07-24
@author: dongxiaoguang
"""
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from mpl_toolkits.mplot3d import Axes3D
from . import sim_data
def plot(x, ... |
example/flask-metric/api.py | c3-e/custom-pod-autoscaler | 209 | 12640583 | # Copyright 2019 The Custom Pod Autoscaler Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
tests/functional/python_tests/comment_payment_tests/test_utils.py | drov0/hive | 283 | 12640600 | import sys
sys.path.append("../../")
import hive_utils
from uuid import uuid4
from time import sleep
import logging
LOG_LEVEL = logging.INFO
LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s"
MAIN_LOG_PATH = "hdf_tester_utils.log"
MODULE_NAME = "Comment-Payment-Tester.Utils"
logger = logging.getL... |
humor/datasets/prox_dataset.py | DalhousieAI/humor | 143 | 12640608 | <gh_stars>100-1000
import sys, os
cur_file_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(cur_file_path, '..'))
import os.path as osp
import glob, time, copy, pickle, json
from torch.utils.data import Dataset, DataLoader
from utils.transforms import batch_rodrigues, rotation_matrix_t... |
regtests/c++/returns_subclasses.py | ahakingdom/Rusthon | 622 | 12640648 | <gh_stars>100-1000
'''
returns subclasses
'''
class A:
def __init__(self, x:int):
self.x = x
def method(self) -> int:
return self.x
class B(A):
def foo(self) ->int:
return self.x * 2
class C(A):
def bar(self) ->int:
return self.x + 200
class D(C):
def hey(self) ->int:
return self.x + 1
def some_subc... |
exercises/practice/hamming/hamming_test.py | samr1ddh1/python-1 | 1,177 | 12640653 | <gh_stars>1000+
import unittest
from hamming import (
distance,
)
# Tests adapted from `problem-specifications//canonical-data.json`
class HammingTest(unittest.TestCase):
def test_empty_strands(self):
self.assertEqual(distance("", ""), 0)
def test_single_letter_identical_strands(self):
... |
test/examples/example_script3.py | robintw/recipy | 451 | 12640668 | """
Usage: python -m recipy example_script3.py OUTPUT.npy
"""
from __future__ import print_function
import sys
import numpy
if len(sys.argv) < 2:
print(__doc__, file=sys.stderr)
sys.exit(1)
arr = numpy.arange(10)
arr = arr + 500
# We've made a fairly big change here!
numpy.save(sys.argv[1], arr)
|
dd_1/Part 1/Section 10 - Extras/11 -command line arguments/example8.py | Rebell-Leader/bg | 3,266 | 12640669 | # sometimes we want to specify multiple values for a single argument
import argparse
parser = argparse.ArgumentParser('Prints the squares of a list of numbers, and the cubes of another list.')
parser.add_argument('--sq', help='list of numbers to square', nargs='*', type=float)
parser.add_argument('--cu', help='list ... |
package_control/package_installer.py | zjzh/package_control | 3,373 | 12640670 | import re
import threading
import time
import sublime
from .thread_progress import ThreadProgress
from .package_manager import PackageManager
from .package_disabler import PackageDisabler
from .versions import version_comparable
USE_QUICK_PANEL_ITEM = hasattr(sublime, 'QuickPanelItem')
class PackageInstaller(Packa... |
robogym/envs/dactyl/observation/shadow_hand.py | 0xflotus/robogym | 288 | 12640703 | <reponame>0xflotus/robogym
import abc
import numpy as np
from robogym.observation.mujoco import MujocoObservation
from robogym.robot.shadow_hand.hand_forward_kinematics import FINGERTIP_SITE_NAMES
from robogym.robot.shadow_hand.hand_interface import JOINTS
from robogym.robot.shadow_hand.mujoco.mujoco_shadow_hand impo... |
alipay/aop/api/domain/AlipayEcoContractProcessSyncModel.py | antopen/alipay-sdk-python-all | 213 | 12640723 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.ContractManagerProcessSyncRequest import ContractManagerProcessSyncRequest
class AlipayEcoContractProcessSyncModel(object):
def __init__(self):
self._batch_no = None
... |
lib/django-1.4/django/core/management/commands/validate.py | MiCHiLU/google_appengine_sdk | 790 | 12640726 | from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
help = "Validates all installed models."
requires_model_validation = False
def handle_noargs(self, **options):
self.validate(display_num_errors=True)
|
zerver/webhooks/pagerduty/tests.py | Pulkit007/zulip | 17,004 | 12640750 | <gh_stars>1000+
from zerver.lib.test_classes import WebhookTestCase
class PagerDutyHookTests(WebhookTestCase):
STREAM_NAME = "pagerduty"
URL_TEMPLATE = "/api/v1/external/pagerduty?api_key={api_key}&stream={stream}"
WEBHOOK_DIR_NAME = "pagerduty"
def test_trigger(self) -> None:
expected_messag... |
tonic/torch/__init__.py | Eyalcohenx/tonic | 350 | 12640792 | <filename>tonic/torch/__init__.py
from . import agents, models, normalizers, updaters
__all__ = [agents, models, normalizers, updaters]
|
deprecated/dataloaders/deprecated_examples/affect/mosi_late_fusion.py | kapikantzari/MultiBench | 148 | 12640797 | <filename>deprecated/dataloaders/deprecated_examples/affect/mosi_late_fusion.py<gh_stars>100-1000
from unimodals.common_models import GRU, MLP
from datasets.affect.get_data import get_dataloader
from fusions.common_fusions import Concat
from training_structures.Simple_Late_Fusion import train, test
import torch
import ... |
others/state_machines/python/coin_state_machine.py | CarbonDDR/al-go-rithms | 1,253 | 12640800 | '''
Imagine a machine that gives you a quarter once you put in 25 cents. I suppose if you really like
gumballs that is in someway useful. The machine will wait until it has reached a state of 25 cents,
then it will spit out a quarter. The machine is totally oblivious to what coins were added to reach
its current state,... |
mac/pyobjc-core/PyObjCTest/test_ivar.py | albertz/music-player | 132 | 12640804 | from __future__ import unicode_literals
from PyObjCTools.TestSupport import *
import objc
import sys
from PyObjCTest.instanceVariables import ClassWithVariables
NSObject = objc.lookUpClass('NSObject')
NSAutoreleasePool = objc.lookUpClass('NSAutoreleasePool')
class Base (object):
def __init__(self, ondel):
... |
tests/test_app/library/loans/migrations/0001_initial.py | Pijuli/django-jazzmin | 972 | 12640806 | # Generated by Django 2.2.15 on 2020-10-14 12:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
("books", "0001_initial"),
migrations.swappable_depe... |
textworld/version.py | microsoft/TextWorld | 307 | 12640815 | <filename>textworld/version.py
__version__ = '1.4.5'
__prerelease__ = '1.4.5rc1'
|
predict.py | marcoleewow/LaTeX_OCR | 290 | 12640832 | from scipy.misc import imread
import PIL
import os
from PIL import Image
import numpy as np
from model.img2seq import Img2SeqModel
from model.utils.general import Config, run
from model.utils.text import Vocab
from model.utils.image import greyscale, crop_image, pad_image, downsample_image, TIMEOUT
def i... |
10 Days of Statistics/08 - Day 2 - Compound Event Probability.py | srgeyK87/Hacker-Rank-30-days-challlenge | 275 | 12640856 | <filename>10 Days of Statistics/08 - Day 2 - Compound Event Probability.py
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-mcq-3/problem
# Difficulty: Easy
# Max Score: 10
# Language: Python
# Multiple Choice Question - No code required... |
alex/components/tts/voicerss.py | oplatek/alex | 184 | 12640882 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import alex.utils.cache as cache
import alex.utils.audio as audio
from alex.components.tts import TTSInterface
from alex.components.tts.exceptions import TTSException
from alex.components.tts.preprocessing import TTSPreprocessing
class Voice... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.