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 |
|---|---|---|---|---|---|---|
tools/mufom.py | asterick/pokemon-tc | 0 | 42500 | from struct import unpack
import sys, re
# Not listed:
# @SPLT
# @CALL
6# ?
FUNCTIONS = {
0x90: "<<",
0x91: ">>",
0x92: "@UDEF2",
0x93: "@DUPL",
0x94: "@EXCH",
0x95: "@UDEF5",
0x96: "@UDEF6",
0x97: "@UDEF7",
0x98: "@UDEF8",
0x99: "@UDEF9",
0x9A: "@UDEFA",
0x9B: "@UDEFB",
0x9C: "@UDEFC",
0x9D: "@UDEFD",
... | 2.28125 | 2 |
codetest.py | Shannon-NJIT/PyCharmsHW | 0 | 42501 | #adding two numbers
num1 = 2
num2 = 3
sum = num1 + num2
print("The sum is:", sum) | 4.0625 | 4 |
molder/__init__.py | lukasturcani/molder | 0 | 42502 | """
"""
from flask import Flask
import os
import json
from molder import db, site
def create_app(instance_path=None, test_config=None):
"""
Create and configure the molder Flask application.
Parameters
----------
instance_path : :class:`str`, optional
Path to the instance directory of t... | 2.75 | 3 |
Tensorflow/Test Project/basic classification.py | iggy12345/Neural-Network-Vault | 0 | 42503 | <reponame>iggy12345/Neural-Network-Vault<gh_stars>0
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__) | 1.664063 | 2 |
_scripts/generate_og.py | sp301415/sp301415.github.io | 2 | 42504 | from PIL import Image, ImageDraw, ImageFont
from urllib.request import urlopen
from textwrap import wrap
import os
BOLD_FONT_URL = "https://cdn.jsdelivr.net/gh/spoqa/spoqa-han-sans@latest/Subset/SpoqaHanSansNeo/SpoqaHanSansNeo-Bold.ttf"
LIGHT_FONT_URL = "https://cdn.jsdelivr.net/gh/spoqa/spoqa-han-sans@latest/Subset/S... | 2.90625 | 3 |
molecule/layouts/tests/test_minio_default.py | Cloud-Temple/ansible-minio | 4 | 42505 | import os
import yaml
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
dir_path = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture()
def AnsibleDefaults():
with open(os.path.j... | 1.960938 | 2 |
src/test.py | sriteja777/megathon2k19-qualcom | 0 | 42506 | <gh_stars>0
# from final import dictionary, corpus, lda
import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
import gensim
from gensim.models import LdaModel
from gensim import models, corpora, similarities
import re
from nltk.stem.porter import PorterStemmer
import time
from nltk import... | 2.875 | 3 |
setup.py | yongzx/labelmodels | 12 | 42507 | <gh_stars>10-100
from setuptools import setup, find_packages
setup(
name='labelmodels',
version='0.0.1',
url='https://github.com/BatsResearch/labelmodels.git',
author='<NAME>, <NAME>',
author_email='<EMAIL>, <EMAIL>',
description='Lightweight implementations of generative label models for '
... | 1.039063 | 1 |
experiment.py | tansey/tstd0 | 13 | 42508 | <filename>experiment.py
import sys
import csv
from gridworld import *
import qlearning
import tstd
if __name__ == "__main__":
build_rewards()
outfile = sys.argv[1]
bandits = int(sys.argv[2])
episodes = int(sys.argv[3])
world = GridWorld(num_bandits = bandits)
"""
# TESTING WITH DETERMINIS... | 2.671875 | 3 |
remedy/admin_views/resourceview.py | AllieDeford/radremedy | 0 | 42509 | """
resourceview.py
Contains administrative views for working with resources.
"""
from datetime import date
from admin_helpers import *
from sqlalchemy import or_, not_, func
from flask import current_app, redirect, flash, request, url_for
from flask.ext.admin import BaseView, expose
from flask.ext.admin.actions im... | 2.234375 | 2 |
sesion_03/songs/migrations/0001_initial.py | bernest/modulo-django-desarrollo-web-cdmx-20-05pt | 0 | 42510 | <gh_stars>0
# Generated by Django 3.1.2 on 2020-10-27 02:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Album',
fields... | 1.875 | 2 |
tb_rest_client/api/api_pe/__init__.py | maksonlee/python_tb_rest_client | 1 | 42511 | # Copyright 2020. ThingsBoard
# #
# 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 ... | 1.03125 | 1 |
src/models/description_to_salary/lstm.py | uiqkos/jobviz | 0 | 42512 | from typing import List
import tensorflow as tf
from tensorflow.keras.layers import Embedding, Layer, LSTM, Input
from src.features.preprocessing import get_embedding, get_text_vectorization
from src.models.embedding_model import EmbeddingModel
class LSTMModel(EmbeddingModel):
def __init__(self):
super(... | 2.875 | 3 |
photohub/logger/__init__.py | HurTeng/PhotoHub | 0 | 42513 | <reponame>HurTeng/PhotoHub
# coding=utf-8
import logging
from logging.handlers import RotatingFileHandler
# 日志打印
def init_logger(app):
handler = RotatingFileHandler('logs/photohub.log', maxBytes=1024 * 1024 * 2, backupCount=2)
logging_format = logging.Formatter(
'%(asctime)s %(levelname)s: %(message)... | 2.21875 | 2 |
sdk/python/pulumi_oci/core/get_dedicated_vm_host.py | EladGabay/pulumi-oci | 5 | 42514 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 1.875 | 2 |
cloud function/Database.py | Med-ELOMARI/marocovid19-dashboard | 0 | 42515 | <filename>cloud function/Database.py<gh_stars>0
import firebase_admin
from firebase_admin import credentials
# conf.json not included in the repo because it have write access to the database
cred = credentials.Certificate("conf.json")
firebase_admin.initialize_app(
cred, {"databaseURL": "https://covid19maroc-632... | 1.773438 | 2 |
Host_DM/plot_results.py | obscode/CSPMCMC | 1 | 42516 | #!/usr/bin/env python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from numpy import *
import pickle
import sys,os,string
from astropy.io import ascii
from myplotlib import PanelPlot
import config
import STANstats
import get_data
import sigfig
try:
import corner
except:
corner = None
... | 2.046875 | 2 |
api/tests/test_svs.py | gsbevilaqua/elections | 0 | 42517 | <reponame>gsbevilaqua/elections
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
from Elections import Elections
from ScoreVoting import ScoreVoting
from nose.tools import assert_equals... | 2.375 | 2 |
moai/validation/metrics/object_pose/__init__.py | tzole1155/moai | 10 | 42518 | <filename>moai/validation/metrics/object_pose/__init__.py<gh_stars>1-10
from moai.validation.metrics.object_pose.position import NormalizedPositionError
from moai.validation.metrics.object_pose.rotation import AngleError
from moai.validation.metrics.object_pose.accuracy import (
Accuracy2,
Accuracy5,
Accura... | 1.773438 | 2 |
lume/config/config.py | alice-biometrics/lume | 15 | 42519 | <filename>lume/config/config.py
from typing import Dict, List
import yaml
from lume.config.install_config import InstallConfig
from lume.config.setup_config import SetupConfig
from lume.config.step_config import StepConfig, read_env_from_file
class Config:
def __init__(self, yaml_dict: Dict = None):
if ... | 2.3125 | 2 |
religion/religion_county.py | natelowry/data_visualization | 0 | 42520 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 07:33:30 2018
@author: aaronpenne
"""
import os
import pandas as pd
import numpy as np
code_dir = os.path.dirname(__file__) # Returns full path of this script
data_dir = os.path.join(code_dir, 'data')
output_dir = os.path.join(code_dir, 'outpu... | 2.703125 | 3 |
blackjack.py | shipperizer/solid-enigma | 0 | 42521 | <gh_stars>0
from nameko_sqlalchemy import Session
from nameko.rpc import rpc
from sqlalchemy import and_
from sqlalchemy.sql.expression import func
from models import Match, Player, Deck, Card, Hand, Base
class BlackJackService:
name = "blackjack"
session = Session(Base)
@rpc
def hit(self, match_uu... | 2.640625 | 3 |
app/classifier.py | hp0404/base-classifier | 0 | 42522 | <gh_stars>0
# -*- coding: utf-8 -*-
import uuid
import spacy
from app.models import InputDocument, ModelResponse
class NER:
"""Pipe Document through a spacy model and return entities.
Usage
-----
>>> nlp = spacy.load("path/to/model")
>>> snippet = '''
Secretary of State Mike Po... | 3.078125 | 3 |
tests/test_hdf5.py | MSLNZ/MSL-IO | 6 | 42523 | import os
import tempfile
import pytest
import numpy as np
try:
import h5py
except ImportError:
h5py = None
from msl.io import read, HDF5Writer, JSONWriter
from msl.io.readers import HDF5Reader
from helper import read_sample, roots_equal
@pytest.mark.skipif(h5py is None, reason='h5py not installed')
def te... | 2.1875 | 2 |
taattack/constraints/text_constraints/min_use_sim.py | linerxliner/ValCAT | 0 | 42524 | <gh_stars>0
from taattack.utils import get_use_sim
from .text_constraint import TextConstraint
class MinUseSim(TextConstraint):
def __init__(self, threshold=0.8):
self._threshold = threshold
def _check(self, workload):
workload.sim = get_use_sim(workload.orig.text, workload.text)
r = ... | 2.5 | 2 |
src/pkgs/ui/calibrationMsgBox.py | Electronya/rc-mission-command | 0 | 42525 | import logging
import tkinter as tk
class CalibrationMsgBox():
"""
The message box class.
"""
MESSAGES = [
'Turn the steering wheel fully LEFT and press x.',
'Turn the steering wheel fully RIGHT and press x.',
'Make sure the throttle is fully DEPRESSED and press x.',
'Ma... | 3.328125 | 3 |
resources/panels/maps/images.py | exposit/pythia-oracle | 32 | 42526 | # -*- coding: utf-8 -*-
##---------------------------------------------------------------------------------------------------
#
# Images Panel
#
##---------------------------------------------------------------------------------------------------
import imports
from imports import *
import config
# set this to False... | 2.375 | 2 |
main.py | skattel49/quotes_scraper | 0 | 42527 | <filename>main.py
from enum import auto
from flask import Flask, request
from bs4 import BeautifulSoup
from flask_cors import CORS
import requests
import json
import random
import time
from dotenv import load_dotenv
import os
import json
load_dotenv()
SECRET_KEY=os.getenv("SECRET_KEY")
ACCESS_KEY=os.getenv("ACCESS_KEY... | 2.953125 | 3 |
ringity/readwrite/diagram.py | ClusterDuck123/ringity | 0 | 42528 | import numpy as np
from ringity.classes.diagram import PersistenceDiagram
def read_pdiagram(fname, **kwargs):
"""
Wrapper for numpy.genfromtxt.
"""
return PersistenceDiagram(np.genfromtxt(fname, **kwargs))
def write_pdiagram(dgm, fname, **kwargs):
"""
Wrapper for numpy.savetxt.
"""
... | 2.59375 | 3 |
dmarcap/identifiers.py | Nekmo/dmarc-aggregate-parser | 6 | 42529 | <reponame>Nekmo/dmarc-aggregate-parser
"""
dmarcap/identifiers/py - DMARC aggregate report IdentifierType representation
Ref. https://tools.ietf.org/html/rfc7489#appendix-C
"""
from builtins import object
class Identifiers(object):
"""
Represention of the aggregate record IdentifierType
"""
def __init__... | 2.140625 | 2 |
cube.py | dairequinlan/bedlam-solver | 0 | 42530 |
""" Cube class contains the logic for maintaining the current
state of the container, or Bedlam Cube, and methods for
checking, inserting, and removing individual Shape objects
from the cube space. """
""" Each Cube is made up of X * Y * Z Cuboids, Each of which
for simplicities sakes contain all the... | 4.0625 | 4 |
StaticEstimates/PriorLearn.py | horribleheffalump/AUVResearch | 4 | 42531 | <gh_stars>1-10
import numpy as np
from sklearn.model_selection import train_test_split
class PriorLearn:
def __init__(self, pipeline, train_size=1.0, already_fit=False):
self.pipeline = pipeline
self.already_fit = already_fit
self.train_size = train_size
def fit(self, x, y):
#... | 3.25 | 3 |
vsr/common/helpers/validators.py | queirozfcom/vector_space_retrieval | 0 | 42532 | def validate_positive_integer(param):
if isinstance(param,int) and (param > 0):
return(None)
else:
raise ValueError("Invalid value, expected positive integer, got {0}".format(param))
| 3.265625 | 3 |
exp_final_whitebox_attacker.py | alanefl/graph-based-recommender-attacks | 3 | 42533 | import traceback
import sys
import numpy as np
from gbra.data.network_loader import Movielens100kLoader
from gbra.attackers.attacker import *
from gbra.recommender.recommenders import PixieRandomWalkRecommender
ITERATIONS = 5
PIXIE_PARAMS = {
'n_p': 30,
'n_v': 4,
'max_steps_in_walk': 1000,
'alpha': 0... | 2.28125 | 2 |
demo/cities/urls.py | mrmikardo/django-map-widgets | 425 | 42534 | <reponame>mrmikardo/django-map-widgets
from django.urls import path, re_path
from cities.views import CityCreateView, CityListView, CityDetailView
app_name = 'cities'
urlpatterns = [
path('', CityListView.as_view(), name="list"),
re_path(r'^(?P<pk>\d+)/$', CityDetailView.as_view(), name="detail"),
re_path... | 2.09375 | 2 |
Examples/connection_test.py | Wenlin88/MonoDAQ-U-X | 1 | 42535 | <reponame>Wenlin88/MonoDAQ-U-X
from isotel.idm import gateway, monodaq
import pickle
from pathlib import Path
# For quick access; remote ip adress; username and password is stored at little.secrets pickle. Note! Newer use donwloaded pickle. It can be hacked!
little_secrets = pickle.load(open(str(Path.home()) + "/littl... | 2.25 | 2 |
figures/ts_clustering.py | ultmaster/deeper-insights-weight-sharing | 6 | 42536 | import functools
import os
from argparse import ArgumentParser
import networkx
import numpy as np
from visualize import heatmap
class MatchingClustering(object):
def __init__(self, n_clusters):
self.n_clusters = n_clusters
def fit_predict(self, X):
total = len(X)
grouping = [{i} for... | 2.78125 | 3 |
backend/algorithms/msn2_backend/elite.py | AroMorin/DNNOP | 6 | 42537 | <reponame>AroMorin/DNNOP
"""Base class for elite."""
import copy
class Elite(object):
def __init__(self, hp):
self.model = []
self.elite_score = hp.initial_score
self.minimizing = hp.minimizing
self.elite_idx = 0
def set_elite(self, pool, analyzer):
"""Checks current t... | 3.5625 | 4 |
Ex031 Custo da Viagem.py | JeanPauloGarcia/Python-Exercicios | 0 | 42538 | <filename>Ex031 Custo da Viagem.py
n = float(input('Distância viagem: '))
'''if n > 200:
n1 = n*0.45
else:
n1 = n*0.5'''
# modo 2
n1 = n*0.5 if n<=200 else n*0.45
print('Sua viagem de {}km custará {} reais'.format(n, n1))
| 3.53125 | 4 |
sfdc_cli/commands/packagexml_local.py | exiahuang/sfdc-cli | 2 | 42539 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from sfdc_cli.package_xml import PackageXml
command_name = os.path.basename(__file__).split('.', 1)[0].replace("_", ":")
def register(parser, subparsers, **kwargs):
def handler(args):
if args.scandir and args.savedir and args.name and args.apiversi... | 2.265625 | 2 |
mhack/basic_app/urls.py | team-anything/Briefly-web | 1 | 42540 | from django.conf.urls import url
from basic_app import views
# SET THE NAMESPACE!
app_name = 'basic_app'
urlpatterns=[
url(r'^register/$',views.register,name='register'),
url(r'^user_login/$',views.user_login,name='user_login'),
url(r'^add/$',views.add,name='add'),
url(r'^bookadd/$',views.bookadd,name... | 1.914063 | 2 |
messApp/reviewSystem/admin.py | vikitripathi/MB-MessApp-API | 0 | 42541 | <reponame>vikitripathi/MB-MessApp-API
from django.contrib import admin
from reviewSystem.models import Item,Category,User,Rating
# register your model here
class CategoryInline(admin.TabularInline):
model = Category
extra = 0
#raw_id_fields = ("item",)
class ItemAdmin(admin.ModelAdmin):
list_display =... | 2.0625 | 2 |
setup.py | mollinaca/slack_utils | 0 | 42542 | <filename>setup.py
from setuptools import setup, find_packages
with open('requirements.txt') as requirements_file:
install_requirements = requirements_file.read().splitlines()
setup(
name="slack_utils",
version="0.0.1",
description="my slack utils",
author="mollinaca",
packages=find_packages(),
... | 1.84375 | 2 |
4_binary_tree/node.py | PythonPostgreSQLDeveloperCourse/Section13 | 0 | 42543 | <filename>4_binary_tree/node.py
class Node:
"""
This Node class has been created for you.
It contains the necessary properties for the solution, which are:
- text
- next
"""
def __init__(self, data, value):
self.data = data
self.value = value
self.__left = None
... | 3.578125 | 4 |
PyKnife/algo/sort/quick_sort.py | Genpeng/PyKnife | 1 | 42544 | # _*_ coding: utf-8 _*_
"""
Implementation of quick sort algorithm.
Reference:
[1] https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheQuickSort.html
Author: <NAME>
"""
from typing import List
def _quick_sort(nums: List[int], li: int, ri: int) -> None:
if li >= ri:
return
sp... | 4.03125 | 4 |
skyviewbot/cli.py | cosmicpudding/skyviewbot | 1 | 42545 | #!/usr/bin/env python
"""Command-line interface for skyviewbot"""
# ASTERICS-OBELICS Good Coding Practices (skyviewbot.py)
# <NAME> (<EMAIL>), with suggestions from <NAME>
import sys
from .functions import skyviewbot
from argparse import ArgumentParser, RawTextHelpFormatter
def main(*function_args):
"""Command-... | 2.875 | 3 |
Leetcoding-Actions/Explore-Monthly-Challenges/2020-09/23-Gas-Station.py | shoaibur/SWE | 1 | 42546 | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
total_tank, curr_tank = 0, 0
start = 0
for i in range(n):
total_tank += gas[i] - cost[i]
curr_tank += gas[i] - cost[i]
# If one cou... | 3.46875 | 3 |
lib/pegasus/python/Pegasus/service/ensembles/views.py | fengggli/pegasus | 0 | 42547 | <reponame>fengggli/pegasus<filename>lib/pegasus/python/Pegasus/service/ensembles/views.py<gh_stars>0
import os
import logging
import subprocess
from flask import g, url_for, make_response, request, send_file, json
from Pegasus.db import connection
from Pegasus.service.ensembles import emapp, api, auth
from Pegasus.db... | 2.171875 | 2 |
src/pykeen/models/unimodal/ntn.py | Rodrigo-A-Pereira/pykeen | 0 | 42548 | # -*- coding: utf-8 -*-
"""Implementation of NTN."""
from typing import Any, ClassVar, Mapping, Optional
from class_resolver import Hint, HintOrType
from torch import nn
from ..nbase import ERModel
from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE
from ...nn import EmbeddingSpecification
from ...nn... | 2.90625 | 3 |
supervisely/train/src/sly_train_args.py | supervisely-ecosystem/FairMOT | 0 | 42549 | <filename>supervisely/train/src/sly_train_args.py
import sys
import sly_globals as g
# import train_config
import re
import torch
def init_script_arguments(state):
sys.argv = []
sys.argv.extend([f'task', 'mot'])
def camel_to_snake(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
... | 1.898438 | 2 |
predict_buyers_category.py | nikolai5slo/algo_sales_acceleration | 0 | 42550 | <gh_stars>0
from collections import defaultdict
import sys
import pickle
import helpers.data as data
import helpers.graph as graph
import networkx as nx
import numpy as np
from helpers.helpers import dprint, readArgs, Result, MeasureTimer, printResults
from predictor import validate_buyers_for_products
(K, orderli... | 2.3125 | 2 |
exercises/en/test_02_21b.py | betatim/MCL-DSCI-011-programming-in-python | 0 | 42551 | <gh_stars>0
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails... | 2.78125 | 3 |
BinlogCapturer/src/binlogCapturer.py | lvxinup/BaikalDB-Migrate | 3 | 42552 | # Copyright (c) 2020-present ly.com, 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.org/licenses/LICENSE-2.0
#
# Unless required by applic... | 1.585938 | 2 |
settings/local-dist.py | brianjgeiger/osf-pigeon | 0 | 42553 | <filename>settings/local-dist.py
# New tokens can be found at https://archive.org/account/s3.php
IA_ACCESS_KEY = 'change to valid token'
IA_SECRET_KEY = 'change to valid token'
DOI_FORMAT = '10.70102/fk2osf.io/{guid}'
OSF_BEARER_TOKEN = ''
DATACITE_USERNAME = None
DATACITE_PASSWORD = None
DATACITE_URL = None
DATACIT... | 1.148438 | 1 |
utils/extract_fold_data.py | ravi-0841/spect-pitch-gan | 0 | 42554 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 14:39:08 2020
@author: ravi
"""
import scipy.io as scio
import scipy.io.wavfile as scwav
import numpy as np
import joblib
import pyworld as pw
import os
import warnings
warnings.filterwarnings('ignore')
from tqdm import tqdm
from concurrent.fut... | 2.015625 | 2 |
basic_ops.py | dingmingxin/crossword_generator | 51 | 42555 | <filename>basic_ops.py
import random
import time
def generate_random_possibility(words, dim):
""" This function returns a randomly-generated possibility, instead of generating all
possible ones.
"""
# Generate possibility
possibility = {"word": words[random.randint(0, len(words)-1)],
... | 4.03125 | 4 |
mukham/detector.py | akvallapuram/mukham | 0 | 42556 | import numpy as np
import cv2
import errno
# set environment variable
import os
os.environ['OPENCV_IO_ENABLE_JASPER']= 'TRUE' # allows JPEG2000 format
# path of this file
det_path = os.path.split(os.path.abspath(__file__))[0] + '/'
class DimensionError(Exception):
"""
raised when the image does not me... | 3.1875 | 3 |
utils/tail_server_events.py | dshean/sliderule-python | 1 | 42557 | #
# Connects to SlideRule server at provided url and prints log messages
# generated on server to local terminal
#
import sys
import logging
from sliderule import sliderule
from sliderule import icesat2
###############################################################################
# GLOBAL CODE
####################... | 2.265625 | 2 |
solutions/problem34.py | wy/ProjectEuler | 0 | 42558 | <gh_stars>0
# coding: utf8
# Author: <NAME> (~wy)
# Date: 2017
# Digit Factorials
import math
def curious(n):
s = str(n)
acc = 0
for i in s:
acc += math.factorial(int(i))
return acc == n
def problem34():
acc = 0
for i in range(3,1000000):
if curious(i):
acc += i
... | 3.515625 | 4 |
hw/hw02/tests/q5.py | surajrampure/data-94-sp21 | 1 | 42559 | <gh_stars>1-10
test = { 'name': 'q5',
'points': 3,
'suites': [ { 'cases': [ {'code': ">>> big_tippers(['suraj', 15, 'isaac', 9, 'angela', 19]) == ['suraj', 'angela']\nTrue", 'hidden': False, 'locked': False},
{ 'code': ">>> big_tippers(['suraj', 15, 'isaac', 25, 'ang... | 2.21875 | 2 |
setup.py | venkatachalamlab/lambda | 0 | 42560 | import setuptools
requirements = [
'docopt',
'numpy',
'pyzmq'
]
console_scripts = [
'lambda_client=lambda_scope.zmq.client:main',
'lambda_forwarder=lambda_scope.zmq.forwarder:main',
'lambda_hub=lambda_scope.devices.hub_relay:main',
'lambda_publisher=lambda_scope.zmq.publisher:main',
'l... | 1.195313 | 1 |
tests/timestamp_tests/test_timestamp_identify.py | sslivkoff/tooltime | 0 | 42561 | <reponame>sslivkoff/tooltime
import pytest
import tooltime.spec
examples = []
for equivalent_set in tooltime.spec.equivalent_sets['Timestamp']:
examples.extend(equivalent_set.items())
@pytest.mark.parametrize('example', examples)
def test_detect_timestamp_type(example):
actual_representation, value = examp... | 2.390625 | 2 |
Plots/Contours/NCL_coneff_16.py | NCAR/GeoCAT-examples | 42 | 42562 | """
NCL_coneff_16.py
================
This script illustrates the following concepts:
- Showing features of the new color display model
- Using a NCL colormap with levels to assign a color palette to contours
- Drawing partially transparent filled contours
See following URLs to see the reproduced NCL plot & s... | 2.734375 | 3 |
handlers/users/__init__.py | Asadbek07/e-commerce-bot | 0 | 42563 | <filename>handlers/users/__init__.py
from . import start
from . import edits
from . import payment
from . import pickup
from . import get_location
from . import information_handler
from . import fikr_bildirish_handler
from . import savat_ortga
from . import biz_bilan_aloqa
from . import product_menu_handler
from . impo... | 1.125 | 1 |
app-2/application/routes.py | sc18kg/QA-PROJECT-2 | 0 | 42564 | <reponame>sc18kg/QA-PROJECT-2
from flask import Flask, Response, request
import random
from application import app
@app.route('/race', methods=['GET'])
def race():
race = ['Altmer', 'Argonian', 'Bosmer', 'Breton', 'Dunmer', 'Imperial', 'Khajiit', 'Nord', 'Orc', 'Redguard']
race = random.choice(race)
retur... | 2.671875 | 3 |
tgbot/models.py | psevdognom/gostbot | 1 | 42565 | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///gosts.db')
Session = sessionmaker(bind=engine)
s... | 2.8125 | 3 |
v0.1/core/model.py | Chaowu88/etfba | 0 | 42566 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = '<NAME>'
import re
from functools import lru_cache
import numpy as np
import pandas as pd
from .reaction import Reaction
from .metabolite import Metabolite
from ..optim.optim import FBAOptimizer, TFBAOptimizer, ETFBAOptimizer
from .pdict import PrettyDict
... | 2.46875 | 2 |
module/mclass/writeMessage.py | Saverio976/Chat-App-TUI | 3 | 42567 | """File with only WriteMessage class."""
import curses
class WriteMessage:
def __init__(self, history_file=False):
"""
Write data to the pad.
Parameters
----------
n_line: int
number of line of the pad
n_col: int
number of colu... | 3.265625 | 3 |
TBert.py | ggnicolau/Projeto-12--TBert-SP-City-Hall | 0 | 42568 | #%%Links
# BERT with Topic Model
https://www.aclweb.org/anthology/2020.acl-main.630.pdf
https://towardsdatascience.com/topic-modeling-with-bert-779f7db187e6
https://www.kaggle.com/dskswu/topic-modeling-bert-lda
https://blog.insightdatascience.com/contextual-topic-identification-4291d256a032
https://datascience.stac... | 2.09375 | 2 |
exot/util/debug.py | ETHZ-TEC/exot_eengine | 0 | 42569 | <reponame>ETHZ-TEC/exot_eengine<gh_stars>0
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# 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 ... | 1.21875 | 1 |
src/Other/LetterFrequency.py | AsclepiiusUnknown/Encrpytion | 0 | 42570 | import matplotlib.pyplot as plt
from string import ascii_uppercase
def countSpecific(_path, _letter):
_letter = _letter.strip().upper()
file = open(_path, 'rb')
text = str(file.read())
return text.count(_letter) + text.count(_letter.lower())
def countAll(_path):
file = open(_path, "rb")
text =... | 3.765625 | 4 |
Lib/test/test_compiler/test_static/readonly.py | mananpal1997/cinder | 0 | 42571 | <gh_stars>0
from compiler.errors import TypedSyntaxError
from unittest import skip
from .common import StaticTestBase
class ReadonlyTests(StaticTestBase):
def test_readonly_assign_0(self):
codestr = """
from typing import List
def foo():
x: List[int] = readonly([])
"""... | 2.703125 | 3 |
utils.py | LeoVogiatzis/GNN_based_NILM | 1 | 42572 | <reponame>LeoVogiatzis/GNN_based_NILM
import numpy as np
def mae(prediction, true):
MAE = abs(true - prediction)
MAE = np.sum(MAE)
MAE = MAE / len(prediction)
return MAE
def mse(prediction, true):
MSE = (true - prediction) ** 2
MSE = np.sum(MSE)
MSE = MSE / len(prediction)
return MSE... | 2.671875 | 3 |
tests/functional/test_get_vehicles.py | vyahello/fake-cars-api | 0 | 42573 | import requests
import pytest
from apistar import TestClient
from api.web.support import Status
from tests.markers import smoke
@pytest.fixture(scope="module")
def response(client: TestClient) -> requests.Response:
return client.get("/api")
@smoke
def test_get_vehicles_status(response: requests.Response) -> Non... | 2.34375 | 2 |
Textbook/Chapter 3/statsFunctions2.py | hunterluepke/Learn-Python-for-Stats-and-Econ | 16 | 42574 | #statsFunctions2.py
def total(list_obj):
total = 0
n = len(list_obj)
for i in range(n):
total += list_obj[i]
return total
def mean(list_obj):
n = len(list_obj)
mean = total(list_obj) / n
return mean
list1 = [3, 6, 9, 12, 15]
total_list1 = total(list1)
print(total_list1)
mean_list1... | 3.796875 | 4 |
res/script/plot_delay.py | sshpark/ETreeLearning | 0 | 42575 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter
filepath = '/Users/huangjiaming/Documents/developer/ETreeLearning/res/losses/delay_etree.txt'
x = []
num = 0
with open(filepath) as fp:
for line in fp:
c = list(map(int, line.split()))
x = c
print(np.... | 2.4375 | 2 |
Extras/002ex.py | lucasbraga10/ListaDeExerciciosPython | 0 | 42576 | hora = input('Digite a hora atual: ')
try:
hora = int(hora)
if 0 <= hora <= 11:
print('Bom Dia')
elif 12 <= hora <= 17:
print('Boa Tarde')
elif 18 <= hora <= 23:
print('Boa Noite')
else:
print('Valor Inválido')
except:
print('Valor Inválido')
| 3.953125 | 4 |
src/aoc/y2021/day1.py | Lexicality/advent-of-code | 0 | 42577 | <filename>src/aoc/y2021/day1.py
from collections import defaultdict
from typing import DefaultDict, Iterable
def _windows(index: int, max: int) -> Iterable[int]:
for i in range(index - 2, index + 1):
if i >= 0 and i < max:
yield i
def main(data: Iterable[str]) -> None:
nums = [int(line) ... | 3.515625 | 4 |
src/api/resources/astro_object/parsers.py | alercebroker/ztf-api-apf | 1 | 42578 | from flask_restx import reqparse
from db_plugins.db.sql import models
columns = []
for c in models.Object.__table__.columns:
columns.append(str(c).split(".")[1])
for c in models.Probability.__table__.columns:
columns.append(str(c).split(".")[1])
def str2bool(v):
if isinstance(v, bool):
return v
... | 2.578125 | 3 |
process_output.py | andrewrgarcia/python_import | 1 | 42579 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 25 15:06:45 2019
@author: garci
"""
import matplotlib.pyplot as plt
import numpy as np
import csv
import xlwings as xw
import pandas
import os
'''MAKE X-Y PLOTS WITH 2-COLUMN FILES
<NAME>, 2019 '''
'''lastRow credit: answered Sep 14 '16 at 11:39 - Stefan
https://st... | 3.515625 | 4 |
run_2c/figures/plot_ivs.py | braghiere/3D_FSPM | 0 | 42580 |
import numpy as np
import matplotlib.pyplot as plt
import os, sys
from scipy.interpolate import interp2d
from pylab import *
filelist=[]
#error = []
biomrsd1= []
biomrsd2= []
dirname1 = "/home/renato/groimp_efficient/run_1/"
dirname2 = "/home/renato/groimp_efficient/run_1c/jules/"
list = [94]
for i in range(1,2):... | 2.34375 | 2 |
pygatt/backends/bgapi/constants.py | Jakeler/ut61e-pygatt | 0 | 42581 | ble_address_type = {
'gap_address_type_public': 0,
'gap_address_type_random': 1
}
gap_discoverable_mode = {
'non_discoverable': 0x00,
'limited_discoverable': 0x01,
'general_discoverable': 0x02,
'broadcast': 0x03,
'user_data': 0x04,
'enhanced_broadcasting': 0x80
}
gap_connectable_mode = {... | 1.726563 | 2 |
Awesome-Scripts/imdbScrapper.py | greengangsta/Lecture-Series-Python | 25 | 42582 | import urllib
from bs4 import BeautifulSoup
print ("Collecting data from IMDb charts....\n\n\n")
print ("The current top 15 IMDB movies are the following: \n\n")
response = urllib.request.urlopen("http://www.imdb.com/chart/top")
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
mytd = soup.findAll("td",... | 3.234375 | 3 |
shop/mainapp/urls.py | Monkey8bit/django-basics | 0 | 42583 | from django.urls import path
import mainapp.views as mainapp
app_name = "mainapp"
urlpatterns = [
path("", mainapp.product, name="index"),
path("<int:pk>/", mainapp.product, name="category"),
path("<int:pk>/page/<int:page>/", mainapp.product, name="page"),
path("product/<int:pk>/", mainapp.product_p... | 1.71875 | 2 |
PC_2.py | thedognexttothetrashcan/taobao | 0 | 42584 | import datetime
import os
import random
import time
import requests
from lxml import etree
from selenium import webdriver
# import config
import threading
# import numpy as np
mUA_list = [
'Mozilla/5.0 (iPhone; CPU iPhone OS 11_2_1 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0 Mobile/15C153... | 2.53125 | 3 |
helpdesk/userportal/management/commands/update_secret_key.py | winstc/helpdesk | 1 | 42585 | import os
import random
import string
import json
from django.core.management import BaseCommand
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, <NAME>"
__licence__ = "BSD 2-Clause Licence"
__version__ = "1.0"
__email__ = "<EMAIL>"
class Command(BaseCommand):
def is_valid_file(self, file):
if no... | 2.3125 | 2 |
rosalindLibrary/programs/fib.py | aevear/RosalindProject | 1 | 42586 | <reponame>aevear/RosalindProject
#-------------------------------------------------------------------------------
# mrna
#-------------------------------------------------------------------------------
def runFib(inputFile):
fi = open(inputFile, 'r') #reads in the file that list the before/after file names
inp... | 3.1875 | 3 |
app/main/forms.py | tonyishangu/Pitch | 0 | 42587 | from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField, SelectField
from wtforms.validators import Required
class PitchForm(FlaskForm):
title = StringField('Pitch title',validators=[Required()])
category = SelectField('Pitch category', choices=[('Motivational', 'Motivational... | 2.71875 | 3 |
docker/GetAndResizeImages.py | vaquarkhan/ecs-refarch-batch-processing | 105 | 42588 | #!/usr/bin/env python
# Copyright 2016 Amazon.com, Inc. or its
# affiliates. 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. A copy of the License is
# located at
#
# http://aws.amazon.com/apache2.0/
#
# or i... | 2.28125 | 2 |
bear.py | jenwich/practicum_game_project | 0 | 42589 | <filename>bear.py
import pygame, random
bears = []
bear_img = pygame.image.load("src/images/Bear.png")
class Bear:
width = 64
height = 136
hp = 1
def __init__(self, screen, gameMap, moveDir, speed):
self.screen = screen
self.gameMap = gameMap
self.moveDir = moveDir
sel... | 3.171875 | 3 |
ekmap_core/qgslayer_parser/marker_symbol/svg_marker_parser.py | eKMap/ekmap-publisher-for-qgis | 4 | 42590 | from .marker_layer_parser import MarkerLayerParser
# This is a parser for svg image
class SvgMarkerParser(MarkerLayerParser):
def __init__(self, svgMarkerParser):
super().__init__(svgMarkerParser)
# Except image information like RasterMarker
# this marker contains some paint information t... | 2.75 | 3 |
app.py | johnbomidi/data-explorer-dash-app | 0 | 42591 |
from dash_extensions.enrich import Dash
from _app.layout import serve_layout
from _app.callback import register_callbacks
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(prevent_initial_callbacks=True,
external_stylesheets=external_stylesheets
)
register_c... | 1.640625 | 2 |
theano/compile/tests/test_function_name.py | mdda/Theano | 295 | 42592 | <gh_stars>100-1000
import unittest
import os
import re
import theano
from theano import tensor
class FunctionName(unittest.TestCase):
def test_function_name(self):
x = tensor.vector('x')
func = theano.function([x], x + 1.)
regex = re.compile(os.path.basename('.*test_function_name.pyc?:1... | 2.21875 | 2 |
tester-webserv/PythonTester/src/testcase_generation/Response/media_type.py | aprilmayjune135/42_web_server | 2 | 42593 | import TestCase
from testcase_generation.Response.default import defaultTestCase
import Constants
def defaultMediaTypeTestCase():
testcase = defaultTestCase()
# Request
testcase.request.method = 'GET'
# Response
testcase.response.status_code = 200
testcase.response.expect_body = True
return testcase
def testC... | 2.34375 | 2 |
hackerrank/Python/Min and Max/solution.py | ATrain951/01.python-com_Qproject | 4 | 42594 | <reponame>ATrain951/01.python-com_Qproject
import numpy
n, m = map(int, input().split())
a = numpy.array([input().split() for _ in range(n)], dtype=int)
print(numpy.max(numpy.min(a, axis=1), axis=0))
| 3.09375 | 3 |
api/routes/index.py | AlbertQueiroz/finalchallenge-api | 3 | 42595 | <filename>api/routes/index.py
from flask import jsonify
from api import app
import logging as logger
@app.route('/api/v1', methods=['GET'])
@app.route('/', methods=['GET'])
def index():
logger.debug("Inside the get method of index")
response = {
'message': 'API is ready for use!',
'url': [
... | 2.6875 | 3 |
solvers.py | brendanhogan/rubiks_cube_solving | 0 | 42596 |
import numpy as np
from typing import List, Tuple
class InterfaceSolver():
"""
Informal interface for solving class needed to interact with rubiks
environment.
"""
def __init__(self, depth:int, possible_moves: List[str]) -> None:
"""
Will be passed depth, i.e. number of backwa... | 3.625 | 4 |
test/unit_tests/sampling/test__boosting.py | KIC/pandas_utils | 3 | 42597 | <reponame>KIC/pandas_utils
from unittest import TestCase
import numpy as np
from pandas_ml_utils.sampling.boosting import KFoldBoostRareEvents, KEquallyWeightEvents
from pandas_ml_utils.utils.functions import unfold_parameter_space, one_hot
class TestBoosting(TestCase):
def test_rare_events_boosting(self):
... | 2.390625 | 2 |
forum/tests.py | sebastian-code/portal | 1 | 42598 | <filename>forum/tests.py
from django.test import TestCase
from .models import Pregunta, Respuesta
from model_mommy import mommy
def gen_func():
return 'this-is-an-sluged-example'
class TestModels(TestCase):
def test_model_pregunta(self):
pregunta = mommy.make(Pregunta)
self.assertTrue(isin... | 2.59375 | 3 |
testing/tests/python/e2e_test.py | ldynia/lucky-app | 0 | 42599 | #!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.common.by import By
class TestLuckyApp:
"""E2E integration tests class."""
def setup_method(self, method):
options = webdriver.FirefoxOptions()
self.driver = webdriver.Remote('http://firefoxdriver:4444/wd/hub', opt... | 2.90625 | 3 |