max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
examples/scripts/flopy_lake_example.py | andrewcalderwood/flopy | 351 | 10400 | import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import flopy
def run():
workspace = os.path.join("lake")
# make sure workspace directory exists
if not os.path.exists(workspace):
os.makedirs(workspace)
fext = "png"
narg = len(sys.argv)
iarg = 0
if narg > 1:... | 2.859375 | 3 |
P2/Caso2/clustering.py | Ocete/Inteligenica-de-Negocio | 0 | 10401 | # -*- coding: utf-8 -*-
'''
Documentación sobre clustering en Python:
http://scikit-learn.org/stable/modules/clustering.html
http://www.learndatasci.com/k-means-clustering-algorithms-python-intro/
http://hdbscan.readthedocs.io/en/latest/comparing_clustering_algorithms.html
https://joernhees.de... | 3.5 | 4 |
signal_processing/ecg_preproc.py | DeepPSP/cpsc2020 | 1 | 10402 | """
preprocess of (single lead) ecg signal:
band pass --> remove baseline --> find rpeaks --> denoise (mainly deal with motion artefact)
TODO:
1. motion artefact detection,
and slice the signal into continuous (no motion artefact within) segments
2. to add
References:
-----------
[1] https://github... | 2.390625 | 2 |
ocaml/bootstrap.bzl | mobileink/obazl | 0 | 10403 | <filename>ocaml/bootstrap.bzl<gh_stars>0
## mv to //:WORKSPACE.bzl ocaml_configure
load("//ocaml/_bootstrap:ocaml.bzl", _ocaml_configure = "ocaml_configure")
# load("//ocaml/_bootstrap:obazl.bzl", _obazl_configure = "obazl_configure")
load("//ocaml/_rules:ocaml_repository.bzl" , _ocaml_repository = "ocaml_reposi... | 1.25 | 1 |
tsts.py | tedtroxell/metrician | 0 | 10404 | <filename>tsts.py
from metrician.explainations.tests import *
| 0.933594 | 1 |
simple/facenet.py | taflahi/facenet | 5 | 10405 | <reponame>taflahi/facenet
import tensorflow as tf
from .. src.align import detect_face
from .. src import facenet
from .. simple import download_model
import sys
import os
from os.path import expanduser
import copy
import cv2
import numpy as np
from scipy import spatial
minsize = 20 # minimum size of face
threshold =... | 2.28125 | 2 |
athena/athena/errors.py | aculich/openmappr | 19 | 10406 | <gh_stars>10-100
class AthenaError(Exception):
"""base class for all athena exceptions"""
pass
class AthenaMongoError(AthenaError):
"""Class for all mongo related errors"""
pass | 1.632813 | 2 |
tf2stats/__init__.py | TheAntecedent/Quintessence | 1 | 10407 | <filename>tf2stats/__init__.py
from .aggregated_stats import *
from .game_stats import *
from .stat_definitions import * | 1.148438 | 1 |
tests/test_messages/test_inbound/test_manage_all_link_record.py | michaeldavie/pyinsteon | 15 | 10408 | """Test Manage All-Link Record."""
import unittest
from binascii import unhexlify
from pyinsteon.address import Address
from pyinsteon.constants import AckNak, ManageAllLinkRecordAction, MessageId
from pyinsteon.protocol.messages.all_link_record_flags import \
AllLinkRecordFlags
from tests import set_log_levels
fr... | 2.453125 | 2 |
Clock/Clock_Fig3F.py | chAwater/OpenFig | 0 | 10409 | <reponame>chAwater/OpenFig
#!/usr/bin/env python
# coding: utf-8
# # Figure Info.
#
# | Title | Journal | Authors | Article Date | Code Date | Figure | Links |
# |:------|:-------:|:-------:|:------------:|:---------:|:------:|:-----:|
# |A microfluidic approach for experimentally modelling <br> the intercellular cou... | 2.359375 | 2 |
rameniaapp/views/report.py | awlane/ramenia | 0 | 10410 | from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.template import loader
from django.conf import settings
from django.contrib.auth.models import User
from rameniaapp.models import ReviewReport, ProfileReport, NoodleReport, Report, Review, Profile, Noodle
from django.views.generic impor... | 1.976563 | 2 |
pyparser.py | ddurvaux/PyUnpacker | 0 | 10411 | #!/usr/bin/python
#
# This tool is an attempt to automate some taks related
# to malware unpacking.
#
# Most (if not all) of the tricks used in this tool
# directly comes from an excellent course given
# by <NAME> (@nicolasbrulez)
#
# Tool developped by David DURVAUX for Autopsit
# (commercial brand of N-Labs sprl)
#... | 1.984375 | 2 |
mjml/elements/head/mj_style.py | ESA-CCI-ODP/mjml-stub | 23 | 10412 |
from ._head_base import HeadComponent
__all__ = ['MjStyle']
class MjStyle(HeadComponent):
@classmethod
def default_attrs(cls):
return {
'inline' : '',
}
def handler(self):
add = self.context['add']
inline_attr = 'inlineStyle' if (self.get_attr('inl... | 2.421875 | 2 |
model_zoo/official/nlp/bert/src/sample_process.py | i4oolish/mindspore | 2 | 10413 | <filename>model_zoo/official/nlp/bert/src/sample_process.py
# Copyright 2020 Huawei Technologies Co., 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://www.apache.org/licenses/LI... | 2.59375 | 3 |
lang_model/data_loader.py | alex44jzy/FancyALMLDLNLP | 0 | 10414 | <gh_stars>0
import torch
from torch.nn import functional as F
from torch.utils.data import Dataset
from gensim.corpora.dictionary import Dictionary
class LangDataset(Dataset):
def __init__(self, src_sents, trg_sents, max_len=-1):
self.src_sents = src_sents
self.trg_sents = trg_sents
# Cre... | 2.625 | 3 |
models_nonconvex_simple2/ndcc13persp.py | grossmann-group/pyomo-MINLP-benchmarking | 0 | 10415 | <reponame>grossmann-group/pyomo-MINLP-benchmarking
# MINLP written by GAMS Convert at 08/20/20 01:30:45
#
# Equation counts
# Total E G L N X C B
# 297 170 42 85 0 0 0 0
#
# Variable counts
# ... | 1.8125 | 2 |
tests/pytests/scenarios/multimaster/conftest.py | lllamnyp/salt | 0 | 10416 | <gh_stars>0
import logging
import os
import shutil
import subprocess
import pytest
import salt.utils.platform
log = logging.getLogger(__name__)
@pytest.fixture(scope="package", autouse=True)
def skip_on_tcp_transport(request):
if request.config.getoption("--transport") == "tcp":
pytest.skip("Multimaster... | 1.742188 | 2 |
supermario/supermario 1117/start_state.py | Kimmiryeong/2DGP_GameProject | 0 | 10417 | import game_framework
from pico2d import *
import title_state
name = "StartState"
image = None
logo_time = 0.0
def enter():
global image
image = load_image('kpu_credit.png')
def exit():
global image
del(image)
def update():
global logo_time
if (logo_time > 1.0):
logo_time = 0.8
... | 2.859375 | 3 |
egs/librispeech/ASR/transducer/test_rnn.py | rosrad/icefall | 0 | 10418 | <reponame>rosrad/icefall<gh_stars>0
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corp. (authors: <NAME>)
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lic... | 1.984375 | 2 |
settings.py | SalinderSidhu/CHIP8 | 4 | 10419 | <filename>settings.py
import configparser
class Settings:
'''The Settings class is a wrapper for configparser and it's functions.
This class simplifies the tasks of loading, storing and manipulating
settings data.'''
def __init__(self, filename):
'''Create a new Settings object with a specifi... | 3.78125 | 4 |
demisto_sdk/commands/common/hook_validations/release_notes.py | yalonso7/demisto-sdk | 0 | 10420 | <filename>demisto_sdk/commands/common/hook_validations/release_notes.py
from __future__ import print_function
import itertools
from demisto_sdk.commands.common.constants import VALIDATED_PACK_ITEM_TYPES
from demisto_sdk.commands.common.errors import Errors
from demisto_sdk.commands.common.hook_validations.base_valida... | 2.078125 | 2 |
PyOpenGL/PyGame/ex06/src/mathematics.py | hoppfull/Legacy-Python | 0 | 10421 | import numpy as np
class ProjectionMatrix():
"""This matrix provides projection distortion.
Projection distortion is when things that are far away
appear smaller and things that are close appear bigger.
This works flawlessly so far. Takes in screen-size and
provides near- and far clipping. fov is f... | 3.40625 | 3 |
test_utils/mocks.py | radomd92/botjagwar | 7 | 10422 | from xml.dom import minidom
import pywikibot
from api.decorator import time_this
SiteMock = pywikibot.Site
class PageMock(pywikibot.Page):
def __init__(self, *args, **kwargs):
super(PageMock, self).__init__(*args, **kwargs)
self.filename = "test_data/test_pages_%s.xml" % self.site.lang
... | 2.484375 | 2 |
dl_tensorflow/deepdream.py | jarvisqi/deep_learning | 32 | 10423 | import os
from functools import partial
from io import BytesIO
import numpy as np
import PIL.Image
import scipy.misc
import tensorflow as tf
graph = tf.Graph()
sess = tf.InteractiveSession(graph=graph)
model_fn = "./models/tensorflow_inception_graph.pb"
with tf.gfile.FastGFile(model_fn, 'rb') as f:
graph_def = tf... | 2.46875 | 2 |
admin.py | BlueBlock/usage-reporter | 4 | 10424 | import calendar
import datetime
import logging
import os
import webapp2
import dbmodel
TESTING = os.environ.get('SERVER_SOFTWARE', '').startswith('Development')
class ResetHandler(webapp2.RequestHandler):
def get(self):
timestamp = calendar.timegm(datetime.datetime.utcnow().timetuple())
self.re... | 2.53125 | 3 |
napari/utils/colormaps/categorical_colormap_utils.py | Zac-HD/napari | 1 | 10425 | from dataclasses import dataclass
from itertools import cycle
from typing import Dict, Union
import numpy as np
from ...layers.utils.color_transformations import (
transform_color,
transform_color_cycle,
)
@dataclass(eq=False)
class ColorCycle:
"""A dataclass to hold a color cycle for the fallback_color... | 2.828125 | 3 |
src/ipywidgets_toggle_buttons/abc_toggle_buttons_with_hide.py | stas-prokopiev/ipywidgets_toggle_buttons | 0 | 10426 | """Abstract class for all toggle buttons"""
# Standard library imports
import logging
from collections import OrderedDict
# Third party imports
import ipywidgets
# Local imports
from .abc_toggle_buttons import BaseToggleButtons
from .layouts import DICT_LAYOUT_HBOX_ANY
LOGGER = logging.getLogger(__name__)
class Ba... | 2.609375 | 3 |
Players/DWPMPlayer.py | jokvedaras/game-framework | 0 | 10427 | __author__ = '<NAME> and <NAME>'
import Player
import Message
# input
#0 for rock
#1 for paper
#2 for scissors
# past move is array of numbers
# our move followed by their move
#Our strategy is to look at all past moves
#In a large number of games, you would expect
# each move to be seen an even amount of times
#So... | 3.578125 | 4 |
example/example.py | mowshon/age-and-gender | 81 | 10428 | <filename>example/example.py
from age_and_gender import *
from PIL import Image, ImageDraw, ImageFont
data = AgeAndGender()
data.load_shape_predictor('models/shape_predictor_5_face_landmarks.dat')
data.load_dnn_gender_classifier('models/dnn_gender_classifier_v1.dat')
data.load_dnn_age_predictor('models/dnn_age_predict... | 3 | 3 |
code/generate_games.py | jppg/pygame-tictactoe | 0 | 10429 | from tictactoe import TicTacToe
import random
import csv
import os
gameNr = 1
gameLimit = 10000
lst_moves_1 = []
lst_moves_2 = []
while gameNr <= gameLimit:
print("+++++++++++")
print("Game#", gameNr)
game = TicTacToe()
tmp_moves_1 = []
tmp_moves_2 = []
while game.get_winner() == 0 and game.... | 3.40625 | 3 |
applications/CoSimulationApplication/custom_data_structure/pyKratos/IntervalUtility.py | lcirrott/Kratos | 2 | 10430 | from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7
# TODO this should be implemented, see "kratos/utilities/interval_utility.h"
class IntervalUtility(object):
def __init__(self, settings):
pass
def IsInInterval(self, curr... | 2.078125 | 2 |
stixcore/tmtc/tests/test_packets.py | nicHoch/STIXCore | 1 | 10431 |
import bitstring
import pytest
from stixcore.data.test import test_data
from stixcore.idb.manager import IDBManager
from stixcore.tmtc.packets import (
SOURCE_PACKET_HEADER_STRUCTURE,
TC_DATA_HEADER_STRUCTURE,
TM_DATA_HEADER_STRUCTURE,
SourcePacketHeader,
TCPacket,
TMDataHeader,
TMPacket,
... | 2.109375 | 2 |
python/thunder/rdds/fileio/seriesloader.py | broxtronix/thunder | 0 | 10432 | <reponame>broxtronix/thunder<gh_stars>0
"""Provides SeriesLoader object and helpers, used to read Series data from disk or other filesystems.
"""
from collections import namedtuple
import json
from numpy import array, arange, frombuffer, load, ndarray, unravel_index, vstack
from numpy import dtype as dtypeFunc
from sci... | 2.265625 | 2 |
mxnet/local_forward.py | rai-project/onnx_examples | 0 | 10433 | # run local models given a path, default to './mxnet_models/'
import os
import argparse
import time
import mxnet as mx
import numpy as np
file_path = os.path.realpath(__file__)
dir_name = os.path.dirname(file_path)
os.environ["MXNET_CUDNN_AUTOTUNE_DEFAULT"] = "0"
class cuda_profiler_start():
import numba.cuda ... | 2.28125 | 2 |
tests/test_get_angles.py | Mopolino8/lammps-data-file | 13 | 10434 | <reponame>Mopolino8/lammps-data-file<gh_stars>10-100
from lammps_data.angles import get_angles
def test_separate_diatomic_molecules_should_have_no_angles():
bonds = [(0, 1), (2, 3)]
assert get_angles(bonds) == []
def test_molecule_with_two_bonds_should_have_one_angle():
bonds = [(0, 1), (1, 2)]
asse... | 2.296875 | 2 |
api/scheduler/migrations/0001_initial.py | jfaach/stock-app | 0 | 10435 | # Generated by Django 3.1.1 on 2020-12-16 03:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Scheduler',
fields=[
('id', models.AutoFiel... | 1.734375 | 2 |
9-Wine-Scaling.py | Pawel762/Class-7_homework | 0 | 10436 | from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
wine = load_wine()
columns_names = wine.feature_names
y = wine.target
X = wine.data
print('Pre scaling X')
print(X)
scaler = StandardScaler()
scaler.fit(X)
scaled_features = sc... | 2.953125 | 3 |
tests/conftest.py | szkkteam/flask-starter | 0 | 10437 | <reponame>szkkteam/flask-starter<filename>tests/conftest.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Common Python library imports
import os
import pytest
# Pip package imports
from collections import namedtuple
from flask import template_rendered
from flask_security.signals import (
reset_password_instruc... | 2.015625 | 2 |
setup.py | YiuRULE/nats.py | 0 | 10438 | <gh_stars>0
from setuptools import setup
from nats.aio.client import __version__
EXTRAS = {
'nkeys': ['nkeys'],
}
setup(
name='nats-py',
version=__version__,
description='NATS client for Python',
long_description='Python client for NATS, a lightweight, high-performance cloud native messaging syst... | 1.15625 | 1 |
example_python_files/MagicDAQ,MABoard,FullDemo.py | MagicDAQ/magicdaq_docs | 1 | 10439 | ##############################################################
#*** MagicDAQ USB DAQ and M&A Board General Demo Script ***
##############################################################
#*** Websites ***
# MagicDAQ Website:
# https://www.magicdaq.com/
# API Docs Website:
# https://magicdaq.github.io/magicdaq_docs/
#*... | 2.34375 | 2 |
src/onenutil/schemas/__init__.py | LemurPwned/onenote-utils | 0 | 10440 | from .results import (ArticleSearchResult, EmbeddingsResult, SearchResult,
TagResult, ZoteroExtractionResult)
__all__ = [
"TagResult", "EmbeddingsResult", "ZoteroExtractionResult", "SearchResult",
"ArticleSearchResult"
]
| 1.117188 | 1 |
src/account/api/serializers.py | amirpsd/drf_blog_api | 33 | 10441 | <filename>src/account/api/serializers.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
class UsersListSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = [
"id", "phone",
"first_name", "last_name",
... | 2.34375 | 2 |
generate_figure9.py | IBM/Simultaneous-diagonalization | 0 | 10442 | # Copyright 2022 IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
# 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 ... | 2.046875 | 2 |
undeployed/legacy/Landsat/L7GapFiller_ArcInterface.py | NASA-DEVELOP/dnppy | 65 | 10443 | <filename>undeployed/legacy/Landsat/L7GapFiller_ArcInterface.py
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: qgeddes
#
# Created: 25/04/2013
# Copyright: (c) qgeddes 2013
# Licence: <your licence>
#-------------------------... | 1.601563 | 2 |
tests/sentry/api/serializers/test_saved_search.py | practo/sentry | 4 | 10444 | <filename>tests/sentry/api/serializers/test_saved_search.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import six
from sentry.api.serializers import serialize
from sentry.models import SavedSearch
from sentry.models.savedsearch import DEFAULT_SAVED_SEARCHES
from sentry.testutils import TestCase
... | 2.28125 | 2 |
xastropy/files/general.py | bpholden/xastropy | 3 | 10445 | """
#;+
#; NAME:
#; general
#; Version 1.0
#;
#; PURPOSE:
#; Module for monkeying with files and filenames
#; 172Sep-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
# Import libraries
import numpy as np
from astropy.io import fits
from astropy.io import as... | 2.578125 | 3 |
setup.py | muatik/genderizer | 54 | 10446 | #!/usr/bin/env python
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
setup(name='genderizer',
version='0.1.2.3',
license='MIT',
description='Genderizer tries to infer gender information looking at first name and/or making text analysis',
lo... | 1.398438 | 1 |
ingestion/tests/unit/great_expectations/test_ometa_validation_action.py | ulixius9/OpenMetadata | 0 | 10447 | # Copyright 2022 Collate
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software... | 1.953125 | 2 |
tests/integration/Containers.py | adnrs96/runtime | 0 | 10448 | # -*- coding: utf-8 -*-
from storyruntime.Containers import Containers
from storyruntime.constants.ServiceConstants import ServiceConstants
import storyscript
def test_containers_format_command(story):
"""
Ensures a simple resolve can be performed
"""
story_text = 'alpine echo msg:"foo"\n'
story.... | 2.59375 | 3 |
project_name/core/admin.py | cosmunsoftwares/django-boilerplate | 3 | 10449 | from django.contrib import admin
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets import AdminFileWidget
class AdminImageWidget(AdminFileWidget):
def render(self, name, value, attrs=None, renderer=None):
output = []
if value and ... | 2.03125 | 2 |
src/5vents.py | subhash686/aoc-2021 | 0 | 10450 | <reponame>subhash686/aoc-2021
import os
plane = [[0 for i in range(1000)] for j in range(1000)]
count = [0]
def overlapping_vents():
path = os.getcwd()
file_path = os.path.join(path, 'vents.txt')
file1 = open(file_path, 'r')
Lines = file1.readlines()
for line in Lines:
input = line.strip... | 2.953125 | 3 |
problems/test_0073_m_plus_n_space.py | chrisxue815/leetcode_python | 1 | 10451 | import unittest
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
rows = [0] * len(matrix)
cols = [0] * len(matrix[0])
for i, row in enumerate(matrix):
... | 3.484375 | 3 |
xlsxwriter/test/worksheet/test_write_print_options.py | Aeon1/XlsxWriter | 2 | 10452 | <reponame>Aeon1/XlsxWriter<filename>xlsxwriter/test/worksheet/test_write_print_options.py
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2019, <NAME>, <EMAIL>
#
import unittest
from ...compatibility import StringIO
from ...worksheet imp... | 2.640625 | 3 |
neo4j_helper.py | smartaec/OpenBridgeGraph | 0 | 10453 | <reponame>smartaec/OpenBridgeGraph<filename>neo4j_helper.py
from neo4j.v1 import GraphDatabase #neo4j==1.7.0
uri="bolt://localhost:7687"
driver=GraphDatabase.driver(uri, auth=("neo4j", "testneo4j"))
def execute_queries(scripts,message=None):
with driver.session() as session:
tx=session.begin_transaction()... | 2.390625 | 2 |
tests/unit/test_juju.py | KellenRenshaw/hotsos | 0 | 10454 | <filename>tests/unit/test_juju.py
import os
import tempfile
import mock
from . import utils
from hotsos.core.config import setup_config
from hotsos.core.ycheck.scenarios import YScenarioChecker
from hotsos.core.issues.utils import KnownBugsStore, IssuesStore
from hotsos.plugin_extensions.juju import summary
JOURNAL... | 1.664063 | 2 |
tools/SPGAN/main.py | by-liu/OpenUnReID | 0 | 10455 | import argparse
import collections
import shutil
import sys
import time
from datetime import timedelta
from pathlib import Path
import torch
from torch.nn.parallel import DataParallel, DistributedDataParallel
try:
# PyTorch >= 1.6 supports mixed precision training
from torch.cuda.amp import autocast
amp_su... | 1.96875 | 2 |
utility/data_download.py | LatvianPython/wind-experience | 2 | 10456 | import logging
import requests
import multiprocessing
import pathlib
from typing import List
from typing import Optional
from typing import Tuple
from typing import Dict
from joblib import delayed
from joblib import Parallel
from datetime import date
from datetime import timedelta
logger = logging.getLogger(__name__)
... | 2.515625 | 3 |
model/net_qspline_A.py | jercoco/QSQF | 0 | 10457 | <filename>model/net_qspline_A.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 19:52:22 2020
#Plan A
@author: 18096
"""
'''Defines the neural network, loss function and metrics'''
#from functools import reduce
import torch
import torch.nn as nn
from torch.nn.functional import pad
from torc... | 2.390625 | 2 |
tests/repositories/helpers/methods/test_reinstall_if_needed.py | traibnn/integration | 1 | 10458 | <filename>tests/repositories/helpers/methods/test_reinstall_if_needed.py
import pytest
@pytest.mark.asyncio
async def test_reinstall_if_needed(repository):
repository.content.path.local = "/non/existing/dir"
repository.data.installed = True
await repository.async_reinstall_if_needed()
| 1.820313 | 2 |
workflow_parser/datasource/log_engine.py | cyx1231st/workflow_parser | 0 | 10459 | <filename>workflow_parser/datasource/log_engine.py<gh_stars>0
# Copyright (c) 2017 <NAME>
#
# 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
#... | 1.960938 | 2 |
IPython/lib/tests/test_irunner_pylab_magic.py | dchichkov/ipython | 0 | 10460 | """Test suite for pylab_import_all magic
Modified from the irunner module but using regex.
"""
# Global to make tests extra verbose and help debugging
VERBOSE = True
# stdlib imports
import StringIO
import sys
import unittest
import re
# IPython imports
from IPython.lib import irunner
from IPython.testing import dec... | 2.5625 | 3 |
checkpoint.py | GooLee0123/MBRNN | 1 | 10461 | import logging
import os
import shutil
import time
import torch
model_state = 'model_state.pt'
trainer_state = 'trainer_state.pt'
class Checkpoint():
def __init__(self, step, epoch, model, optim, path=None, opt=None):
self.step = step
self.epoch = epoch
self.model = model
self.o... | 2.375 | 2 |
test/eval_mines_color.py | alalagong/LEDNet | 3 | 10462 | import numpy as np
import torch
import os
import cv2
import importlib
from dataset import *
from PIL import Image
from argparse import ArgumentParser
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, CenterCrop, Normalize, Resize
from torchvision.tr... | 2.359375 | 2 |
tests/test_resource_linkage.py | firesock/pydantic-jsonapi | 0 | 10463 | import pytest
from pytest import raises
from pydantic_jsonapi.resource_linkage import ResourceLinkage
from pydantic import BaseModel, ValidationError
class ThingWithLinkageData(BaseModel):
data: ResourceLinkage
class TestResourceLinks:
@pytest.mark.parametrize(
'linkage, message',
[
... | 2.515625 | 3 |
src/tensorflow/keras_cnn.py | del680202/MachineLearning-memo | 4 | 10464 | import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.utils import np_utils
import keras.callbacks
import keras.backend.tensorflow_backend as KTF
import tensorflow as tf
batch_size = 1... | 2.828125 | 3 |
tests/blas/nodes/ger_test.py | xiacijie/dace | 1 | 10465 | <reponame>xiacijie/dace
#!/usr/bin/env python3
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
from dace.transformation.dataflow.streaming_memory import StreamingMemory
from dace.transformation.interstate.sdfg_nesting import InlineSDFG
from dace.transformation.interstate.fpga_transform_sdfg... | 1.984375 | 2 |
spp.py | ninfueng/torch-cifar | 0 | 10466 | <reponame>ninfueng/torch-cifar
import math
from typing import List, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
@torch.jit.script
def spatial_pyramid_pool(
input: Tensor, bins: Union[int, List[int]], mode: str = "max"
) -> Tensor:
"""Spatial Pyramid Pooli... | 2.921875 | 3 |
src/SparseSC/utils/AzureBatch/azure_batch_client.py | wofein/SparseSC | 0 | 10467 | """
usage requires these additional modules
pip install azure-batch azure-storage-blob jsonschema pyyaml && pip install git+https://github.com/microsoft/SparseSC.git@ad4bf27edb28f517508f6934f21eb65d17fb6543 && scgrad start
usage:
from SparseSC import fit, aggregate_batch_results
from SparseSC.utils.azure_batch_clie... | 2.171875 | 2 |
src/vilbert/datasets/__init__.py | NoOneUST/COMP5212 | 3 | 10468 | <reponame>NoOneUST/COMP5212
from .visual_entailment_dataset import VisualEntailmentDataset
| 0.859375 | 1 |
Dungeoneer/Treasure.py | jameslemon81/Dungeoneer | 12 | 10469 | <filename>Dungeoneer/Treasure.py
# Basic Fantasy RPG Dungeoneer Suite
# Copyright 2007-2012 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain ... | 1.554688 | 2 |
covid19/COVID19/code/controller/main.py | zhanqingheng/COVID-19 | 16 | 10470 | from flask import Flask, current_app
from flask import render_template
from flask import jsonify
from jieba.analyse import extract_tags
import string
from DB import chinaSQL
from DB import worldSQL
app = Flask(__name__, template_folder='../../web', static_folder='../../static')
@app.route('/', methods=["get", "post"... | 2.453125 | 2 |
T2API/migrations/0008_product_weight.py | hackhb18-T2/api | 0 | 10471 | # Generated by Django 2.0.2 on 2018-02-17 10:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('T2API', '0007_apiuser_deviceuser'),
]
operations = [
migrations.AddField(
model_name='product',
name='weight',
... | 1.640625 | 2 |
contrib/cirrus/podbot.py | juhp/libpod | 2 | 10472 | #!/usr/bin/env python3
# Simple and dumb script to send a message to the #podman IRC channel on frenode
# Based on example from: https://pythonspot.com/building-an-irc-bot/
import os
import time
import random
import errno
import socket
import sys
class IRC:
response_timeout = 10 # seconds
irc = socket.sock... | 2.578125 | 3 |
changes/api/build_coverage.py | vault-the/changes | 443 | 10473 | <reponame>vault-the/changes
from changes.api.base import APIView
from changes.lib.coverage import get_coverage_by_build_id, merged_coverage_data
from changes.models.build import Build
class BuildTestCoverageAPIView(APIView):
def get(self, build_id):
build = Build.query.get(build_id)
if build is ... | 2.0625 | 2 |
topopt/mechanisms/problems.py | arnavbansal2764/topopt | 53 | 10474 | <reponame>arnavbansal2764/topopt<gh_stars>10-100
"""Compliant mechanism synthesis problems using topology optimization."""
import numpy
import scipy.sparse
from ..problems import ElasticityProblem
from .boundary_conditions import MechanismSynthesisBoundaryConditions
from ..utils import deleterowcol
class MechanismS... | 2.203125 | 2 |
tests/test_parse_icao24bit.py | Collen-Roller/arp | 2 | 10475 | import unittest
from flydenity import Parser
class TestParseIcao24Bit(unittest.TestCase):
def setUp(self):
self.parser = Parser()
def test_parse_simple(self):
match = self.parser.parse("3D2591", icao24bit=True)
self.assertEqual(match, {"nation": "Germany", "description": "general", ... | 3.125 | 3 |
ever/util/_main.py | Bobholamovic/ever | 22 | 10476 | import os
def create_project(path):
dirs = ['configs', 'module', 'data']
dirs = [os.path.join(path, d) for d in dirs]
for d in dirs:
os.makedirs(d)
train_script = r"""
import ever as er
def train(trainer_name):
trainer = er.trainer.get_trainer(trainer_name)()
trainer.run()
... | 2.609375 | 3 |
src/app/services/metrics_service.py | chrisbpoint/the-app | 0 | 10477 | class MetricsService:
def __init__(self, adc_data, metrics_data):
self._adc_data = adc_data
self._metrics_data = metrics_data
@property
def metrics_data(self):
return self._metrics_data
def update(self):
self._metrics_data.is_new_data_available = False
if self.... | 2.65625 | 3 |
resthelper/tests/test_build_url.py | rklonner/resthelper | 0 | 10478 | import unittest
from resthelper.utils import build_restful_url
class TestBuildUrl(unittest.TestCase):
def test_is_restful_https_url(self):
url = build_restful_url('https://jenkins1.tttech.com',
'testuser', '/rest/1.0/request')
self.assertEqual(url,
'htt... | 3.046875 | 3 |
sendsms/backends/rq.py | this-is-the-bard/django-sendsms | 0 | 10479 | """ python-rq based backend
This backend will send your messages asynchronously with python-rq.
Before using this backend, make sure that django-rq is installed and
configured.
Usage
-----
In settings.py
SENDSMS_BACKEND = 'sendsms.backends.rq.SmsBackend'
RQ_SENDSMS_BACKEND = 'actual.backend.to.use.SmsBack... | 2.40625 | 2 |
venv/Lib/site-packages/openpyxl/worksheet/errors.py | ajayiagbebaku/NFL-Model | 5,079 | 10480 | <gh_stars>1000+
#Autogenerated schema
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Typed,
String,
Bool,
Sequence,
)
from openpyxl.descriptors.excel import CellRange
class Extension(Serialisable):
tagname = "extension"
uri = String(allow_none=T... | 2.34375 | 2 |
cwbot/kolextra/request/ItemDescriptionRequest.py | zeryl/RUcwbot | 0 | 10481 | <gh_stars>0
from kol.request.GenericRequest import GenericRequest
from kol.manager import PatternManager
import re
class ItemDescriptionRequest(GenericRequest):
"Gets the description of an item and then parses various information from the response."
_itemIdPattern = re.compile(r'(?i)<!--\s*itemid:\s*(\d+)\s*--... | 2.53125 | 3 |
SmartMove/SmartConnector/cpapi/utils.py | themichaelasher/SmartMove | 24 | 10482 | import json
import sys
def compatible_loads(json_data):
"""
Function json.loads in python 3.0 - 3.5 can't handle bytes, so this function handle it.
:param json_data:
:return: unicode (str if it's python 3)
"""
if isinstance(json_data, bytes) and (3, 0) <= sys.version_info < (3, 6):
... | 3.0625 | 3 |
VokeScan.py | DaduVoke/VokeScan | 2 | 10483 | import sys,time
def sprint(str):
for c in str + '\n':
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(3./90)
from colorama import Fore, Back, Style
sprint (Fore.RED + "გამარჯობა. tool-ი შექმინლია ლევან ყიფიანი-DaduVoke-ის მიერ @2021")
import socket
import _thread
im... | 2.78125 | 3 |
agent/src/clacks/agent/objects/object.py | gonicus/clacks | 2 | 10484 | <filename>agent/src/clacks/agent/objects/object.py
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level ... | 1.867188 | 2 |
tests/test_benchmark.py | fossabot/BIRL | 0 | 10485 | <gh_stars>0
"""
Testing default benchmarks in single thred and parallel configuration
Check whether it generates correct outputs and resulting values
Copyright (C) 2017-2019 <NAME> <<EMAIL>>
"""
import argparse
import logging
import os
import shutil
import sys
import unittest
try: # python 3
from unittest.mock ... | 2.0625 | 2 |
python/UdemyCourse/2022_Python_Bootcamp/basics/errors_exception_handling/__init__.py | pradyotprksh/development_learning | 9 | 10486 | from .errors_exception_handling import errors_exception_handling
| 1.09375 | 1 |
mtstub.py | shimniok/rockblock | 1 | 10487 | <reponame>shimniok/rockblock<gh_stars>1-10
#!/usr/bin/env python
##################################################################################################
## mtstub.py
##
## emulates rockblock api so I don't have to burn credits testing...
######################################################################... | 1.828125 | 2 |
sum.py | PraghadeshManivannan/Built-in-Functions-Python | 0 | 10488 | <filename>sum.py
#sum(iterable, start=0, /)
#Return the sum of a 'start' value (default: 0) plus an iterable of numbers
#When the iterable is empty, return the start value.
'''This function is intended specifically for use with numeric values and may
reject non-numeric types.'''
a = [1,3,5,7,9,4,6,2,8]
... | 4 | 4 |
idaes/apps/matopt/materials/lattices/diamond_lattice.py | carldlaird/idaes-pse | 112 | 10489 | #################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... | 2.03125 | 2 |
elateridae_baits.py | AAFC-BICoE/elateridae-ortholog-baitset | 0 | 10490 | <filename>elateridae_baits.py
# coding: utf8
"""
Ortholog Based Bait Design Script for creating Elateridae ortholog based baits suitable submission to myBaits
Compares t_coffee AA alignment scores with nucleotide tranalignments to find conserved blocks
Author <NAME> <EMAIL>
License: MIT
Copywright: Government of Canada... | 2.796875 | 3 |
poilab.py | octeufer/Annotate_Optimize | 0 | 10491 | <filename>poilab.py
import sys
import numpy as np
sys.path.append("d:/data/annooptimize")
import triangle
import time
tinternal = list()
def labstart():
points,tri = triangle.gentri("d:/data/annooptimize/Annodata/200600/poise.shp")
plabels = triangle.dynamicSize(points)
conflictg = triangle.con... | 2.5 | 2 |
t_core/tc_python/xrule.py | levilucio/SyVOLT | 3 | 10492 |
from util.infinity import INFINITY
from tc_python.arule import ARule
from t_core.rollbacker import Rollbacker
from t_core.resolver import Resolver
class XRule(ARule):
'''
Applies the transformation on one match with roll-back capability.
'''
def __init__(self, LHS, RHS, max_iterations=... | 2.296875 | 2 |
tests/commonsense/semantic_lexicon_knowledge/ai2_lexicon_test.py | keisks/propara | 84 | 10493 | <reponame>keisks/propara<gh_stars>10-100
from unittest import TestCase
from propara.commonsense.semantic_lexicon_knowledge.ai2_lexicon import AI2Lexicon, AI2LexiconPredicate, AI2LexiconArg, AI2LexiconIndications, \
AI2LexiconPattern
class TestAI2Lexicon(TestCase):
def setUp(self):
self.lexicon_fp = "... | 2.546875 | 3 |
fitbit/__init__.py | erichilarysmithsr/python-fitbit | 0 | 10494 | # -*- coding: utf-8 -*-
"""
Fitbit API Library
------------------
:copyright: 2012-2015 ORCAS.
:license: BSD, see LICENSE for more details.
"""
from .api import Fitbit, FitbitOauthClient, FitbitOauth2Client
# Meta.
__title__ = 'fitbit'
__author__ = '<NAME> and ORCAS'
__author_email__ = '<EMAIL>'
__copyright__ = 'Co... | 1.101563 | 1 |
bitcoinExchange/exchange/api/urls.py | pogginicolo98/start2impact_exchange | 1 | 10495 | <reponame>pogginicolo98/start2impact_exchange
from django.urls import include, path
from exchange.api.views import LatestOrdersListAPIView, OrderViewSet, ProfileAPIView
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'orders', OrderViewSet, basename='orders')
urlpatterns = [... | 1.929688 | 2 |
python/testData/formatter/indentInGenerator_after.py | jnthn/intellij-community | 2 | 10496 | def dbl():
return (
(a, a) for a in [])
| 1.65625 | 2 |
kevin/aggregate/process_html.py | toddoh/thisisallabout_backend | 0 | 10497 | from bs4 import BeautifulSoup
import requests
import re
def retrieveText():
print("Parsing text from online target")
url = "https://www.whitehouse.gov/the-press-office/2017/10/16/remarks-president-trump-and-senate-majority-leader-mitch-mcconnell-joint"
response = requests.get(url)
soup = BeautifulSoup(... | 3.484375 | 3 |
cfmacro/_resources/examples/lambda.py | gchiesa/cfmacro | 0 | 10498 | <reponame>gchiesa/cfmacro<filename>cfmacro/_resources/examples/lambda.py
# -*- coding: utf-8 -*-
from cfmacro.processors import SgProcessor
from cfmacro.core.engine import ProcessorEngine
from cfmacro.core.template import TemplateProcessor
def lambda_handler(event, context):
"""
Implement a core handler for ... | 1.898438 | 2 |
tf2qa/predict_long.py | mikelkl/TF2-QA | 17 | 10499 | <reponame>mikelkl/TF2-QA<gh_stars>10-100
import torch
import argparse
from roberta_modeling import RobertaJointForLong
from transformers.modeling_roberta import RobertaConfig, RobertaModel
from torch.utils.data import TensorDataset, SequentialSampler, DataLoader
import utils
from tqdm import tqdm
import os
import json
... | 2.140625 | 2 |