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 |
|---|---|---|---|---|---|---|
readfile.py | y-azvd/perceptron | 0 | 23400 | <reponame>y-azvd/perceptron<filename>readfile.py
import numpy as np
##
## @brief function_description
##
## @param filename The filename
##
## @return description_of_the_return_value
##
def readfile(filename):
csvfile = open(filename, "r")
if not csvfile:
print "error"
return -1
rows = []
f... | 3.296875 | 3 |
utils.py | SappieKonig/eind-practicum | 0 | 23401 | <gh_stars>0
import numpy as np
import cv2 as cv
import os
import shutil
from skimage.util.shape import view_as_windows
import torch.nn.functional as F
import torch
from functools import lru_cache
@lru_cache(maxsize=None)
def get_exp_decay_filter(filter_size=1, decay=.9, avg=True):
side = 2 * filter_size + 1
f... | 2.15625 | 2 |
python/pangram.py | emiliot/hackerrank | 0 | 23402 | <filename>python/pangram.py
s = input().strip()
res = [c for c in set(s.lower()) if c.isalpha()]
if len(res) == 26:
print("pangram")
else:
print("not pangram")
| 4.03125 | 4 |
stream.py | ccgcyber/xpcap | 5 | 23403 | from __future__ import print_function
import pkgutil
import stream_decoders
# this module decodes stream based protocols.
# and resolves retransmissions.
decoders= []
# __path__ is used to find the location of all decoder submodules
for impimp, name, ii in pkgutil.iter_modules(stream_decoders.__path__):
impload= ... | 2.453125 | 2 |
app/db/connection.py | melhin/streamchat | 0 | 23404 | import logging
import aioredis
from app.core.config import REDIS_DSN, REDIS_PASSWORD
logger = logging.getLogger(__name__)
async def get_redis_pool():
return await aioredis.create_redis(REDIS_DSN, encoding='utf-8', password=REDIS_PASSWORD)
| 2.1875 | 2 |
calculators/static_dipolar_couplings/dcc.py | jlorieau/nmr | 0 | 23405 | <reponame>jlorieau/nmr<filename>calculators/static_dipolar_couplings/dcc.py
from math import pi
u0 = 4.*pi*1E-7 # T m /A
hbar = 1.0545718E-34 # J s
# 1 T = kg s^-2 A-1 = J A^-1 m^-2
g = {
'1H' : 267.513E6, # rad T^-1 s^-1
'13C': 67.262E6,
'15N': -27.116E6,
'e': 176086E6
}
# nuc_i, nuc_j: nucleu... | 2.34375 | 2 |
torchvision/prototype/datasets/_builtin/country211.py | SariaCxs/vision | 1 | 23406 | import pathlib
from typing import Any, Dict, List, Tuple
from torchdata.datapipes.iter import IterDataPipe, Mapper, Filter
from torchvision.prototype.datasets.utils import Dataset, DatasetConfig, DatasetInfo, HttpResource, OnlineResource
from torchvision.prototype.datasets.utils._internal import path_comparator, hint_... | 2.25 | 2 |
asar_pi_applications/asar_vision/robot_distance_incorrect.py | ssnover/msd-p18542 | 3 | 23407 | import numpy as np
from math import sqrt
def robot_distance_incorrect(robot_actual_location, hexagon_pixel_values):
distance_to_get_back = []
distances = []
pixel_distance = []
for i in range(0, len(hexagon_pixel_values)):
dist = sqrt((robot_actual_location[0] - hexagon_pixel_values[i][0]) ** ... | 3.421875 | 3 |
tests/test_generate_unique_id_function.py | ssensalo/fastapi | 1 | 23408 | import warnings
from typing import List
from fastapi import APIRouter, FastAPI
from fastapi.routing import APIRoute
from fastapi.testclient import TestClient
from pydantic import BaseModel
def custom_generate_unique_id(route: APIRoute):
return f"foo_{route.name}"
def custom_generate_unique_id2(route: APIRoute)... | 2.4375 | 2 |
hbruraldoctor/hbvirtual/lib/python3.7/site-packages/Naked/app.py | hallohubo/DjangoDocterAPI | 89 | 23409 | #!/usr/bin/env python
# encoding: utf-8
#------------------------------------------------------------------------------
# Naked | A Python command line application framework
# Copyright 2014 <NAME>
# MIT License
#------------------------------------------------------------------------------
#-------------------------... | 2.671875 | 3 |
codes/day7_task1.py | tayyrov/AdventOfCode | 1 | 23410 | <reponame>tayyrov/AdventOfCode<gh_stars>1-10
"""
Advent Of Code 2021
Day 7
Date: 07-12-2021
Site: https://adventofcode.com/2021/day/7
Author: Tayyrov
"""
import sys
file1 = open('../input_files/day7_input', 'r')
numbers = list(map(int, file1.readlines()[0].split(",")))
numbers.sort()
middle = numbers... | 3.09375 | 3 |
events/utils.py | ewjoachim/pythondotorg | 0 | 23411 | import datetime
import re
import pytz
from django.utils.timezone import make_aware, is_aware
def seconds_resolution(dt):
return dt - dt.microsecond * datetime.timedelta(0, 0, 1)
def minutes_resolution(dt):
return dt - dt.second * datetime.timedelta(0, 1, 0) - dt.microsecond * datetime.timedelta(0, 0, 1)
... | 2.796875 | 3 |
frontend/main.py | loukwn/klougle | 2 | 23412 | <filename>frontend/main.py
import json
import operator
import os
import webbrowser
from timeit import default_timer as timer
from kivy.app import App
from kivy.config import Config
from kivy.properties import ObjectProperty
from kivy.uix.stacklayout import StackLayout
from nltk.stem.wordnet import WordNetLemmatizer
C... | 2.765625 | 3 |
test.py | richisusiljacob/VideoTo360VR | 5 | 23413 | <filename>test.py<gh_stars>1-10
from tkinter import *
import tkinter.ttk as ttk
from PIL import ImageTk,Image
""" root = Tk()
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()
img = ImageTk.PhotoImage(Image.open("output/collage1/FinalCollage.jpg"))
canvas.create_image(0,0,anchor=NW, image=img) ... | 3.078125 | 3 |
testscripts/RDKB/component/WEBCONFIG/TS_WEBCONFIG_DisableRFC_QuerySyncParams.py | rdkcmf/rdkb-tools-tdkb | 0 | 23414 | ##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2021 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... | 1.273438 | 1 |
xappt_qt/plugins/tools/examples/auto_advance.py | cmontesano/xappt_qt | 0 | 23415 | import time
import xappt
@xappt.register_plugin
class AutoAdvance(xappt.BaseTool):
message = xappt.ParamString(options={"ui": "label"})
next_iteration_advance_mode = xappt.ParamInt(choices=("no auto advance", "auto advance"))
def __init__(self, *, interface: xappt.BaseInterface, **kwargs):
super... | 2.578125 | 3 |
play-1.2.4/python/Lib/site-packages/Rpyc/Utils/Discovery.py | AppSecAI-TEST/restcommander | 550 | 23416 | <reponame>AppSecAI-TEST/restcommander<gh_stars>100-1000
"""
Discovery: broadcasts a query, attempting to discover all running RPyC servers
over the local network/specific subnet.
"""
import socket
import select
import struct
__all__ = ["discover_servers"]
UDP_DISCOVERY_PORT = 18813
QUERY_MAGIC = "RPYC_QUERY"
MAX_DGRA... | 2.5 | 2 |
atest/testresources/testlibs/objecttoreturn.py | userzimmermann/robotframework | 7 | 23417 | <gh_stars>1-10
try:
import exceptions
except ImportError: # Python 3
import builtins as exceptions
class ObjectToReturn:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def exception(self, name, msg=""):
exception = getattr(exceptions, name)... | 2.90625 | 3 |
quiz/models.py | jzi040941/django_quiz | 1 | 23418 | <gh_stars>1-10
from django.db import models
# Create your models here.
class quiz_short(models.Model):
AssignNum = models.ForeignKey('teacher.Assignment', on_delete=models.CASCADE)
Question = models.TextField()
Answer = models.TextField()
def __str__(self):
return "AssignNum : %s, question: %s... | 2.578125 | 3 |
benchmark/VAR/GG/common.py | victor-estrade/SystGradDescent | 2 | 23419 | # coding: utf-8
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
| 1.054688 | 1 |
problems/problem3.py | JakobHavtorn/euler | 0 | 23420 | """Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
"""
import math
import numpy as np
def largest_prime_factor_naive(number):
"""
Let the given number be n and let k = 2, 3, 4, 5, ... .
For each k, if it is a factor of n ... | 3.9375 | 4 |
aio_binance/futures/usdt/api/methods/stream.py | GRinvest/aiobinance | 5 | 23421 | <filename>aio_binance/futures/usdt/api/methods/stream.py
class DataStream:
async def create_private_listen_key(self) -> dict:
"""**Create a ListenKey (USER_STREAM)**
Notes:
``POST /fapi/v1/listenKey``
See Also:
https://binance-docs.github.io/apidocs/futures/en/#st... | 2.265625 | 2 |
nova/tests/test_hooks.py | bopopescu/zknova | 0 | 23422 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack, LLC.
# 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... | 2.046875 | 2 |
code/reasoningtool/kg-construction/QueryUniprot.py | andrewsu/RTX | 31 | 23423 | """ This module defines the class QueryUniprot which connects to APIs at
http://www.uniprot.org/uploadlists/, querying reactome pathways from uniprot id.
* map_enzyme_commission_id_to_uniprot_ids(ec_id)
Description:
map enzyme commission id to UniProt ids
Args:
ec_id (str): enzyme commissio... | 2.59375 | 3 |
code_trunk/emb.py | chris4540/DD2430-ds-proj | 0 | 23424 | <gh_stars>0
import torch
from network.siamese import SiameseNet
from network.resnet import ResidualEmbNetwork
import os
import numpy as np
from utils.datasets import DeepFashionDataset
from torchvision.transforms import Compose
from torchvision.transforms import Resize
from torchvision.transforms import ToTensor
from t... | 1.882813 | 2 |
src/stations/datastructures.py | cwerner/st-folium-demo | 1 | 23425 | <filename>src/stations/datastructures.py
from enum import Enum
# ifu
ifu = {"name": "IFU", "geo_lat": 47.476180, "geo_lon": 11.063350}
# tereno stations
tereno_stations = [
{"name": "Fendth", "geo_lat": 47.83243, "geo_lon": 11.06111},
{"name": "Grasswang", "geo_lat": 47.57026, "geo_lon": 11.03189},
{"name... | 3.09375 | 3 |
Tools/Scripts/Python/module_Basemap_RegCM_domain.py | taobrienlbl/RegCM | 27 | 23426 | <reponame>taobrienlbl/RegCM<gh_stars>10-100
#!/usr/bin/python2.6
""" Here a comment starts, with 3 quotation marks. In the same way, the comment ends ...
Purpose: Draw a base map of the CORDEX domain
Selected projection: Lambert Conformal Projection
Date: Sept. 26, 2018
Author: <NAME>
REFERENCES:... | 2.578125 | 3 |
old_game/combat.py | jwvhewitt/dmeternal | 53 | 23427 | <gh_stars>10-100
from . import characters
from . import teams
from . import hotmaps
from . import pygwrap
import pygame
from . import maps
import collections
from . import image
from . import pfov
import random
from . import stats
from . import rpgmenu
from . import animobs
from . import effects
from . import enchantme... | 2.28125 | 2 |
tests/testJobQueue.py | hartloff/Tango | 2 | 23428 | import unittest
import redis
from jobQueue import JobQueue
from tangoObjects import TangoIntValue, TangoJob
from config import Config
class TestJobQueue(unittest.TestCase):
def setUp(self):
if Config.USE_REDIS:
__db = redis.StrictRedis(
Config.REDIS_HOSTNAME, Config.REDIS_PO... | 2.515625 | 3 |
hybmc/products/Swap.py | sschlenkrich/HybridMonteCarlo | 3 | 23429 | <filename>hybmc/products/Swap.py
#!/usr/bin/python
import sys
sys.path.append('./')
import QuantLib as ql
from hybmc.simulations.Payoffs import Payoff, Fixed, ZeroBond, LiborRate, Cache, Asset
from hybmc.simulations.AmcPayoffs import AmcSum
from hybmc.products.Product import Product
def DiscountedPayoffFromCashFlow... | 2 | 2 |
src/streamlink/plugins/tamago.py | hymer-up/streamlink | 5 | 23430 | import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.stream import HTTPStream
from streamlink import NoStreamsError
class Tamago(Plugin):
_url_re = re.compile(r"https?://(?:player\.)?tamago\.live/w/(?P<id>\d+)")
_api_url_base = "https://player.tamago.liv... | 2.328125 | 2 |
models/misc/modules.py | zgjslc/Film-Recovery-master1 | 0 | 23431 | """
Name: modules.py
Desc: This script defines some base module for building networks.
"""
from typing import Any
import torch
import torch.nn as nn
import torch.nn.functional as F
class UNet_down_block(nn.Module):
def __init__(self, input_channel, output_channel, down_size=True):
super(UNet_down_block,... | 2.515625 | 3 |
flask_webpack_bundle/config.py | briancappello/flask-webpack-bundle | 0 | 23432 | import os
from flask_unchained import AppConfig
class Config(AppConfig):
WEBPACK_MANIFEST_PATH = os.path.join(
AppConfig.STATIC_FOLDER, 'assets', 'manifest.json')
class ProdConfig:
# use relative paths by default, ie, the same host as the backend
WEBPACK_ASSETS_HOST = ''
class StagingConfig(P... | 1.765625 | 2 |
touchdown/aws/elasticache/replication_group.py | yaybu/touchdown | 14 | 23433 | <gh_stars>10-100
# Copyright 2014 Isotoma Limited
#
# 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 agr... | 1.789063 | 2 |
core/env.py | ayyuriss/EigenFunctions | 0 | 23434 | <gh_stars>0
import xxhash
import numpy as np
from base.grid import SimpleGRID
import scipy.sparse as SP
h = xxhash.xxh64()
s_to_i = lambda x,size : size*x[0]+x[1]
i_to_s = lambda x,size : (x%size,x//size)
def hash(x):
h.reset()
h.update(x)
return h.digest()
class Indexer(object):
def __init__(... | 2 | 2 |
tests/test_properties.py | jmborr/ipdflex | 3 | 23435 | <reponame>jmborr/ipdflex
import random
import numpy as np
import pytest
import tempfile
import shutil
from idpflex import properties as ps
from idpflex.properties import SecondaryStructureProperty as SSP
class TestRegisterDecorateProperties(object):
def test_register_as_node_property(self):
class SomePr... | 2.28125 | 2 |
3d_cnn/src/constants/particles.py | mrmattuschka/DeePiCt | 0 | 23436 | <filename>3d_cnn/src/constants/particles.py
from os.path import join
def create_particle_file_name(folder_path: str, img_number: int,
coord_indx: int, ext: str) -> str:
file_name = str(img_number) + 'particle' + str(coord_indx) + '.' + ext
return join(folder_path, file_name)
| 2.390625 | 2 |
unn/models/heads/utils/loss.py | zongdaoming/TinyTransformer | 2 | 23437 | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from .... import extensions as E
from . import accuracy as A
logger = logging.getLogger('global')
def _reduce(loss, reduction, **kwargs):
if reduction == 'none':
ret = loss
elif reduction == 'mean':
normalizer... | 2.546875 | 3 |
integration/phore/tests/shardsynctest.py | phoreproject/synapse | 9 | 23438 | <filename>integration/phore/tests/shardsynctest.py
import logging
from phore.framework import tester, validatornode, shardnode
from phore.pb import common_pb2
class ShardSyncTest(tester.Tester):
def __init__(self):
logging.info(logging.INFO)
super().__init__()
def _do_run(self):
bea... | 2.203125 | 2 |
chartconvert/mpp.py | e-sailing/avnav | 0 | 23439 | <filename>chartconvert/mpp.py<gh_stars>0
#! /usr/bin/env python
#
# vim: ts=2 sw=2 et
#
import sys
#from wx.py.crust import Display
inchpm=39.3700
dpi=100
if len(sys.argv) >1:
dpi=int(sys.argv[1])
displaympp=1/(float(dpi)*inchpm)
print "display mpp=%f"%(displaympp)
mpp= 20037508.342789244 * 2 / 256
print "Leve... | 2.421875 | 2 |
Lower_Upper_Counter/Lower_Upper_Counter.py | GracjanBuczek/Python | 0 | 23440 | <filename>Lower_Upper_Counter/Lower_Upper_Counter.py
x = input("Enter sentence: ")
count={"Uppercase":0, "Lowercase":0}
for i in x:
if i.isupper():
count["Uppercase"]+=1
elif i.islower():
count["Lowercase"]+=1
else:
pass
print ("There is:", count["Uppercase"], "uppercases.")
print ("... | 4.03125 | 4 |
examples/driving_in_traffic/scenarios/loop/scenario.py | zbzhu99/SMARTS | 2 | 23441 | <filename>examples/driving_in_traffic/scenarios/loop/scenario.py<gh_stars>1-10
from pathlib import Path
from smarts.sstudio import gen_scenario
from smarts.sstudio import types as t
traffic = t.Traffic(
flows=[
t.Flow(
route=t.RandomRoute(),
rate=60 * 60,
actors={t.Traf... | 2.375 | 2 |
asyncorm/models/models.py | kejkz/asyncorm | 1 | 23442 | import inspect
import os
from collections import Callable
from asyncorm.application.configure import get_model
from asyncorm.exceptions import AsyncOrmFieldError, AsyncOrmModelDoesNotExist, AsyncOrmModelError
from asyncorm.manager import ModelManager
from asyncorm.models.fields import AutoField, Field, ForeignKey, Man... | 2.21875 | 2 |
pyseq/main.py | nygctech/PySeq2500 | 9 | 23443 | <gh_stars>1-10
"""
TODO:
"""
import time
import logging
import os
from os.path import join
import sys
import configparser
import threading
import argparse
from . import methods
from . import args
from . import focus
# Global int to trac... | 2.78125 | 3 |
tests/parser/rewriting.projection.4.test.py | veltri/DLV2 | 0 | 23444 | input = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
output = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
| 2.578125 | 3 |
focus/receiver.py | frederikhermans/focus | 6 | 23445 | <filename>focus/receiver.py<gh_stars>1-10
# Copyright (c) 2016, <NAME>, <NAME>
#
# This file is part of FOCUS and is licensed under the 3-clause BSD license.
# The full license can be found in the file COPYING.
import cPickle as pickle
import sys
import click
import imageframer
import numpy as np
import rscode
impor... | 2.15625 | 2 |
calc/bond.py | RaphaelOneRepublic/financial-calculator | 2 | 23446 | <filename>calc/bond.py
import logging
from typing import Sequence
import numpy as np
from calc.optimize import root
class Bond(object):
"""
Represents a coupon paying bond.
Upon creation, the time to maturity, coupon periods per year, coupon rate must be provided.
If yield to maturity is provided, b... | 3.4375 | 3 |
jasy/build/Script.py | sebastian-software/jasy | 2 | 23447 | #
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
# Copyright 2013-2014 <NAME>
#
import os
import jasy
import jasy.core.Console as Console
from jasy.item.Script import ScriptError
from jasy.item.Script import ScriptItem
import jasy.script.Resolver as ScriptResolver
from jasy.script.Resolver import R... | 1.90625 | 2 |
13.py | kwoshvick/project-euler | 0 | 23448 | <reponame>kwoshvick/project-euler<filename>13.py
file = open("13")
sum = 0
for numbers in file:
#print(numbers.rstrip())
numbers = int(numbers)
sum += numbers;
print(sum)
sum = str(sum)
print(sum[:10])
| 3.359375 | 3 |
snlds/model_cavi_snlds.py | egonrian/google-research | 3 | 23449 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | 2.46875 | 2 |
grid_search/mlp_gridsearch.py | RiboswitchClassifier/RiboswitchClassification | 2 | 23450 | <reponame>RiboswitchClassifier/RiboswitchClassification<gh_stars>1-10
from sklearn.model_selection import cross_val_score, GridSearchCV, cross_validate, train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.neural_network import MLPClassifier
import pandas as pd
import csv
fro... | 2.78125 | 3 |
bermuda/demos/shape_options.py | glue-viz/bermuda | 1 | 23451 | import matplotlib.pyplt as plt
from bermuda import ellipse, polygon, rectangle
plt.plot([1,2,3], [2,3,4])
ax = plg.gca()
# default choices for everything
e = ellipse(ax)
# custom position, genric interface for all shapes
e = ellipse(ax, bbox = (x, y, w, h, theta))
e = ellipse(ax, cen=(x, y), width=w, height=h, the... | 3 | 3 |
porthole/contact_management.py | speedyturkey/porthole | 3 | 23452 | <reponame>speedyturkey/porthole<filename>porthole/contact_management.py
from sqlalchemy.orm.exc import NoResultFound
from porthole.app import Session
from .logger import PortholeLogger
from porthole.models import AutomatedReport, AutomatedReportContact, AutomatedReportRecipient
class AutomatedReportContactManager(obj... | 2.34375 | 2 |
tests/python/benchmarks/two_neighborhood_bench.py | sid17/weaver | 163 | 23453 | <gh_stars>100-1000
#! /usr/bin/env python
#
# ===============================================================
# Description: Two neighborhood benchmark
#
# Created: 2014-03-21 13:39:06
#
# Author: <NAME>, <EMAIL>
#
# Copyright (C) 2013-2014, Cornell University, see the LICENSE
# ... | 2.296875 | 2 |
composer/datasets/brats_hparams.py | growlix/composer | 0 | 23454 | # Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""BraTS (Brain Tumor Segmentation) dataset hyperparameters."""
from dataclasses import dataclass
import torch
import yahp as hp
from composer.datasets.brats import PytTrain, PytVal, get_data_split
from composer.datasets.dataset_hparam... | 2.40625 | 2 |
examples/getchar.py | scalabli/quo | 3 | 23455 | from quo.getchar import getchar
getchar()
| 1.179688 | 1 |
setup.py | cfbolz/syntaxerrors | 5 | 23456 | from setuptools import setup, find_packages
setup(
name='syntaxerrors',
version='0.0.1',
description='Report better SyntaxErrors',
author='<NAME>',
author_email='<EMAIL>',
packages=['syntaxerrors'],
package_dir={'': 'src'},
include_package_data=True,
)
| 1.195313 | 1 |
unit/either_spec.py | tek/amino | 33 | 23457 | import operator
from amino.either import Left, Right
from amino import Empty, Just, Maybe, List, Either, _
from amino.test.spec_spec import Spec
from amino.list import Lists
class EitherSpec(Spec):
def map(self) -> None:
a = 'a'
b = 'b'
Right(a).map(_ + b).value.should.equal(a + b)
... | 2.71875 | 3 |
Modulo_1/semana2/variables_contantes/sentencia-global.py | rubens233/cocid_python | 0 | 23458 | variable1 = "variable original"
def variable_global():
global variable1
variable1 = "variable global modificada"
print(variable1)
#variable original
variable_global()
print(variable1)
#variable global modificada
| 3.296875 | 3 |
weather_alarm/main.py | Cs4r/weather_alarm | 0 | 23459 | <filename>weather_alarm/main.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from weather_alarm.constants import *
from weather_alarm.forecaster import Forecaster
from weather_alarm.sender import NotificationSender
sender = Not... | 2.671875 | 3 |
authlib/oauth2/rfc6749/__init__.py | geoffwhittington/authlib | 0 | 23460 | # -*- coding: utf-8 -*-
"""
authlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~
This module represents a direct implementation of
The OAuth 2.0 Authorization Framework.
https://tools.ietf.org/html/rfc6749
"""
from .wrappers import OAuth2Request, OAuth2Token, HttpRequest
from .errors import (
OAuth2... | 1.921875 | 2 |
scripts/serial_command.py | philip-long/singletact-python-wrapper | 0 | 23461 | <filename>scripts/serial_command.py
TIMEOUT=100
def GenerateWriteCommand(i2cAddress, ID, writeLocation, data):
i = 0
TIMEOUT = 100
command = bytearray(len(data)+15)
while (i < 4):
command[i] = 255
i += 1
command[4] = i2cAddress
command[5] = TIMEOUT
command[6] = ... | 2.6875 | 3 |
1SiteRanking/create_kernel_density_map_arcpy.py | HCH2CHO/EmotionMap | 3 | 23462 | # coding:utf-8
# version:python2.7.3
# author:kyh
# import x,y data from txt and create kernel density map
import arcpy
from arcpy.sa import *
from arcpy import env
def read_point_data(filepath,i):
# Read data file and create shp file
with open(filepath, 'r') as pt_file:
pt=arcpy.Point()
ptGeo... | 2.765625 | 3 |
src/explore.py | dngo13/enpm808x_inspection_robot | 0 | 23463 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""*******************************************************************************
* MIT License
* Copyright (c) <NAME> 2021
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the... | 1.195313 | 1 |
mapclientplugins/loadcsvstep/utils/processCSV.py | mahyar-osn/mapclientplugins.loadcsvstep | 0 | 23464 | import pandas as pd
class ProcessCSV:
"""
A general class to read in and process a csv format file using pandas.
"""
def __init__(self, filename, delim=',', header=None, usecols=None, dtype=None, ignore=False, *args):
self._filename = filename
self._args = args
self._df = self.... | 3.625 | 4 |
src/api/handlers/projects/tokens.py | sap-steffen/InfraBox | 50 | 23465 | <filename>src/api/handlers/projects/tokens.py<gh_stars>10-100
from flask import request, g, abort
from flask_restplus import Resource, fields
from pyinfrabox.utils import validate_uuid4
from pyinfraboxutils.ibflask import auth_required, OK
from pyinfraboxutils.ibrestplus import api
from pyinfraboxutils.token import en... | 2.375 | 2 |
tigergraph/benchmark.py | yczhang1017/ldbc_snb_bi | 0 | 23466 | <gh_stars>0
import argparse
from pathlib import Path
from datetime import datetime, date, timedelta
from queries import run_queries, precompute, cleanup
from batches import run_batch_update
import os
import time
import re
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='LDBC TigerGraph BI w... | 2.1875 | 2 |
wgan/updater.py | Aixile/chainer-gan-experiments | 70 | 23467 | <filename>wgan/updater.py
import numpy as np
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import cuda, optimizers, serializers, Variable
import sys
sys.path.insert(0, '../')
from common.loss_functions import *
class Updater(chainer.training.StandardUpdater):
def __init__(sel... | 2.203125 | 2 |
tools/ig/definitions.py | grahamegrieve/vocab-poc | 2 | 23468 | <reponame>grahamegrieve/vocab-poc<gh_stars>1-10
#! /usr/bin/env python3.
# create ig definition file with all value sets in the /resources directory
import json, os, sys, logging, re, csv
from lxml import etree
#logging.disable(logging.CRITICAL)
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelna... | 2.015625 | 2 |
src/sadie/renumbering/clients/g3.py | jwillis0720/pybody | 0 | 23469 | from functools import lru_cache
from itertools import product
from pathlib import Path
from typing import Optional, List, Tuple
from pydantic import validate_arguments
import pyhmmer
import requests as r
from yarl import URL
from sadie.typing import Species, Chain, Source
class G3:
"""API Wrapper with OpenAPI f... | 2.4375 | 2 |
projects/shadow/kmap-builder-jython27/MapReduce/mappers/__init__.py | zaqwes8811/smart-vocabulary-cards | 0 | 23470 | # coding: utf-8
from nlp_components.content_items_processors import process_list_content_sentences
from nlp_components.content_items_processors import process_list_content_sentences_real
import dals.os_io.io_wrapper as dal
import json
# NO DRY!!
def read_utf_txt_file(fname):
sets = dal.get_utf8_template()
se... | 2.484375 | 2 |
config.py | xXAligatorXx/repostAlert | 25 | 23471 | import os
client_id = os.environ['BOT_CLIENT_ID']
client_secret = os.environ['BOT_CLIENT_SECRET']
user_agent = os.environ['BOT_USER_AGENT']
username = os.environ['BOT_USERNAME']
password = os.environ['BOT_PASSWORD']
num_subs = int(os.environ['BOT_SUB_COUNT'])
sub_settings = [[
os.environ['BOT_SUBREDDIT' + i],
... | 2.140625 | 2 |
lib/aquilon/worker/formats/list.py | ned21/aquilon | 7 | 23472 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... | 2.328125 | 2 |
satyrus/sat/types/string.py | lucasvg/Satyrus3-FinalProject-EspTopsOTM | 0 | 23473 | from .main import SatType
class String(SatType, str):
def __new__(cls, *args, **kwargs):
return str.__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
SatType.__init__(self) | 2.984375 | 3 |
setup.py | ZeroCater/zerocaterpy | 0 | 23474 | <reponame>ZeroCater/zerocaterpy
from setuptools import setup
setup(name='zerocater',
version='0.0.1',
description="Python interface to ZeroCater",
long_description='',
keywords='zerocater food delivery meal planning catering lunch',
author='ZeroCater',
author_email='<EMAIL>',
... | 1.34375 | 1 |
tests/conftest.py | scottmanderson/minerva | 0 | 23475 | <reponame>scottmanderson/minerva
import pytest
from app import create_app, db
from config import TestConfig
@pytest.fixture
def test_client():
flask_app = create_app(TestConfig)
with flask_app.test_client() as testing_client:
with flask_app.app_context():
yield testing_client
@pytest.fi... | 2.078125 | 2 |
Test/two/payments/momo/urls.py | titan256/Python-Django-Assignment | 0 | 23476 | <reponame>titan256/Python-Django-Assignment<filename>Test/two/payments/momo/urls.py
from django.contrib import admin
from django.urls import path , include
from . import views
urlpatterns = [
path('',views.index,name='index')
] | 1.851563 | 2 |
pdsensorvis/sensors/models.py | mickeykkim/masters-project-sphere | 2 | 23477 | from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.utils import timezone
import uuid
ANNOTATION = (
('asm', 'Asymmetry'),
('dst', 'Dystonia'),
('dsk', 'Dyskensia'),
('ebt', 'En Bloc Turning'),
('str', 'Short Stride Length'),
('mo... | 2.1875 | 2 |
setup.py | soumyarani/mopac | 20 | 23478 | <gh_stars>10-100
from distutils.core import setup
from setuptools import find_packages
setup(
name='mopac',
packages=find_packages(),
version='0.1',
description='Model-based policy optimization',
long_description=open('./README.md').read(),
author='',
author_email='',
url='',
entry_... | 1.265625 | 1 |
examples/imu.py | dan-stone/canal | 2 | 23479 | import datetime
import canal
from influxdb import InfluxDBClient
class IMU(canal.Measurement):
accelerometer_x = canal.IntegerField()
accelerometer_y = canal.IntegerField()
accelerometer_z = canal.IntegerField()
gyroscope_x = canal.IntegerField()
gyroscope_y = canal.IntegerField()
gyroscope_z... | 2.5625 | 3 |
lib/ravstack/runtime.py | geertj/raviron | 1 | 23480 | #
# This file is part of ravstack. Ravstack is free software available under
# the terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2015 the ravstack authors. See the file "AUTHORS" for a
# complete list.
from __future__ impo... | 1.789063 | 2 |
onetouch.py | kakoni/insulaudit | 1 | 23481 | #!/usr/bin/python
import user
import serial
from pprint import pprint, pformat
import insulaudit
from insulaudit.data import glucose
from insulaudit.log import io
from insulaudit.devices import onetouch2
import sys
PORT = '/dev/ttyUSB0'
def get_serial( port, timeout=2 ):
return serial.Serial( port, timeout=timeou... | 2.6875 | 3 |
src/graphdb_builder/databases/parsers/smpdbParser.py | hhefzi/CKG | 0 | 23482 | import os.path
import zipfile
import pandas as pd
from collections import defaultdict
from graphdb_builder import builder_utils
#########################
# SMPDB database #
#########################
def parser(databases_directory, download=True):
config = builder_utils.get_config(config_name="smpdbConfig.ym... | 2.5625 | 3 |
server/waitFramerate.py | mboerwinkle/RingGame | 0 | 23483 | import time
#Timing stuff
lastTime = None
prevFrameTime = 0;
def waitFramerate(T): #TODO if we have enough time, call the garbage collector
global lastTime, prevFrameTime
ctime = time.monotonic()
if lastTime:
frameTime = ctime-lastTime #how long the last frame took
sleepTime = T-frameTime #how much time is rem... | 3.421875 | 3 |
shellbot/spaces/local.py | bernard357/shellbot | 11 | 23484 | <reponame>bernard357/shellbot
# -*- 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 L... | 2.234375 | 2 |
src/warp/yul/AstTools.py | sambarnes/warp | 414 | 23485 | from __future__ import annotations
import re
from typing import Union
import warp.yul.ast as ast
from warp.yul.AstVisitor import AstVisitor
from warp.yul.WarpException import WarpException
class AstParser:
def __init__(self, text: str):
self.lines = text.splitlines()
if len(self.lines) == 0:
... | 2.65625 | 3 |
srfnef/tools/doc_gen/doc_generator.py | twj2417/srf | 0 | 23486 | # encoding: utf-8
'''
@author: <NAME>
@contact: <EMAIL>
@software: basenef
@file: doc_generator.py
@date: 4/13/2019
@desc:
'''
import os
import sys
import time
from getpass import getuser
import matplotlib
import numpy as np
import json
from srfnef import Image, MlemFull
matplotlib.use('Agg')
author = getuser()
de... | 2.375 | 2 |
prep_scripts/0_join_data.py | linas-p/EVDPEP | 5 | 23487 | <reponame>linas-p/EVDPEP
import pandas as pd
import numpy as np
DATA_PATH = "./data/EVconsumption/"
weather = pd.read_csv(DATA_PATH + "dimweathermeasure.csv", sep = "|")
osm = pd.read_csv(DATA_PATH + "osm_dk_20140101.csv", sep = "|")
data0 = pd.read_csv(DATA_PATH + "2020_11_25_aal_viterbi.csv", sep = ",")
data1 = pd.... | 2.453125 | 2 |
csuibot/utils/kbbi.py | chadmadna/CSUIBot | 0 | 23488 | import requests
import json
class WordDefinition:
def __init__(self, word):
self.word = word
self.definisi = None
self.json_data = None
def url_data(self):
api_url = 'http://kateglo.com/api.php'
r = requests.get(api_url, params={
'format': 'json', 'phrase'... | 3.25 | 3 |
networking_vsphere/tests/unit/agent/test_ovsvapp_agent.py | Mirantis/vmware-dvs | 8 | 23489 | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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/LIC... | 1.328125 | 1 |
yolov3/utils/__init__.py | hysts/pytorch_yolov3 | 13 | 23490 | from yolov3.utils import data
| 0.988281 | 1 |
pootlestuff/watchables.py | pootle/pootles_utils | 0 | 23491 | """
This module provides classes that support observers, smart value handling and debug functions
All changes to values nominate an agent, and observers nominate the agent making changes they
are interested in.
It supercedes the pvars module
"""
import logging, sys, threading, pathlib, math, json
from enum import Enu... | 2.484375 | 2 |
tests/test_codecs.py | reece/et | 0 | 23492 | import et.codecs
tests = [
{
"data": 0,
"e_data": {
1: b'\x00\x010',
2: b'\x00\x02x\x9c3\x00\x00\x001\x001'
}
},
{
"data": {},
"e_data": {
1: b'\x00\x01{}',
2: b'\x00\x02x\x9c\xab\xae\x05\x00\x01u\x00\xf9'
}
... | 2.390625 | 2 |
tests/test_sa.py | mariushelf/sa2django | 0 | 23493 | import sqlite3
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import tests.testsite.testapp.models as dm
from tests.sa_models import Base, Car, Child, Dog, Parent
@pytest.fixture(scope="session")
def engine():
print("NEW ENGINE")
engine = create_engine(
"s... | 2.453125 | 2 |
src/github4/session.py | staticdev/github3.py | 0 | 23494 | """Module containing session and auth logic."""
import collections.abc as abc_collections
import datetime
from contextlib import contextmanager
from logging import getLogger
import dateutil.parser
import requests
from . import __version__
from . import exceptions as exc
__url_cache__ = {}
__logs__ = getLogger(__pac... | 3.140625 | 3 |
models/ffn_ace.py | MilesQLi/Theano-Lights | 313 | 23495 | import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
from theano.tensor.nnet.conv import conv2d
from theano.tensor.signal.downsample import max_pool_2d
from theano.tensor.shared_randomstreams import RandomStreams
import numpy as np
from toolbox import *
from modelbase import *
... | 2.140625 | 2 |
src/misc/helpers.py | dnmarkon/kaggle_elo_merchant | 0 | 23496 | <reponame>dnmarkon/kaggle_elo_merchant
import pandas as pd
def one_hot(df, column):
df = pd.concat([df, pd.get_dummies(df[column], prefix=column)], axis=1)
df.drop([column], axis=1, inplace=True)
return df
| 2.875 | 3 |
1306_Jump_Game_III.py | imguozr/LC-Solutions | 0 | 23497 | from typing import List
class Solution:
"""
BFS
"""
def canReach_1(self, arr: List[int], start: int) -> bool:
"""
Recursively.
"""
seen = set()
def helper(pos):
if not 0 <= pos < len(arr) or pos in seen:
return False
... | 3.671875 | 4 |
Extensions/BabaGUI/config.py | siva-msft/baba-is-auto | 108 | 23498 | import pygame
FPS = 60
BLOCK_SIZE = 48
COLOR_BACKGROUND = pygame.Color(0, 0, 0)
| 2.140625 | 2 |
simulation/strategies/bucketing.py | kantai/hyperbolic-caching | 15 | 23499 | class AveragingBucketUpkeep:
def __init__(self):
self.numer = 0.0
self.denom = 0
def add_cost(self, cost):
self.numer += cost
self.denom += 1
return self.numer / self.denom
def rem_cost(self, cost):
self.numer -= cost
self.denom -= 1
if self.... | 3.140625 | 3 |