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 |
|---|---|---|---|---|---|---|
accalib/utils.py | pj0620/acca-video-series | 0 | 5900 | from manimlib.imports import *
from manimlib.utils import bezier
import numpy as np
class VectorInterpolator:
def __init__(self,points):
self.points = points
self.n = len(self.points)
self.dists = [0]
for i in range(len(self.points)):
self.dists += [np.linalg.norm(
... | 2.84375 | 3 |
setup.py | def-mycroft/rapid-plotly | 1 | 5901 | from setuptools import setup
setup(name='rapid_plotly',
version='0.1',
description='Convenience functions to rapidly create beautiful Plotly graphs',
author='<NAME>',
author_email='<EMAIL>',
packages=['rapid_plotly'],
zip_safe=False)
| 1.203125 | 1 |
dodo.py | enerqi/bridge-bidding-systems | 2 | 5902 | <filename>dodo.py
#! /usr/bin/doit -f
# https://pydoit.org
# `pip install [--user] doit` adds `doit.exe` to the PATH
# - Note `doit auto`, the file watcher only works on Linux/Mac
# - All commands are relative to dodo.py (doit runs in the working dir of dodo.py
# even if ran from a different directory `doit -f path/t... | 2.265625 | 2 |
learn/hard-way/EmptyFileError.py | hustbill/Python-auto | 0 | 5903 | class EmptyFileError(Exception):
pass
filenames = ["myfile1", "nonExistent", "emptyFile", "myfile2"]
for file in filenames:
try:
f = open(file, 'r')
line = f.readline()
if line == "":
f.close()
raise EmptyFileError("%s: is empty" % file)
# except IO... | 3.6875 | 4 |
plugins/crumbling_in.py | jimconner/digital_sky | 2 | 5904 | <reponame>jimconner/digital_sky<filename>plugins/crumbling_in.py
# Crumbling In
# Like randomised coloured dots and then they
# increase on both sides getting closer and closer into the middle.
import sys, traceback, random
from numpy import array,full
class animation():
def __init__(self,datastore):
self... | 2.78125 | 3 |
pybleau/app/plotting/tests/test_plot_config.py | KBIbiopharma/pybleau | 4 | 5905 | from __future__ import division
from unittest import skipIf, TestCase
import os
from pandas import DataFrame
import numpy as np
from numpy.testing import assert_array_equal
BACKEND_AVAILABLE = os.environ.get("ETS_TOOLKIT", "qt4") != "null"
if BACKEND_AVAILABLE:
from app_common.apptools.testing_utils import asser... | 2.390625 | 2 |
test/integration/languages/test_mixed.py | thomasrockhu/bfg9000 | 72 | 5906 | import os.path
from .. import *
class TestMixed(IntegrationTest):
def __init__(self, *args, **kwargs):
super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs)
def test_build(self):
self.build(executable('program'))
self.assertOutput([executable('program')], 'hello from ... | 2.0625 | 2 |
code/7/collections/namedtupe_example.py | TeamLab/introduction_to_pythoy_TEAMLAB_MOOC | 65 | 5907 | from collections import namedtuple
# Basic example
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p[0] + p[1])
x, y = p
print(x, y)
print(p.x + p.y)
print(Point(x=11, y=22))
from collections import namedtuple
import csv
f = open("users.csv", "r")
next(f)
reader = csv.reader(f)
student_list = []
fo... | 4 | 4 |
test/helper_tools/benchtool.py | dotnes/mitmproxy | 4 | 5908 | <reponame>dotnes/mitmproxy
# Profile mitmdump with apachebench and
# yappi (https://code.google.com/p/yappi/)
#
# Requirements:
# - Apache Bench "ab" binary
# - pip install click yappi
from mitmproxy.main import mitmdump
from os import system
from threading import Thread
import time
import yappi
import click
class ... | 2.140625 | 2 |
pivpy/graphics.py | alexliberzonlab/pivpy | 1 | 5909 | <filename>pivpy/graphics.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Various plots
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
import xarray as xr
import os
def quiver(data, arrScale = 25.0, threshold = None, nthArr = 1,
contourL... | 2.765625 | 3 |
configs/my_config/vit_base_aspp.py | BostonCrayfish/mmsegmentation | 0 | 5910 | # model settings
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='pretrain/vit_base_patch16_224.pth',
backbone=dict(
type='VisionTransformer',
img_size=(224, 224),
patch_size=16,
in_channels=3,
embed_dim=768,
dept... | 1.507813 | 2 |
tripleo_ansible/ansible_plugins/modules/podman_container.py | smolar/tripleo-ansible | 0 | 5911 | <filename>tripleo_ansible/ansible_plugins/modules/podman_container.py
#!/usr/bin/python
# Copyright (c) 2019 OpenStack Foundation
# 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... | 1.5625 | 2 |
setup.py | UdoGi/dark-matter | 0 | 5912 | #!/usr/bin/env python
from setuptools import setup
# Modified from http://stackoverflow.com/questions/2058802/
# how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package
def version():
import os
import re
init = os.path.join('dark', '__init__.py')
with open(init) as fp:
initDat... | 2.09375 | 2 |
authenticationApp/templatetags/timetags.py | FilipBali/VirtualPortfolio-WebApplication | 0 | 5913 | <reponame>FilipBali/VirtualPortfolio-WebApplication<gh_stars>0
# ======================================================================================================================
# Fakulta informacnich technologii VUT v Brne
# Bachelor thesis
# Author: <NAME> (xbalif00)
# License: MIT
# ===========================... | 2.25 | 2 |
pycfmodel/model/resources/properties/policy.py | donatoaz/pycfmodel | 23 | 5914 | <reponame>donatoaz/pycfmodel
from pycfmodel.model.resources.properties.policy_document import PolicyDocument
from pycfmodel.model.resources.properties.property import Property
from pycfmodel.model.types import Resolvable, ResolvableStr
class Policy(Property):
"""
Contains information about an attached policy.... | 2.015625 | 2 |
stlearn/__init__.py | mrahim/stacked-learn | 2 | 5915 | from .stacking import StackingClassifier, stack_features
from .multitask import MultiTaskEstimator
| 1.054688 | 1 |
samples/workload/XNNPACK/toolchain/emscripten_toolchain_config.bzl | utsavm9/wasm-micro-runtime | 2 | 5916 | # Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"tool_p... | 1.351563 | 1 |
cloud_storages/gdrive/gdrive.py | toplenboren/safezone | 0 | 5917 | <gh_stars>0
from __future__ import print_function
import json
from typing import List
from functools import lru_cache
from cloud_storages.http_shortcuts import *
from database.database import Database
from models.models import StorageMetaInfo, Resource, Size
from cloud_storages.storage import Storage
from cloud_stora... | 2.8125 | 3 |
index/urls.py | darkestmidnight/fedcodeathon2018 | 1 | 5918 | <gh_stars>1-10
from django.urls import re_path, include
from . import views
app_name='logged'
# url mappings for the webapp.
urlpatterns = [
re_path(r'^$', views.logged_count, name="logged_count"),
re_path(r'^loggedusers/', views.logged, name="logged_users"),
re_path(r'^settings/', views.user_settings, na... | 1.945313 | 2 |
scout/dao/item.py | uw-it-aca/scout | 7 | 5919 | <filename>scout/dao/item.py<gh_stars>1-10
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from scout.dao.space import get_spots_by_filter, _get_spot_filters, \
_get_extended_info_by_key
import copy
def get_item_by_id(item_id):
spot = get_spots_by_filter([
('... | 1.992188 | 2 |
juriscraper/opinions/united_states/state/minnctapp.py | umeboshi2/juriscraper | 0 | 5920 | <filename>juriscraper/opinions/united_states/state/minnctapp.py
#Scraper for Minnesota Court of Appeals Published Opinions
#CourtID: minnctapp
#Court Short Name: MN
#Author: mlr
#Date: 2016-06-03
from juriscraper.opinions.united_states.state import minn
class Site(minn.Site):
# Only subclasses minn for the _dow... | 1.820313 | 2 |
monty/os/__init__.py | JosephMontoya-TRI/monty | 0 | 5921 | from __future__ import absolute_import
import os
import errno
from contextlib import contextmanager
__author__ = '<NAME>'
__copyright__ = 'Copyright 2013, The Materials Project'
__version__ = '0.1'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__date__ = '1/24/14'
@contextmanager
def cd(path):
"""
A Fabr... | 2.625 | 3 |
{{ cookiecutter.repo_name }}/tests/test_environment.py | FrancisMudavanhu/cookiecutter-data-science | 0 | 5922 | import sys
REQUIRED_PYTHON = "python3"
required_major = 3
def main():
system_major = sys.version_info.major
if system_major != required_major:
raise TypeError(
f"This project requires Python {required_major}."
f" Found: Python {sys.version}")
else:
print(">>> ... | 3.3125 | 3 |
documents/aws-doc-sdk-examples/python/example_code/kda/kda-python-datagenerator-stockticker.py | siagholami/aws-documentation | 5 | 5923 | # snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data for Amazon Kinesis Data Analytics SQL applications.]
# snippet-service:[kinesisanalytics]
# snippet-keyword:[Python]
# sn... | 2.421875 | 2 |
backend/app.py | alexespejo/project-argus | 1 | 5924 | <reponame>alexespejo/project-argus
import face_recognition
from flask import Flask, request, redirect, Response
import camera
import firestore as db
# You can change this to any folder on your system
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__)
def allowed_file(filename):
return '.' in ... | 2.796875 | 3 |
module/classification_package/src/utils.py | fishial/Object-Detection-Model | 1 | 5925 | import numpy as np
import logging
import numbers
import torch
import math
import json
import sys
from torch.optim.lr_scheduler import LambdaLR
from torchvision.transforms.functional import pad
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
sel... | 2.578125 | 3 |
tests/pylint_plugins/test_assert_raises_without_msg.py | L-Net-1992/mlflow | 0 | 5926 | import pytest
from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable
pytestmark = skip_if_pylint_unavailable()
@pytest.fixture(scope="module")
def test_case():
import pylint.testutils
from pylint_plugins import AssertRaisesWithoutMsg
class TestAssertRaisesWithou... | 2.1875 | 2 |
SVassembly/plot_bcs_across_bkpts.py | AV321/SVPackage | 0 | 5927 | import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors
import csv
from scipy.stats import mode
import math as m
import os
import collections
#set working directory
#os.chdir("/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_15072... | 2.15625 | 2 |
bites/bite029.py | ChidinmaKO/Chobe-bitesofpy | 0 | 5928 | <reponame>ChidinmaKO/Chobe-bitesofpy
def get_index_different_char(chars):
alnum = []
not_alnum = []
for index, char in enumerate(chars):
if str(char).isalnum():
alnum.append(index)
else:
not_alnum.append(index)
result = alnum[0] if len(alnum) < len(not_alnum)... | 3.328125 | 3 |
language-detection-webapp/blueprints/langid.py | derlin/SwigSpot_Schwyzertuutsch-Spotting | 6 | 5929 | import logging
from flask import Blueprint
from flask import Flask, render_template, request, flash
from flask_wtf import FlaskForm
from wtforms import StringField, validators, SelectField, BooleanField
from wtforms.fields.html5 import IntegerRangeField
from wtforms.widgets import TextArea
import langid
from utils.u... | 2.234375 | 2 |
var/spack/repos/builtin/packages/r-xts/package.py | kehw/spack | 2 | 5930 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RXts(RPackage):
"""Provide for uniform handling of R's different time-based data classes b... | 1.398438 | 1 |
sandbox/lib/jumpscale/Jumpscale/core/BASECLASSES/JSConfigsBCDB.py | threefoldtech/threebot_prebuilt | 0 | 5931 | <gh_stars>0
# Copyright (C) July 2018: TF TECH NV in Belgium see https://www.threefold.tech/
# In case TF TECH NV ceases to exist (e.g. because of bankruptcy)
# then Incubaid NV also in Belgium will get the Copyright & Authorship for all changes made since July 2018
# and the license will automatically become Apac... | 1.710938 | 2 |
source/tree.py | holderekt/regression-tree | 0 | 5932 | import utils as utl
import error_measures as err
# Regression Tree Node
class Node:
def __init__(self, parent, node_id, index=None, value=None, examples=None, prediction=0):
self.index = index
self.id = node_id
self.prediction = prediction
self.value = value
self.parent = pa... | 2.90625 | 3 |
src/site/config.py | ninaamorim/sentiment-analysis-2018-president-election | 39 | 5933 | <reponame>ninaamorim/sentiment-analysis-2018-president-election
from starlette.applications import Starlette
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles
app = Starlette(debug=False, template_directory='src/site/... | 1.132813 | 1 |
loadbalanceRL/lib/__init__.py | fqzhou/LoadBalanceControl-RL | 11 | 5934 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Contains core logic for Rainman2
"""
__author__ = '<NAME> (<EMAIL>), <NAME>(<EMAIL>)'
__date__ = 'Wednesday, February 14th 2018, 11:42:09 am'
| 1.75 | 2 |
openff/bespokefit/__init__.py | openforcefield/bespoke-f | 12 | 5935 | """
BespokeFit
Creating bespoke parameters for individual molecules.
"""
import logging
import sys
from ._version import get_versions
versions = get_versions()
__version__ = versions["version"]
__git_revision__ = versions["full-revisionid"]
del get_versions, versions
# Silence verbose messages when running the CLI ... | 1.757813 | 2 |
TRANSFORM/Resources/python/2006LUT_to_SDF.py | greenwoodms/TRANSFORM-Library | 29 | 5936 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 03 11:06:37 2018
@author: vmg
"""
import sdf
import numpy as np
# Load 2006 LUT for interpolation
# 2006 Groeneveld Look-Up Table as presented in
# "2006 CHF Look-Up Table", Nuclear Engineering and Design 237, pp. 190-1922.
# This file requires the file 2006LUTdata.tx... | 2.09375 | 2 |
test/asserting/policy.py | tmsanrinsha/vint | 2 | 5937 | import unittest
from pathlib import Path
from pprint import pprint
from vint.compat.itertools import zip_longest
from vint.linting.linter import Linter
from vint.linting.config.config_default_source import ConfigDefaultSource
class PolicyAssertion(unittest.TestCase):
class StubPolicySet(object):
def __ini... | 2.328125 | 2 |
dataprofiler/labelers/character_level_cnn_model.py | gliptak/DataProfiler | 0 | 5938 | import copy
import json
import logging
import os
import sys
import time
from collections import defaultdict
import numpy as np
import tensorflow as tf
from sklearn import decomposition
from .. import dp_logging
from . import labeler_utils
from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel
... | 1.789063 | 2 |
airflow/contrib/plugins/metastore_browser/main.py | Nipica/airflow | 0 | 5939 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | 1.507813 | 2 |
app/lib/manage.py | AaronDewes/compose-nonfree | 5 | 5940 | #!/usr/bin/env python3
# SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
import stat
import tempfile
import threading
from typing import List
from sys import argv
import os
import requests
import shutil
import json
import yaml
import subprocess
from lib.composegenerator.v0.generate imp... | 2.296875 | 2 |
features/jit-features/query/query.py | YuanruiZJU/SZZ-TSE | 13 | 5941 | <gh_stars>10-100
from query.base import BaseQuery
class CommitMetaQuery(BaseQuery):
table_name = 'commit_meta'
class DiffusionFeaturesQuery(BaseQuery):
table_name = 'diffusion_features'
class SizeFeaturesQuery(BaseQuery):
table_name = 'size_features'
class PurposeFeaturesQuery(BaseQuery):
table_... | 1.929688 | 2 |
example/mappers.py | mikeywaites/flask-arrested | 46 | 5942 | <reponame>mikeywaites/flask-arrested
from kim import Mapper, field
from example.models import Planet, Character
class PlanetMapper(Mapper):
__type__ = Planet
id = field.Integer(read_only=True)
name = field.String()
description = field.String()
created_at = field.DateTime(read_only=True)
class... | 2.609375 | 3 |
collections/ansible_collections/community/general/plugins/connection/saltstack.py | escalate/ansible-gitops-example-repository | 1 | 5943 | # Based on local.py (c) 2012, <NAME> <<EMAIL>>
# Based on chroot.py (c) 2013, <NAME> <<EMAIL>>
# Based on func.py
# (c) 2014, <NAME> <<EMAIL>>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print... | 2.234375 | 2 |
create/views.py | normaldotcom/webvirtmgr | 1 | 5944 | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from servers.models import Compute
from create.models import Flavor
from instance.models import Instance
from libvirt import l... | 2.078125 | 2 |
utils/wassersteinGradientPenalty.py | andimarafioti/GACELA | 15 | 5945 | import torch
__author__ = 'Andres'
def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
batch_size = real_data.size()[0]
alpha = torch.rand(batch_size, 1, 1, 1)
alpha = alpha.expand(real_data.size()).to(devi... | 2.3125 | 2 |
pytest_capture_log_error/test_file.py | butla/experiments | 1 | 5946 | <reponame>butla/experiments
import a_file
def test_a(capsys):
assert a_file.bla() == 5
assert a_file.LOG_MESSAGE in capsys.readouterr().err
| 2.046875 | 2 |
src_py/ui/identify_page.py | Magier/Aetia | 0 | 5947 | <reponame>Magier/Aetia
import streamlit as st
from ui.session_state import SessionState, get_state
from infer import ModelStage
def show(state: SessionState):
st.header("identify")
state = get_state()
if state.model.stage < ModelStage.DEFINED:
st.error("Please create the model first!")
| 2.421875 | 2 |
openke/data/UniverseTrainDataLoader.py | luofeisg/OpenKE-PuTransE | 0 | 5948 | <reponame>luofeisg/OpenKE-PuTransE
'''
MIT License
Copyright (c) 2020 <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 limitation the rights
to use, c... | 1.445313 | 1 |
test/jit/test_backend_nnapi.py | Hacky-DH/pytorch | 60,067 | 5949 | import os
import sys
import unittest
import torch
import torch._C
from pathlib import Path
from test_nnapi import TestNNAPI
from torch.testing._internal.common_utils import TEST_WITH_ASAN
# Make the helper files in test/ importable
pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.pa... | 2.296875 | 2 |
main/configure.py | syxu828/Graph2Seq-0.1 | 24 | 5950 | <gh_stars>10-100
train_data_path = "../data/no_cycle/train.data"
dev_data_path = "../data/no_cycle/dev.data"
test_data_path = "../data/no_cycle/test.data"
word_idx_file_path = "../data/word.idx"
word_embedding_dim = 100
train_batch_size = 32
dev_batch_size = 500
test_batch_size = 500
l2_lambda = 0.000001
learning_r... | 2.171875 | 2 |
dataControlWidget.py | andreasbayer/AEGUIFit | 0 | 5951 | from PyQt5.QtWidgets import QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox
from InftyDoubleSpinBox import InftyDoubleSpinBox
from PyQt5.QtCore import pyqtSignal, Qt
import helplib as hl
import numpy as np
class dataControlWidget(QGroupBox):
showErrorBars_changed = pyqtSignal(bool)
ignoreFirstPoint_changed ... | 2.328125 | 2 |
src/freemovr_engine/calib/acquire.py | strawlab/flyvr | 3 | 5952 | <filename>src/freemovr_engine/calib/acquire.py
import roslib
roslib.load_manifest('sensor_msgs')
roslib.load_manifest('dynamic_reconfigure')
import rospy
import sensor_msgs.msg
import dynamic_reconfigure.srv
import dynamic_reconfigure.encoding
import numpy as np
import time
import os.path
import queue
class CameraHa... | 2.0625 | 2 |
examples/hfht/pointnet_classification.py | nixli/hfta | 24 | 5953 | <gh_stars>10-100
import argparse
import logging
import numpy as np
import os
import pandas as pd
import random
import subprocess
from pathlib import Path
from hyperopt import hp
from hyperopt.pyll.stochastic import sample
from hfta.hfht import (tune_hyperparameters, attach_common_args,
rearrang... | 2.09375 | 2 |
cpdb/trr/migrations/0002_alter_trr_subject_id_type.py | invinst/CPDBv2_backend | 25 | 5954 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-03-06 04:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trr', '0001_initial'),
]
operations = [
migrations.AlterField(
... | 1.40625 | 1 |
tests/utils/dut.py | Ostrokrzew/standalone-linux-io-tracer | 24 | 5955 | #
# Copyright(c) 2020 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
from core.test_run_utils import TestRun
from utils.installer import install_iotrace, check_if_installed
from utils.iotrace import IotracePlugin
from utils.misc import kill_all_io
from test_tools.fio.fio import Fio
def dut_prepare... | 1.8125 | 2 |
game_service.py | Drew8521/MusiQ | 0 | 5956 | from models import Song
from random import choice
def random_song(genre):
results = Song.query().filter(Song.genre==genre).fetch()
print(results)
songs = choice(results)
random_song = {
"title": songs.song,
"album": songs.album,
"artist": songs.artist.lower(),
"genre": g... | 3.15625 | 3 |
stdlib/csv/custom_dialect.py | janbodnar/Python-Course | 13 | 5957 | #!/usr/bin/python
# custom_dialect.py
import csv
csv.register_dialect("hashes", delimiter="#")
f = open('items3.csv', 'w')
with f:
writer = csv.writer(f, dialect="hashes")
writer.writerow(("pencils", 2))
writer.writerow(("plates", 1))
writer.writerow(("books", 4))
| 3.296875 | 3 |
servicex/web/forms.py | zorache/ServiceX_App | 3 | 5958 | from typing import Optional
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length, Email
from servicex.models import UserModel
class ProfileForm(FlaskForm):
name = StringField('Full Name', validators=[DataRequired(), Length(... | 2.71875 | 3 |
data/studio21_generated/interview/1657/starter_code.py | vijaykumawat256/Prompt-Summarization | 0 | 5959 | <reponame>vijaykumawat256/Prompt-Summarization
def string_func(s, n):
| 1.289063 | 1 |
libs/export_pbs/exportPb.py | linye931025/FPN_Tensorflow-master | 0 | 5960 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import os, sys
import tensorflow as tf
import tf_slim as slim
from tensorflow.python.tools import freeze_graph
sys.path.append('../../')
from data.io.image_preprocess import short_side_resize_for_inference_data
from libs.configs... | 2.171875 | 2 |
ngadnap/command_templates/adapter_removal.py | smilefreak/NaDNAP | 0 | 5961 | <gh_stars>0
"""
Adapter Removal templates
"""
# AdapterRemoval
#
# {0}: executable
# {1}: fastq1 abs
# {2}: fastq2 abs
# {3}: fastq1
# {4}: fastq2
# {5}: minimum length
# {6}: mismatch_rate
# {7}: min base uality
# {8}: min merge_length
__ADAPTER_REMOVAL__="""
{0} --collapse --file1 {1} --file2 {2} --outp... | 2.171875 | 2 |
undercloud_heat_plugins/immutable_resources.py | AllenJSebastian/tripleo-common | 52 | 5962 | #
# 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.820313 | 2 |
lm5/input.py | jmcph4/lm5 | 4 | 5963 | class Input(object):
def __init__(self, type, data):
self.__type = type
self.__data = deepcopy(data)
def __repr__(self):
return repr(self.__data)
def __str__(self):
return str(self.__type) + str(self.__data)
| 3.40625 | 3 |
slybot/setup.py | DataKnower/dk-portia | 0 | 5964 | <filename>slybot/setup.py
from os.path import join, abspath, dirname, exists
from slybot import __version__
from setuptools import setup, find_packages
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.sdist import sdist
def build_js():
root = abspath(dirname(__file__))
base_path = ab... | 2.046875 | 2 |
yolov3.py | huhuhang/yolov3 | 35 | 5965 | <filename>yolov3.py
import torch
import torch.nn as nn
from .yolo_layer import *
from .yolov3_base import *
class Yolov3(Yolov3Base):
def __init__(self, num_classes=80):
super().__init__()
self.backbone = Darknet([1,2,8,8,4])
anchors_per_region = 3
self.yolo_0_pre = Yolov3... | 2.328125 | 2 |
tests/assets/test_driver_errors.py | CyrilLeMat/modelkit | 0 | 5966 | import os
import pytest
from modelkit.assets import errors
from tests.conftest import skip_unless
def _perform_driver_error_object_not_found(driver):
with pytest.raises(errors.ObjectDoesNotExistError):
driver.download_object("someasset", "somedestination")
assert not os.path.isfile("somedestination"... | 2.359375 | 2 |
wiki/tests.py | Jarquevious/makewiki | 0 | 5967 | from django.test import TestCase
from django.contrib.auth.models import User
from wiki.models import Page
# Create your tests here.
def test_detail_page(self):
""" Test to see if slug generated when saving a Page."""
# Create a user and save to the database
user = User.objects.create()
user.save()
... | 2.71875 | 3 |
BanditSim/__init__.py | AJB0211/BanditSim | 0 | 5968 | <reponame>AJB0211/BanditSim
from .multiarmedbandit import MultiArmedBandit
from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize
from .greedy_constant_stepsize import GreedyConstantStepsize
from .epsilon_greedy_average_step import EpsilonGreedyAverageStep
from .greedy_average_step import GreedyAverag... | 0.960938 | 1 |
tests/queries/test_query.py | txf626/django | 2 | 5969 | from datetime import datetime
from django.core.exceptions import FieldError
from django.db.models import CharField, F, Q
from django.db.models.expressions import SimpleCol
from django.db.models.fields.related_lookups import RelatedIsNull
from django.db.models.functions import Lower
from django.db.models.lookups import... | 2.171875 | 2 |
src/matrix_game/matrix_game.py | ewanlee/mackrl | 26 | 5970 | # This notebook implements a proof-of-principle for
# Multi-Agent Common Knowledge Reinforcement Learning (MACKRL)
# The entire notebook can be executed online, no need to download anything
# http://pytorch.org/
from itertools import chain
import torch
import torch.nn.functional as F
from torch.multiprocessing import... | 2.40625 | 2 |
pr_consistency/2.find_pr_branches.py | adrn/astropy-tools | 10 | 5971 | <reponame>adrn/astropy-tools
# The purpose of this script is to check all the maintenance branches of the
# given repository, and find which pull requests are included in which
# branches. The output is a JSON file that contains for each pull request the
# list of all branches in which it is included. We look specifica... | 2.796875 | 3 |
agents/solo_q_agents/q_agent_test/aux.py | pedMatias/matias_hfo | 1 | 5972 | <reponame>pedMatias/matias_hfo
from datetime import datetime as dt
import os
import numpy as np
import settings
def mkdir():
now = dt.now().replace(second=0, microsecond=0)
name_dir = "q_agent_train_" + now.strftime("%Y-%m-%d_%H:%M:%S")
path = os.path.join(settings.MODELS_DIR, name_dir)
try:
... | 2.40625 | 2 |
Python38/Lib/site-packages/PyInstaller/hooks/hook-PyQt4.py | AXFS-H/Windows10Debloater | 5 | 5973 | <filename>Python38/Lib/site-packages/PyInstaller/hooks/hook-PyQt4.py
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distrib... | 1.828125 | 2 |
timeserio/utils/functools.py | ig248/timeserio | 63 | 5974 | import inspect
def get_default_args(func):
"""Get default arguments of a function.
"""
signature = inspect.signature(func)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
}
| 3.125 | 3 |
Sec_10_expr_lambdas_fun_integradas/a_lambdas.py | PauloAlexSilva/Python | 0 | 5975 | <filename>Sec_10_expr_lambdas_fun_integradas/a_lambdas.py
"""
Utilizando Lambdas
Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são funções sem nome, ou seja,
funções anónimas.
# Função em Python
def funcao(x):
return 3 * x + 1
print(funcao(4))
print(funcao(7))
# Expressão Lambda
lambda x: 3 * ... | 4.125 | 4 |
ex085.py | EduotavioFonseca/ProgramasPython | 0 | 5976 | <gh_stars>0
# Lista dentro de dicionário
campeonato = dict()
gol = []
aux = 0
campeonato['Jogador'] = str(input('Digite o nome do jogador: '))
print()
partidas = int(input('Quantas partidas ele jogou? '))
print()
for i in range(0, partidas):
aux = int(input(f'Quantos gols na partida {i + 1}? '))
gol.a... | 3.71875 | 4 |
heat/initial_data.py | kjetil-lye/ismo_heat | 0 | 5977 | <reponame>kjetil-lye/ismo_heat<gh_stars>0
import numpy
class InitialDataControlSine:
def __init__(self, coefficients):
self.coefficients = coefficients
def __call__(self, x):
u = numpy.zeros_like(x)
for k, coefficient in enumerate(self.coefficients):
u += coefficient * n... | 2.609375 | 3 |
explore/scripts/get_repos_creationhistory.py | john18/uccross.github.io | 12 | 5978 | <filename>explore/scripts/get_repos_creationhistory.py
import helpers
import json
import re
datfilepath = "../github-data/labRepos_CreationHistory.json"
allData = {}
# Check for and read existing data file
allData = helpers.read_existing(datfilepath)
# Read repo info data file (to use as repo list)
dataObj = helpers... | 2.828125 | 3 |
examples/test/runMe.py | tomaszjonak/PBL | 0 | 5979 | <gh_stars>0
#! /usr/bin/env python2.7
from __future__ import print_function
import sys
sys.path.append("../../include")
import PyBool_public_interface as Bool
if __name__ == "__main__":
expr = Bool.parse_std("input.txt")
expr = expr["main_expr"]
expr = Bool.simplify(expr)
expr = Bool.nne(expr)
... | 2.0625 | 2 |
calculator.py | rupen4678/botique_management_system | 0 | 5980 | <reponame>rupen4678/botique_management_system
from tkinter import *
import random
import time
from PIL import Image
from datetime import datetime
from tinydb import *
import os
import pickle
#from database1 import *
from random import randint
root = Tk()
root.geometry("1600x800+0+0")
root.title("Suman_dai_ko_DHOKAN")
... | 2.703125 | 3 |
mmdet/models/anchor_heads/embedding_nnms_head_v2_limited.py | Lanselott/mmdetection | 0 | 5981 | import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule, Scale, bias_init_with_prob
from IPython import embed
INF = 1e8
... | 2.0625 | 2 |
firefly_flask/app/models.py | Haehnchen/trivago-firefly | 0 | 5982 | from . import db
from sqlalchemy.dialects.mysql import LONGTEXT
class Search(db.Model):
__tablename__ = 'spots'
id = db.Column(db.Integer, primary_key=True)
search_string = db.Column(db.Text)
lat = db.Column(db.Float)
lon = db.Column(db.Float)
location_name = db.Column(db.Text)
json_result ... | 2.578125 | 3 |
plotly_basic_plots/line_chart2.py | HarishOsthe/Plotly_Dash_Practice_Codes | 0 | 5983 | <gh_stars>0
import pandas as pd
import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
df= pd.read_csv("Data/nst-est2017-alldata.csv")
df2=df[df["DIVISION"] == '1']
df2.set_index("NAME",inplace=True)
list_of_pop_col=[col for col in df2.columns if col.startswith('POP')]
df2=df2[list_of_pop_col... | 2.984375 | 3 |
tests/test_markup.py | samdoran/sphinx | 4,973 | 5984 | <gh_stars>1000+
"""
test_markup
~~~~~~~~~~~
Test various Sphinx-specific markup extensions.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import pytest
from docutils import frontend, nodes, utils
from docutils.parsers.rst i... | 1.90625 | 2 |
dev/tools/leveleditor/direct/showbase/ContainerLeakDetector.py | CrankySupertoon01/Toontown-2 | 1 | 5985 | from pandac.PandaModules import PStatCollector
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen
from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr
from direct.showbase.Job import Job
import types, w... | 1.914063 | 2 |
virtual/lib/python3.6/site-packages/sqlalchemy/sql/default_comparator.py | mzazakeith/flask-blog | 207 | 5986 | <reponame>mzazakeith/flask-blog
# sql/default_comparator.py
# Copyright (C) 2005-2018 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Default implementation of SQL compariso... | 2.171875 | 2 |
recipes/serializers.py | klharshini/recipe-django-api | 0 | 5987 | <gh_stars>0
from django.contrib.auth.validators import UnicodeUsernameValidator
from rest_framework import serializers
from django.contrib.auth.models import User
from recipes.models import Recipe, Ingredient, Step
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields... | 2.234375 | 2 |
tests/test_model/test_temporal_regression_head.py | jcwon0/BlurHPE | 0 | 5988 | <reponame>jcwon0/BlurHPE
import numpy as np
import pytest
import torch
from mmpose.models import TemporalRegressionHead
def test_temporal_regression_head():
"""Test temporal head."""
head = TemporalRegressionHead(
in_channels=1024,
num_joints=17,
loss_keypoint=dict(type='M... | 2.34375 | 2 |
django_orm/sports_orm/leagues/migrations/0002_auto_20161031_1620.py | gfhuertac/coding_dojo_python | 0 | 5989 | <filename>django_orm/sports_orm/leagues/migrations/0002_auto_20161031_1620.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-31 23:20
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('leagues', '0001_initia... | 1.632813 | 2 |
353-Design-Snake-Game/solution.py | Tanych/CodeTracking | 0 | 5990 | <gh_stars>0
class SnakeGame(object):
def __init__(self, width,height,food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is po... | 4.03125 | 4 |
scripts/register_sam.py | jessebrennan/azul | 0 | 5991 | from itertools import (
chain,
)
import logging
from azul import (
config,
require,
)
from azul.logging import (
configure_script_logging,
)
from azul.terra import (
TDRClient,
TDRSourceName,
)
log = logging.getLogger(__name__)
def main():
configure_script_logging(log)
tdr = TDRClien... | 2.09375 | 2 |
altitude/players.py | StamKaly/altitude-mod-foundation | 1 | 5992 | class Player:
def __init__(self, nickname, vapor_id, player_id, ip):
self.nickname = nickname
self.vapor_id = vapor_id
self.player_id = player_id
self.ip = ip
self.not_joined = True
self.loads_map = True
self.joined_after_change_map = True
class Players:
... | 2.78125 | 3 |
dsn/editor/construct.py | expressionsofchange/nerf0 | 2 | 5993 | <reponame>expressionsofchange/nerf0<gh_stars>1-10
"""
Tools to "play notes for the editor clef", which may be thought of as "executing editor commands".
NOTE: in the below, we often connect notes together "manually", i.e. using NoteSlur(..., previous_hash). As an
alternative, we could consider `nouts_for_notes`.
"""
... | 2.125 | 2 |
src/pytong/base.py | richtong/pytong | 0 | 5994 | """Base for all Classes.
Base mainly includes the description fields
"""
import logging
from typing import Optional
from .log import Log # type: ignore
class BaseLog:
"""
Set a base logging.
Use this as the base class for all your work. This adds a logging root.
"""
def __init__(self, log_roo... | 2.765625 | 3 |
subprocess-10.py | GuillaumeFalourd/poc-subprocess | 1 | 5995 | import subprocess
import re
programs = input('Separe the programs with a space: ').split()
secure_pattern = '[\w\d]'
for program in programs:
if not re.match(secure_pattern, program):
print("Sorry we can't check that program")
continue
process = subprocess. run(
['which', program],... | 3.171875 | 3 |
authentication/socialaccount/forms.py | vo0doO/pydj-persweb | 0 | 5996 | <filename>authentication/socialaccount/forms.py
from __future__ import absolute_import
from django import forms
from authentication.account.forms import BaseSignupForm
from . import app_settings, signals
from .adapter import get_adapter
from .models import SocialAccount
class SignupForm(BaseSignupForm):
def _... | 1.984375 | 2 |
pytheos/pytheos.py | nilsbeck/pytheos | 0 | 5997 | #!/usr/bin/env python
""" Provides the primary interface into the library """
from __future__ import annotations
import asyncio
import logging
from typing import Callable, Optional, Union
from . import utils
from . import controllers
from .networking.connection import Connection
from .networking.types import SSDPRes... | 2.3125 | 2 |
test_modules/language_dictionary_test.py | 1goodday/Google-Dictionary-Pronunciation.ankiaddon | 1 | 5998 | <gh_stars>1-10
import csv
_iso_639_1_codes_file = open("files/ISO-639-1_Codes.csv", mode='r')
_iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file)
_iso_639_1_codes_dict: dict = {}
for _row in _iso_639_1_codes_dictreader:
_iso_639_1_codes_dict[_row['ISO-639-1 Code']] = _row['Language']
print(str(_i... | 2.84375 | 3 |
tianshou/data/collector.py | DZ9/tianshou | 1 | 5999 | import time
import torch
import warnings
import numpy as np
from tianshou.env import BaseVectorEnv
from tianshou.data import Batch, ReplayBuffer,\
ListReplayBuffer
from tianshou.utils import MovAvg
class Collector(object):
"""docstring for Collector"""
def __init__(self, policy, env, buffer=None, stat_si... | 2.234375 | 2 |