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 |
|---|---|---|---|---|
dashlivesim/dashlib/mediasegmentfilter.py | Dash-Industry-Forum/dash-live-source-simulator | 133 | 11029215 | """Filter media segment for live streams."""
# The copyright in this software is being made available under the BSD License,
# included below. This software may be subject to other third party and contributor
# rights, including patent rights, and no such rights are granted under this license.
#
# Copyright (c) 2015, ... |
cpu/Other/cpu/pin.py | erhu666/computer | 117 | 11029234 | <reponame>erhu666/computer<filename>cpu/Other/cpu/pin.py
# coding=utf-8
MSR = 1
MAR = 2
MDR = 3
RAM = 4
IR = 5
DST = 6
SRC = 7
A = 8
B = 9
C = 10
D = 11
DI = 12
SI = 13
SP = 14
BP = 15
CS = 16
DS = 17
SS = 18
ES = 19
VEC = 20
T1 = 21
T2 = 22
MSR_OUT = MSR
MAR_OUT = MAR
MDR_OUT = MDR
RAM_OUT = RAM
IR_OUT = IR
DST_OUT ... |
qanta/ingestion/annotated_mapping.py | Mshivam2409/qb | 122 | 11029246 | <filename>qanta/ingestion/annotated_mapping.py
from unidecode import unidecode
import pickle
from typing import Dict, List, Optional, Tuple
import os
import yaml
import string
import re
from qanta.util.constants import WIKI_TITLES_PICKLE
from pedroai.result import Ok, Err, Result
PUNCTUATION = string.punctuation
PAREN... |
prospr/dataloader.py | dellacortelab/ProSPr | 422 | 11029253 | import numpy as np
import torch
import os
import pickle as pkl
import sys
import re
import scipy.io
from Bio import SeqIO
from Bio.PDB.DSSP import DSSP
from Bio.PDB import PDBParser
from prospr.nn import INPUT_DIM, CROP_SIZE
def seq_to_mat(seq):
"""Convert a sequence into Nx21 matrix for input vector"""
aa_or... |
predict_segmentation.py | zippyai/TensorFlow-ENet | 280 | 11029259 | import tensorflow as tf
import os
import matplotlib.pyplot as plt
from enet import ENet, ENet_arg_scope
from preprocessing import preprocess
from scipy.misc import imsave
import numpy as np
slim = tf.contrib.slim
image_dir = './dataset/test/'
images_list = sorted([os.path.join(image_dir, file) for file in os.listdir(i... |
examples/mlp_mnist.py | MilesQLi/nnet | 157 | 11029268 | #!/usr/bin/env python
# coding: utf-8
import time
import numpy as np
import sklearn.datasets
import nnet
def run():
# Fetch data
mnist = sklearn.datasets.fetch_mldata('MNIST original', data_home='./data')
split = 60000
X_train = mnist.data[:split]/255.0
y_train = mnist.target[:split]
X_test =... |
setup.py | osamai/ffpass | 382 | 11029288 | #!/usr/bin/env python3
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="ffpass",
version="0.5.0",
author="<NAME>",
license="MIT",
author_email="<EMAIL>",
description="Import and Export passwords for F... |
confluent-tensorflow-io-kafka-simplified.py | ora0600/hivemq-mqtt-tensorflow-kafka-realtime-iot-machine-learning-training-inference | 294 | 11029294 | import tensorflow as tf
import datetime
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512,... |
torchsketch/__init__.py | songyzh/torchsketch | 182 | 11029297 | <reponame>songyzh/torchsketch
from torchsketch import data
from torchsketch import networks
from torchsketch import utils
__version__ = '0.1.0' |
statsforecast/models.py | Nixtla/statsforecast | 483 | 11029301 | <gh_stars>100-1000
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models.ipynb (unless otherwise specified).
__all__ = ['ses', 'adida', 'historic_average', 'croston_classic', 'croston_sba', 'croston_optimized',
'seasonal_window_average', 'seasonal_naive', 'imapa', 'naive', 'random_walk_with_drift', 'window... |
Src/StdLib/Lib/popen2.py | cwensley/ironpython2 | 6,989 | 11029320 | """Spawn a command with pipes to its stdin, stdout, and optionally stderr.
The normal os.popen(cmd, mode) call spawns a shell command and provides a
file interface to just the input or output of the process depending on
whether mode is 'r' or 'w'. This module provides the functions popen2(cmd)
and popen3(cmd) which r... |
frappe/patches/v12_0/webpage_migrate_description_to_meta_tag.py | chentaoz/frappe | 3,755 | 11029355 | import frappe
def execute():
web_pages = frappe.get_all('Web Page', ['name', 'description'])
for web_page in web_pages:
if web_page.description and web_page.route:
doc = frappe.new_doc('Website Route Meta')
doc.name = web_page.route
doc.append('meta_tags', {
'key': 'description',
'value': web_pag... |
Lib/test/test_compiler/sbs_code_tests/74_class_kwargs.py | diogommartins/cinder | 1,886 | 11029356 | <reponame>diogommartins/cinder
class Foo(x=42):
pass
# EXPECTED:
[
...,
LOAD_CONST(Code((1, 0))),
...,
LOAD_CONST(42),
LOAD_CONST(('x',)),
CALL_FUNCTION_KW(3),
...
]
|
recipes/Python/576948_Simple_primes_generator/recipe-576948.py | tdiprima/code | 2,023 | 11029364 | <reponame>tdiprima/code<filename>recipes/Python/576948_Simple_primes_generator/recipe-576948.py
"""
Prime number generator
I found it quite simple to implement this generator with the 'any' function
It is certainly not the most optimized algorithm.
Primes list will only grow in the function though.
"""
import ite... |
atlas/foundations_sdk/src/integration/config.py | DeepLearnI/atlas | 296 | 11029365 | <reponame>DeepLearnI/atlas
def _config():
from uuid import uuid4
from os import getcwd
from foundations_contrib.global_state import (
config_manager,
current_foundations_job,
)
from foundations_contrib.global_state import config_manager
from foundations_contrib.local_file_syste... |
fastai_do_not_use/text/__init__.py | anhquan0412/fastai_v1 | 115 | 11029395 | <gh_stars>100-1000
from .learner import *
from .data import *
from .transform import *
|
contrib/python/samples/sample_lob.py | eido5/cubrid | 253 | 11029422 | #sample_lob.py
import _cubrid
con = _cubrid.connect('CUBRID:localhost:33000:demodb:::', 'public')
cur = con.cursor()
cur.prepare('create table test_lob (image BLOB)')
cur.execute()
lob_bind = con.lob()
lob_bind.imports('123.jpg')
cur.prepare("insert into test_lob values (?)")
cur.bind_lob(1, lob_bind)
cur.execute... |
1]. DSA/2]. Algorithms/02]. Sorting Algorithms/Python/Merge_Sort.py | MLinesCode/The-Complete-FAANG-Preparation | 6,969 | 11029459 | <reponame>MLinesCode/The-Complete-FAANG-Preparation
def divide(arr):
if len(arr)>1:
a = arr[:len(arr)//2]
b = arr[len(arr)//2:]
divide(a)
divide(b)
i = j = k = 0
while(i<len(a) and j<len(b)):
if a[i]<b[j]:
arr[k] = a[i]
i+=1... |
unsilence/lib/intervals/Intervals.py | RomanKornev/unsilence | 236 | 11029496 | <filename>unsilence/lib/intervals/Intervals.py<gh_stars>100-1000
from unsilence.lib.intervals.Interval import Interval
class Intervals:
"""
Collection of lib.Intervals.Interval
"""
def __init__(self, interval_list: list = None):
"""
Initializes a new Interval Collection
:param... |
cpp/dyncg/data/sentclf/conllu_to_ix.py | mikejqzhang/sparsemap | 101 | 11029549 | import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('file')
opts = parser.parse_args()
with open(opts.file) as f:
sent, tree = [], []
for line in f:
line = line.strip()
if not line:
sent_s = " ".join(... |
tests/st/ops/ascend/dynamic_shape/test_dynamic_all.py | tianjiashuo/akg | 286 | 11029568 | import sys
from collections.abc import Iterable
from tests.common import boot
from tests.common.test_run.ascend.batchmatmul_run import batchmatmul_execute
from tests.common.test_run import reduce_sum_run
def run_case(*args, **kwargs):
if len(sys.argv) >= 3:
case_name = sys.argv[2]
if len(args) < 2:... |
tests/messages_data/rfc2822/example14.py | unqx/imap_tools | 344 | 11029610 | <filename>tests/messages_data/rfc2822/example14.py
import datetime
from imap_tools import EmailAddress
DATA = dict(
subject='Re: TESTテストテスト',
from_='<EMAIL>',
to=('<EMAIL>',),
cc=(),
bcc=(),
reply_to=('<EMAIL>',),
date=datetime.datetime(2011, 8, 19, 10, 47, 17, tzinfo=datetime.timezone(date... |
python/lbann/onnx/__init__.py | jonesholger/lbann | 194 | 11029615 | import onnx
import numpy as np
ELEM_TYPE = onnx.TensorProto.FLOAT
ELEM_TYPE_NP = np.float32
|
machina/apps/forum_conversation/forum_polls/urls.py | BrendaH/django-machina | 572 | 11029618 | """
Forum polls URLs
================
This module defines URL patterns associated with the django-machina's ``forum_polls``
application.
"""
from django.urls import path
from machina.core.loading import get_class
from machina.core.urls import URLPatternsFactory
class ForumPollsURLPatternsFactory(U... |
pysmi/codegen/intermediate.py | itsmehara/pysmi | 121 | 11029634 | <gh_stars>100-1000
#
# This file is part of pysmi software.
#
# Copyright (c) 2015-2019, <NAME> <<EMAIL>>
# License: http://snmplabs.com/pysmi/license.html
#
import sys
import re
from time import strptime, strftime
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
... |
azure_functions_worker/testutils_lc.py | tonybaloney/azure-functions-python-worker | 277 | 11029638 | <reponame>tonybaloney/azure-functions-python-worker
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict
import base64
import json
import os
import re
import subprocess
import sys
import time
import uuid
from Crypto.Cipher import AES
from Crypto.Hash.S... |
res/PyTorchExamples/examples/LSTM/__init__.py | chogba6/ONE | 255 | 11029639 | import torch
import torch.nn as nn
# model
class net_LSTM(nn.Module):
def __init__(self):
super().__init__()
self.op = nn.LSTM(10, 20, 1)
def forward(self, inputs):
return self.op(inputs[0], (inputs[1], inputs[2]))
_model_ = net_LSTM()
# dummy input for onnx generation
_dummy_ = [t... |
python2/pracmln/mln/learning/sll.py | seba90/pracmln | 123 | 11029666 | # -*- coding: utf-8 -*-
#
# Markov Logic Networks
#
# (C) 2011-2012 by <NAME> (<EMAIL>) and <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without ... |
nova/tests/functional/regressions/test_bug_1943431.py | zjzh/nova | 1,874 | 11029675 | <filename>nova/tests/functional/regressions/test_bug_1943431.py
# Copyright 2021, Red Hat, 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... |
test/programytest/storage/stores/file/store/test_postprocessors.py | cdoebler1/AIML2 | 345 | 11029682 | <filename>test/programytest/storage/stores/file/store/test_postprocessors.py
import os
import os.path
import unittest
from programy.processors.processing import ProcessorCollection
from programy.storage.stores.file.config import FileStorageConfiguration
from programy.storage.stores.file.config import FileStoreConfigur... |
services/ui_backend_service/data/cache/client/cache_worker.py | runsascoded/metaflow-service | 103 | 11029746 | <filename>services/ui_backend_service/data/cache/client/cache_worker.py
import os
import json
import signal
from .cache_action import import_action_class_spec
def best_effort_read(key_paths):
for key, path in key_paths:
try:
with open(path, 'rb') as f:
yield key, f.read()
... |
dynamo/plot/heatmaps.py | xing-lab-pitt/dynamo-release | 236 | 11029752 | import numpy as np
import pandas as pd
import math
import scipy.spatial as ss
import seaborn
from functools import reduce
import warnings
from ..tools.utils import update_dict, flatten
from ..vectorfield.utils import get_jacobian
from ..dynamo_logger import main_info_insert_adata, main_info, main_warning
from .utils i... |
tutorials/eboutique/microservices/cart/src/__init__.py | bhardwajRahul/minos-python | 247 | 11029765 | __author__ = ""
__email__ = ""
__version__ = "0.1.0"
from .aggregates import (
Cart,
CartItem,
)
from .cli import (
main,
)
from .commands import (
CartCommandService,
)
from .queries import (
CartQueryRepository,
CartQueryService,
)
|
examples/pytorch/ScreenerNet/snet_voc.py | 5m477/samples-for-ai | 443 | 11029768 | <reponame>5m477/samples-for-ai
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
from collections import OrderedDict
import torchvision.transforms as transforms
import numpy as np
import os
# =========== dataset ====================
from PIL imp... |
tests/test_config.py | tony/vcspull | 169 | 11029773 | import pathlib
import pytest
from vcspull import config
@pytest.fixture
def load_yaml(tmp_path: pathlib.Path):
def fn(content, dir="randomdir", filename="randomfilename.yaml"):
_dir = tmp_path / dir
_dir.mkdir()
_config = _dir / filename
_config.write_text(content, encoding="utf-... |
client/verta/verta/registry/_verify_io.py | benshaw/modeldb | 835 | 11029774 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import functools
import itertools
import json
from verta.external import six
_ALLOWED_INPUT_TYPES = {
dict,
list,
float,
bool,
type(None),
} | set(six.string_types) | set(six.integer_types)
_ALLOWED_OUTPUT_TYPES = _ALLOWED_INPUT_TYPES | {tuple}
# for u... |
mobilenext/utils/grid.py | zhoudaquan/rethinking_bottleneck_structure_code_release | 153 | 11029790 | <gh_stars>100-1000
import torch
import torch.nn as nn
import numpy as np
from PIL import Image
import pdb
import math
class Grid(object):
def __init__(self, d1, d2, rotate = 1, ratio = 0.5, mode=0, prob=1.):
self.d1 = d1
self.d2 = d2
self.rotate = rotate
self.ratio = ratio
s... |
gff/convert_prodigal_to_gff3.py | senjoro/biocode | 355 | 11029802 | <filename>gff/convert_prodigal_to_gff3.py<gh_stars>100-1000
#!/usr/bin/env python3
"""
Prodigal's 'GFF' output is just a collection of CDS features, which doesn't follow the GFF3
spec's canonical gene model. This script corrects that.
INPUT example:
gi|169887498|gb|CP000948.1| Prodigal_v2.6.3 CDS 3 98 1.7 + 0 ID=1_... |
preprocess/pretrain/filter_and_cleanup_lines.py | ZhiyuanChen/TUPE | 225 | 11029811 | <gh_stars>100-1000
import re
import string
import sys
from collections import Counter
# globals
pending_tail = string.ascii_letters + string.digits + ','
# Filter invalid lines
def is_valid(line):
l = len(line)
if l > 1000000 or l < 50:
return False
count = Counter(line)
alpha_cnt = sum(cou... |
data/logs_model/logs_producer/interface.py | giuseppe/quay | 2,027 | 11029813 | <reponame>giuseppe/quay<filename>data/logs_model/logs_producer/interface.py<gh_stars>1000+
from abc import ABCMeta, abstractmethod
from six import add_metaclass
@add_metaclass(ABCMeta)
class LogProducerInterface(object):
@abstractmethod
def send(self, logentry):
"""
Send a log entry to the con... |
begoneads/exceptions.py | HxxxxxS/begoneads | 336 | 11029819 | <gh_stars>100-1000
class NotElevatedException(Exception):
pass
class InvalidSourceException(Exception):
def __init__(self, source):
self.message = f'{source} is not a valid source'
def __str__(self):
return self.message
|
tests/types/test_resolver_types.py | TheVinhLuong102/Strawberry | 2,062 | 11029830 | <filename>tests/types/test_resolver_types.py
from enum import Enum
from typing import List, Optional, TypeVar, Union
import strawberry
from strawberry.types.fields.resolver import StrawberryResolver
def test_enum():
@strawberry.enum
class Language(Enum):
ENGLISH = "english"
ITALIAN = "italian... |
opal_server/policy/bundles/api.py | mburtless/opal | 367 | 11029833 | import os
from opal_common.confi.confi import load_conf_if_none
from opal_common.git.bundle_maker import BundleMaker
from typing import Optional, List
from fastapi import APIRouter, Depends, Query, HTTPException, status
from pathlib import Path
from git import Repo
from opal_common.git.commit_viewer import CommitView... |
tests/mocks.py | mgorny/python-socks | 158 | 11029857 | import socket
from tests.config import (
TEST_HOST_NAME_IPV4,
PROXY_HOST_NAME_IPV4,
TEST_HOST_NAME_IPV6,
PROXY_HOST_NAME_IPV6
)
def _resolve_local(host):
if host in (TEST_HOST_NAME_IPV4, PROXY_HOST_NAME_IPV4):
return socket.AF_INET, '127.0.0.1'
if host in (TEST_HOST_NAME_IPV6, PROXY_... |
angr/procedures/libc/atoi.py | Kyle-Kyle/angr | 6,132 | 11029859 | <reponame>Kyle-Kyle/angr
import angr
import logging
l = logging.getLogger(name=__name__)
class atoi(angr.SimProcedure):
#pylint:disable=arguments-differ
def run(self, s):
strtol = angr.SIM_PROCEDURES['libc']['strtol']
return strtol.strtol_inner(s, self.state, self.state.memory, 10, True)[1]
|
src/pretalx/submission/migrations/0042_question_is_visible_to_reviewers.py | hrchu/pretalx | 418 | 11029863 | # Generated by Django 2.2.7 on 2019-11-11 20:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("submission", "0041_auto_20191105_0042"),
]
operations = [
migrations.AddField(
model_name="question",
name="is_visib... |
Lib/test/test_import_pep328.py | jimmyyu2004/jython | 332 | 11029869 | # test_import_pep328 - Test various aspects of import
#
# Copyright (c) 2010 by science+computing ag
#
# 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... |
gobbli/model/fasttext/model.py | RTIInternational/gobbli | 276 | 11029875 | <gh_stars>100-1000
import re
import shutil
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
import gobbli.io
from gobbli.docker import maybe_mount, run_contai... |
dso/dso/test/test_constant.py | ryok/deep-symbolic-optimization | 134 | 11029889 | <filename>dso/dso/test/test_constant.py
import pytest
import numpy as np
from dso.library import HardCodedConstant
from dso.config import load_config
from dso.core import DeepSymbolicOptimizer
from dso.test.test_core import model
def test_constant():
valid_cases = np.arange(0, 25, 0.1)
for number in valid_c... |
tests/test_engine/test_update/test_update_pop.py | bobuk/montydb | 478 | 11029960 |
import pytest
from pymongo.errors import WriteError as mongo_write_err
from montydb.errors import WriteError as monty_write_err
def test_update_pop_1(monty_update, mongo_update):
docs = [
{"a": [1, 2, 3]}
]
spec = {"$pop": {"a": 1}}
monty_c = monty_update(docs, spec)
mongo_c = mongo_upd... |
languages/python/exercises/concept/basics/lasagna_test.py | AlexLeSang/v3 | 200 | 11029972 | <reponame>AlexLeSang/v3<filename>languages/python/exercises/concept/basics/lasagna_test.py
import unittest
from lasagna import EXPECTED_BAKE_TIME, bake_time_remaining, preparation_time_in_minutes, elapsed_time_in_minutes
class LasagnaTest(unittest.TestCase):
def test_EXPECTED_BAKE_TIME(self):
self.assert... |
atlas/foundations_core_rest_api_components/src/test/v1/controllers/test_authentication_controller.py | DeepLearnI/atlas | 296 | 11029991 |
from foundations_spec import Spec, let_now, set_up, Mock, let
from mock import patch
class TestAuthenticationController(Spec):
@let_now
def auth_client(self):
constructor = self.patch(
"foundations_authentication.authentication_client.AuthenticationClient",
autospec=True,
... |
extractor/qutoutiao.py | pwh19920920/spiders | 390 | 11029994 | import json
from urllib.parse import urlparse, parse_qs
import requests
# TODO: 支持小视频
def get(url: str) -> dict:
"""
author、title、videos
"""
data = {}
if "new.3qtt.cn" in url: # 短连接转长连接
url = requests.get(url).url
data_url_format = "http://api.1sapp.com/content/getRecommendV3?key={k... |
exercises/pt/exc_02_02_02.py | Jette16/spacy-course | 2,085 | 11030000 | <gh_stars>1000+
from spacy.lang.en import English
nlp = English()
doc = nlp("<NAME> is a PERSON")
# Consulte o código hash para a string com o marcador "PERSON"
person_hash = ____.____.____[____]
print(person_hash)
# Consulte o person_hash para obter o texto novamente
person_string = ____.____.____[____]
print(perso... |
src/app/dummycrypto.py | ojimary/titus | 108 | 11030004 | <reponame>ojimary/titus<gh_stars>100-1000
# Copyright (c) 2009, <NAME>. All rights reserved. See LICENSING for details.
'''
A dummy module to act as a stub for crypto.
'''
import os, struct, pickle
class PublicKey(object):
__slots__ = ('n', 'e', '_data', '_bits')
def __init__(self, data=None, **kwargs):
... |
finquant/monte_carlo.py | shashwat-sanjeev/Portfolio-Analysis | 774 | 11030060 | """The module provides a class ``MonteCarlo`` which is an implementation of the
Monte Carlo method and a class ``MonteCarloOpt`` which allows the user to perform a
Monte Carlo run to find optimised financial portfolios, given an intial portfolio.
"""
import numpy as np
import pandas as pd
import matplotlib.pylab as p... |
google/modules/shopping_search.py | DragonCat1/wechat-robot | 571 | 11030073 | <reponame>DragonCat1/wechat-robot
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from builtins import object
from .utils import get_html, normalize_query
from bs4 import BeautifulSoup
import re
from unidecode import unide... |
vault/tests/test_bench.py | tdimnet/integrations-core | 663 | 11030105 | # (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
@pytest.mark.usefixtures('dd_environment')
def test_run(benchmark, dd_run_check, check, instance):
check = check(instance())
# Run once to get instantiation of config out of the wa... |
deepmath/deephol/train/extractor.py | LaudateCorpus1/deepmath | 830 | 11030110 | <filename>deepmath/deephol/train/extractor.py
"""Extractor for HOLparam models. Tokenizes goals and theorems."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
from deepmath.deephol.train import utils
class Extractor(o... |
utils/cyclic_scheduler.py | ivivan/Imputation_AWS_product | 132 | 11030122 | from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
import math
import torch
class ReduceMaxLROnRestart:
def __init__(self, ratio=0.75):
self.ratio = ratio
def __call__(self, eta_min, eta_max):
return eta_min, eta_max * self.ratio
class ExpReduceMaxLROnIterat... |
ml_logger/wrappers/__init__.py | episodeyang/ml_logger | 107 | 11030129 | <gh_stars>100-1000
from .analysis_wrapper import Analysis |
code/test_data.py | eutychius/encore.ai | 314 | 11030155 | <reponame>eutychius/encore.ai
from data_reader import DataReader
d = DataReader('kanye_west')
print len(d.get_vocab()) |
flows/appconfig.py | sergioisidoro/django-flows | 104 | 11030190 | import django
def _setup():
from flows import statestore
statestore.setup()
if django.VERSION >= (1, 7):
from django.apps import AppConfig
class FlowsAppConfig(AppConfig):
name = 'flows'
def ready(self):
_setup()
else:
_setup()
|
tests/unit/test_query_result.py | 10088/redisgraph-py | 141 | 11030191 | <filename>tests/unit/test_query_result.py<gh_stars>100-1000
from tests.utils import base
class TestQueryResult(base.TestCase):
pass
|
src/explainable_cnn/validators/base_validator.py | MANISH007700/explainable-cnn | 106 | 11030203 | <filename>src/explainable_cnn/validators/base_validator.py<gh_stars>100-1000
class BaseValidator:
def __init__(self):
"""
Validates types of different modules used in the package and raises
error if necessary.
"""
pass
def assert_type(self, obj, obj_type):
"""
... |
tests/components/faa_delays/test_config_flow.py | MrDelik/core | 30,023 | 11030242 | """Test the FAA Delays config flow."""
from unittest.mock import patch
from aiohttp import ClientConnectionError
import faadelays
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.faa_delays.const import DOMAIN
from homeassistant.const import CONF_ID
from homeassistant.exceptions... |
scripts/features.py | kalarea/detection-2016-nipsws | 478 | 11030258 | <reponame>kalarea/detection-2016-nipsws
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
from keras import backend as K
import cv2, numpy as np
import math
import n... |
autogl/module/hpo/suggestion/algorithm/chocolate_random_search.py | general502570/AutoGL | 824 | 11030268 | <reponame>general502570/AutoGL
from ...suggestion.algorithm.base_chocolate_algorithm import BaseChocolateAlgorithm
class ChocolateRandomSearchAlgorithm(BaseChocolateAlgorithm):
"""
The implementation is based on https://github.com/tobegit3hub/advisor
Get the new suggested trials with random search algorit... |
core/char.py | XTJ21/Darknights-server | 112 | 11030279 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Description: Char Build System
from bottle import *
import json
import time
from utils import logger, api, err, file
with open('./serverData/gamedata_const.json', 'r', encoding='utf-8') as f:
constConfig = json.loads(f.read())
log... |
tests/samples/long_variable.py | spamegg1/snoop | 751 | 11030324 | <reponame>spamegg1/snoop<gh_stars>100-1000
import snoop
@snoop.snoop()
def main():
foo = list(range(1000))
return foo
|
plynx/utils/plugin_manager.py | khaxis/plynx | 137 | 11030330 | <reponame>khaxis/plynx<filename>plynx/utils/plugin_manager.py
"""Utils that materialize plugins"""
# pylint: disable=global-statement
import logging
import pydoc
from typing import Any, Dict
from plynx.base.executor import BaseExecutor
from plynx.base.hub import BaseHub
from plynx.base.resource import BaseResource
fro... |
ch09-Basic operation of image/9.shape.py | Anancha/OpenCV-Python-Tutorial | 2,875 | 11030336 | # -*- coding: utf-8 -*-
import cv2
import numpy as np
img = cv2.imread('../data/messi5.jpg', 0) # gray
print(img.shape)
img = cv2.imread('../data/messi5.jpg')
# print(img.shape)
rows, cols, ch = img.shape
print('行/高:', rows, '列/宽:', cols, '通道:', ch)
print(img.size)
print(img.dtype)#uint8
#注意 在 debug 时 img.dtype非常... |
src/ecco/attribution.py | pgfeldman/ecco | 1,391 | 11030352 | import torch
import numpy as np
def saliency(prediction_logit, token_ids_tensor_one_hot, norm=True, retain_graph=True):
# Back-propegate the gradient from the selected output-logit
prediction_logit.backward(retain_graph=retain_graph)
# token_ids_tensor_one_hot.grad is the gradient propegated to ever embe... |
tests/components/evil_genius_labs/test_diagnostics.py | jlmaners/core | 30,023 | 11030420 | """Test evil genius labs diagnostics."""
import pytest
from homeassistant.components.diagnostics import REDACTED
from tests.components.diagnostics import get_diagnostics_for_config_entry
@pytest.mark.parametrize("platforms", [[]])
async def test_entry_diagnostics(
hass, hass_client, setup_evil_genius_labs, conf... |
tests/samples/test-filter-manifest/wrapping/python/setup.py | mlasch/scikit-build | 299 | 11030424 | <reponame>mlasch/scikit-build<filename>tests/samples/test-filter-manifest/wrapping/python/setup.py
from skbuild import setup
def exclude_dev_files(cmake_manifest):
return list(filter(lambda name: not (name.endswith('.a') or name.endswith('.h')), cmake_manifest))
setup(
name="hello",
version="1.2.3",
... |
desktop/core/ext-py/python-openid-2.2.5/openid/test/datadriven.py | kokosing/hue | 5,079 | 11030472 | import unittest
import types
class DataDrivenTestCase(unittest.TestCase):
cases = []
def generateCases(cls):
return cls.cases
generateCases = classmethod(generateCases)
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):
... |
book/mle/contour_loglik_ecological.py | cqlc94/SMC_test | 234 | 11030478 | <filename>book/mle/contour_loglik_ecological.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Plot the contours of the log-likelihood of a theta-logistic model;
see Figure 13.2 in the MLE Chapter for more details.
Notes: this script uses multi-processing to speed things up; this may not work
on certain OSes (s... |
wasm/tests/test_demo.py | mainsail-org/RustPython | 11,058 | 11030496 | import time
import sys
import pytest
RUN_CODE_TEMPLATE = """
var output = "";
save_output = function(text) {{
output += text
}};
var vm = window.rp.vmStore.init('test_vm');
vm.setStdout(save_output);
vm.exec('{}');
vm.destroy();
return output;
"""
@pytest.mark.parametrize(
"script, output", [("print(5)", "5"),... |
tapiriik/payments/payments.py | prohfesor/tapiriik | 1,445 | 11030546 | from datetime import datetime, timedelta
from tapiriik.database import db
from tapiriik.settings import PAYMENT_AMOUNT, PAYMENT_SYNC_DAYS
from bson.objectid import ObjectId
class Payments:
def LogPayment(id, amount, initialAssociatedAccount, email):
# pro-rate their expiry date
expires_in_days = mi... |
torcms/script/autocrud/func_gen_html.py | bukun/TorCMS | 243 | 11030556 | # -*- coding:utf-8 -*-
'''
The functions for generating add, edit, view HTML file.
for each item.
'''
from .html_tpl import HTML_TPL_DICT
def gen_input_add(sig_dic):
'''
Adding for HTML Input control.
'''
if sig_dic['en'] == 'tag_file_download':
html_str = HTML_TPL_DICT['input_add_download'].f... |
auto_derby/single_mode/race/race_score.py | DoctrineAlanK/auto-derby | 235 | 11030565 | # -*- coding=UTF-8 -*-
# pyright: strict
from __future__ import annotations
from ... import mathtools
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .race import Race
from ..context import Context
def compute(ctx: Context, race: Race) -> float:
estimate_order = race.estimate_order(ctx)
if... |
xcessiv/tests/test_models.py | KhaledTo/xcessiv | 1,362 | 11030575 | from __future__ import absolute_import, print_function, division, unicode_literals
import unittest
from xcessiv import models
from sklearn.ensemble import RandomForestClassifier
class TestReturnTrainDataFromJSON(unittest.TestCase):
def setUp(self):
self.extraction = models.Extraction()
self.extrac... |
recipes/Python/578471_Multiple_unique_class_instances__tentative/recipe-578471.py | tdiprima/code | 2,023 | 11030577 | >>> import base
>>> class UniqueSub(base.UniqueBase):
def __init__(self, unique_id, a=1, b=2, **kw_args):
super(UniqueSub, self).__init__(unique_id, **kw_args)
self.a = a
self.b = b
>>> first = UniqueSub("item 1")
>>> second = UniqueSub("item 2", a=4, b=7) # keyword arguments are required
>>... |
bunkai/algorithm/tsunoda_sbd/annotator/constant.py | megagonlabs/bunkai | 149 | 11030578 | #!/usr/bin/env python3
import typing
# \u2605: ★
# \u2606: ☆
# \u266a: ♪
PUNCTUATIONS: str = "。!?.!?.\u2605\u2606\u266a\\**※"
SYMBOLS: str = r"[((\(]笑[)\))]|[((\(]泣[)\))]|[((\(]涙[)\))]"
SPANS_PARENTHESES1_REGEXP: str = r"\((?!涙|笑|泣).+?(?<!涙|笑|泣)\)"
SPANS_PARENTHESES2_REGEXP: str = r"\((?!涙|笑|泣).+?\)"
CHARS_FOR_IGNOR... |
Malmo/samples/Python_examples/decision_tree_test.py | Diffblue-benchmarks/Microsoft-malmo | 3,570 | 11030601 | from __future__ import print_function
from __future__ import division
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2016 Microsoft Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# ass... |
Trakttv.bundle/Contents/Libraries/Shared/plugin/sync/core/task/state/main.py | disrupted/Trakttv.bundle | 1,346 | 11030619 | <reponame>disrupted/Trakttv.bundle<filename>Trakttv.bundle/Contents/Libraries/Shared/plugin/sync/core/task/state/main.py
from plugin.sync.core.task.state.plex_ import SyncStatePlex
from plugin.sync.core.task.state.trakt_ import SyncStateTrakt
import elapsed
import logging
log = logging.getLogger(__name__)
class Syn... |
basic_ML/classification/logistic_regression_GD.py | cllei12/LearningX | 240 | 11030620 | """
logistic_regression_GD.py (author: <NAME> / git: ankonzoid)
"""
import os, random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import log_loss
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def split(fracs, N, seed):
def is_intersect(arr1, arr2):
... |
vul/8-druid-access.py | zx273983653/vulscan | 582 | 11030660 | <filename>vul/8-druid-access.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2014-2015 pocsuite developers (http://seebug.org)
See the file 'docs/COPYING' for copying permission
"""
#命令行
from pocsuite import pocsuite_cli
#验证模块
from pocsuite import pocsuite_verify
#攻击模块
from pocsuite import pocsuite_... |
floo/proxy.py | barrasch/floobits-sublime | 124 | 11030678 | <reponame>barrasch/floobits-sublime
# coding: utf-8
from __future__ import print_function
from collections import defaultdict
import json
import optparse
import platform
import sys
import time
import copy
# Monkey patch editor
timeouts = defaultdict(list)
top_timeout_id = 0
cancelled_timeouts = set()
calling_timeout... |
mudpi/extensions/sequence/__init__.py | icyspace/mudpi-core | 163 | 11030682 | """
Sequence Extension
Enabled actions to be grouped into
automations that can be fired in
a sequenctial order.
"""
import json
import time
import datetime
import threading
from mudpi.utils import decode_event_data
from mudpi.constants import FONT_RESET, FONT_CYAN
from mudpi.logger.Logger import Logge... |
uldlib/const.py | SpiReCZ/ulozto-streamer | 120 | 11030688 | CLI_STATUS_STARTLINE = 5
XML_HEADERS = {
"Accept-Encoding": "gzip",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Go-http-client/1.1",
}
DOWNPOSTFIX = '.udown'
CACHEPOSTFIX = '.ucache'
DOWN_CHUNK_SIZE = 20480
OUTFILE_WRITE_BUF = 20480
|
azure-kusto-data/azure/kusto/data/aio/_models.py | mitsuo0114/azure-kusto-python | 134 | 11030708 | <reponame>mitsuo0114/azure-kusto-python<filename>azure-kusto-data/azure/kusto/data/aio/_models.py
from typing import AsyncIterator
from azure.kusto.data._models import KustoResultRow, BaseStreamingKustoResultTable
class KustoStreamingResultTable(BaseStreamingKustoResultTable):
"""Async Iterator over a Kusto resu... |
tests/functional/services/api/registries/test_get.py | rbrady/anchore-engine | 1,484 | 11030738 | <gh_stars>1000+
from urllib.parse import quote
from tests.functional.services.api.registries import get_registry_info
from tests.functional.services.utils.http_utils import APIResponse, http_get
class TestRegistriesAPIGetReturns200:
def test_list_registries(self, add_and_teardown_registry):
add_resp, api... |
unittest/scripts/py_devapi/scripts/mysqlx_collection_options.py | mueller/mysql-shell | 119 | 11030745 | # Assumptions: test_validation of collection requires MySQL 8.0.19
# 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.c... |
HRI/TFVT_HRI/perception/common/utils.py | WorldEditors/PaddleRobotics | 146 | 11030777 | import io
import cv2
import numpy as np
import pycocotools.mask as coco_mask_util
from paddle.fluid.core import PaddleTensor
from config import YOLOv3_img_resize_to, YOLOv4_img_resize_to
##################################################
# CV related utils
################################################... |
tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_ac94ed17.py | eduardojdiniz/CompNeuro | 2,294 | 11030778 |
# Set random number generator
np.random.seed(2020)
# Initialize step_end and n
step_end = int(t_max / dt)
n = 50
# Intiatialize the list v_n with 50 values of membrane leak potential el
v_n = [el] * n
with plt.xkcd():
# Initialize the figure
plt.figure()
plt.title('Multiple realizations of $V_m$')
plt.xlabe... |
dot_vim/plugged/powerline/tests/test_in_vterm/test_shells.py | gabefgonc/san-francisco-rice-dotfiles | 11,435 | 11030782 | <filename>dot_vim/plugged/powerline/tests/test_in_vterm/test_shells.py
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os
import sys
from time import sleep
from subprocess import check_call
from glob import glob1
from trac... |
pages/tests/test_unit.py | timbortnik/django-page-cms | 113 | 11030785 | <reponame>timbortnik/django-page-cms
# -*- coding: utf-8 -*-
"""Django page CMS unit test suite module."""
from pages.models import Page, Content
from pages.tests.testcase import TestCase
from pages import urlconf_registry as reg
from pages.phttp import get_language_from_request
from pages.phttp import get_request_mock... |
plugin/al/plugin/AL_USDMayaTestPlugin/py/testUSDMayaPythonModuleOnly.py | ika-rporter/maya-usd | 507 | 11030792 | #!/usr/bin/env python
#
# Copyright 2020 Autodesk
#
# 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 ... |
talkgenerator/run.py | korymath/talk-generator | 110 | 11030800 | <gh_stars>100-1000
from talkgenerator import generator
def main(args):
"""Main run method for command line talk generation."""
presentations, slide_deck, output_file = generator.generate_presentation_using_cli_arguments(
args
)
def main_cli():
args = generator.get_argument_parser().parse_arg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.