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 |
|---|---|---|---|---|---|---|
import data/insert_metadata.py | elenisproject/internet-and-applications | 2 | 12766851 | #------------------------------------------ EXTRACT DATA FROM METADATA.CSV -------------------------------------------------
#
# our table has the same structrure as the csv file downloaded
#
#
#---------------------------------------------------------------------------------------... | 2.609375 | 3 |
scripts/omtools/om/devices/hca.py | sifive/testenv-metal | 1 | 12766852 | from typing import Dict, Union
from ..generator import OMSifiveSisHeaderGenerator
from .. import pprint
class OMSifiveSisHcaHeaderGenerator(OMSifiveSisHeaderGenerator):
"""SiFive SIS header generator for HCA crypto engine.
"""
def _generate_definitions(self, devname: str,
features: Dict[str, ... | 2.546875 | 3 |
porcupine/plugins/run/common.py | Akuli/editor | 1 | 12766853 | from __future__ import annotations
import dataclasses
import os
from pathlib import Path
from typing import Dict, List, Optional
from porcupine import tabs, utils
@dataclasses.dataclass
class Command:
command_format: str
cwd_format: str
external_terminal: bool
substitutions: Dict[str, str]
def ... | 2.46875 | 2 |
utils.py | sillwood/voicemos | 2 | 12766854 | # Modified based on the HRNet repo.
from __future__ import absolute_import, division, print_function
import logging
import os
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
class FullModel(nn.Module):
"""
Distribute the loss on multi-g... | 2.734375 | 3 |
xc/common/libraries/generate_verilog.py | bl0x/symbiflow-arch-defs | 183 | 12766855 | """Transforms the XML module definitions parsed from the PDF into a verilog representation"""
from lxml import etree
from datetime import datetime
def format_port(name, width, type, **kwargs):
wstr = '' if int(width) == 1 else '[%s:0]\t' % width
return '\t%s\t%s%s;\n' % (type, wstr, name)
def format_attrib(... | 2.859375 | 3 |
slides/template.py | russellromney/dash-slides | 14 | 12766856 | <filename>slides/template.py
###
# no need to delete this - it won't show up in the presentation unless you add it to presentation.py
###
# necessary imports - do not change
from app import app
# custom imports - delete these if you don't need them
import dash_html_components as html
import dash_core_components as dc... | 2.421875 | 2 |
moment_polytopes/__init__.py | amsqi/moment_polytopes | 2 | 12766857 | <reponame>amsqi/moment_polytopes
from __future__ import absolute_import, print_function
#:Current version.
__version__ = "1.2.dev0"
from .polyhedron import *
from .lie_group import *
from .ressayre import *
from .combinat import *
from . import qmp
from . import third_party
| 0.894531 | 1 |
done/12.py | eNV25/euler | 0 | 12766858 | <gh_stars>0
import sys
def factors(n):
'''Generator of factors.'''
n = int(n)
for i in range(1, int(n**0.5) +1):
if not n % i: # if n is multiple of i
yield i
for i in reversed(range(1, int(n**0.5) +1)):
if not n % i:
yield n//i
def lenfactors(n):
'''Gene... | 3.546875 | 4 |
tm4/colourTools.py | zhubonan/tm4 | 1 | 12766859 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 10:40:39 2016
Converting reflectance spectrum to a CIE coordinate
@author: Bonan
"""
import numpy as np
from scipy import interpolate
import os
# Adobe RGB (1998) D65 as reference white
# http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_RGB.html
_RGB_to_XYZ = np.arra... | 2.6875 | 3 |
bot/settings/base.py | hqrrylyu/ob-eshop-telegram-bot | 0 | 12766860 | from pathlib import Path
from typing import Dict
from environs import Env
from furl import furl
from .utils import FilterSettings
env = Env()
DEBUG = False
BASE_DIR = Path(__file__).parent.parent
LOCALES_DIR = BASE_DIR / "locales"
I18N_DOMAIN = "messages"
BOT_TOKEN = env("BOT_TOKEN")
ADMINS = env.list("ADMINS"... | 2 | 2 |
17-exercises/02-lista/regex.py | deniscostadsc/regex-tutorial | 4 | 12766861 | '''
Nesse exer você deve casar linha que tenham 'b' ou 'c' seguido de uma vogal,
duas vezes seguidas.
exemplo: "baba", "caca", ou "cabo"
Para fixação, usar o '[]' (lista).
'''
import re
import sys
REGEX = r''
lines = sys.stdin.readlines()
for line in lines:
if re.search(REGEX, line):
print(line.replace... | 3.453125 | 3 |
dataloader.py | husnejahan/DeepAR-Pytorch | 213 | 12766862 | <gh_stars>100-1000
from __future__ import division
import numpy as np
import torch
import os
import logging
from torch.utils.data import DataLoader, Dataset, Sampler
logger = logging.getLogger('DeepAR.Data')
class TrainDataset(Dataset):
def __init__(self, data_path, data_name, num_class):
self.data = np.l... | 2.484375 | 2 |
tests/utils/test_utils_create_match.py | battleforcastile/battleforcastile | 0 | 12766863 | <filename>tests/utils/test_utils_create_match.py
import json
import os
from unittest.mock import patch
from battleforcastile.constants import BATTLEFORCASTILE_BACKEND_URL
from battleforcastile.utils.create_match import create_match
CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
@patch('battleforcastile.... | 2.734375 | 3 |
_testing/upython/app_echo.py | kevinkk525/micropython_iot_generic | 0 | 12766864 | <reponame>kevinkk525/micropython_iot_generic
# Author: <NAME>
# Copyright <NAME> 2019 Released under the MIT license
# Created on 2019-01-02
__updated__ = "2019-01-02"
__version__ = "0.0"
from client.apphandler import get_apphandler, TimeoutError
from client.app_template import App, AppTemporary
import uasyncio as a... | 2.84375 | 3 |
source/xiaopeip/read.py | xuyu92327/waveform-analysis | 7 | 12766865 | import h5py
import tables
import numpy as np
import sys
args=int(sys.argv[1])
# Read hdf5 file
h5file = tables.open_file(f"./data/atraining-{args}.h5", "r")
WaveformTable = h5file.root.Waveform
GroundTruthTable = h5file.root.GroundTruth
sinevet,sinchan,sintime=[],[],[]
#根据groundtruth找出只有单光子的事例
i=1
while i <100000:
... | 2.015625 | 2 |
DataAnalysis/__init__.py | AdamSwenson/TwitterProject | 0 | 12766866 | <reponame>AdamSwenson/TwitterProject
__author__ = 'adam'
import environment
| 1.085938 | 1 |
scripts/PIRSensor.py | sradevski/HomeAutomate | 0 | 12766867 | <reponame>sradevski/HomeAutomate<gh_stars>0
import RPi.GPIO as GPIO
import time
import come_home
import radio_lights
import remote_core as core
sensor = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
#Denotes when to start checking if the kitchen lights should be turned on or not.
turn_on_hour ... | 2.671875 | 3 |
scripts/deploy.py | mikaelaakko/vesting-contracts | 1 | 12766868 | from brownie import LinearVesting, Contract
from scripts.helper_functions import get_account
custom_token_address = "0x61c2984d0D60e8C498bdEE6dbE4A4E83E53ecfE8"
amount = 1000000 * 10 ** 18
def deploy():
account = get_account()
publish_source = True
vesting = LinearVesting.deploy(
custom_token_add... | 2.421875 | 2 |
tests/test_dataset_reader.py | ReyRiordan/GoEmotions-pytorch | 0 | 12766869 | from classifier.dataset_readers.dataset_reader import ClassificationTsvReader
from classifier.dataset_readers.dataset_reader_pt import ClassificationPtTsvReader
from allennlp.common.util import ensure_list
def test_rey_reader_1(project_root_dir_path, test_fixtures_dir_path, test_log):
data_file_path = test_fixtur... | 2.328125 | 2 |
app/run.py | es-g/disaster_response | 0 | 12766870 | <reponame>es-g/disaster_response
import gzip
import json
import os
import pickle
import plotly
import pandas as pd
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from flask import Flask
from flask import render_template, request
from plotly.graph_objs import Bar
from sqlalchemy impor... | 2.671875 | 3 |
llvm_tools/custom_script_example.py | TinkerBoard-Android/external-toolchain-utils | 0 | 12766871 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A custom script example that utilizes the .JSON contents of the tryjob."""
from __future__ import print... | 2.09375 | 2 |
app/routes/error.py | Chartes-TNAH/CollectArt | 0 | 12766872 | from flask import render_template, url_for
# importation de render_template (pour relier les templates aux routes) et d'url_for (pour construire des URL vers les
# fonctions et les pages html)
from ..app import app
# importation de la variable app qui instancie l'application
# | ROUTES POUR LES ERREURS COURANTES |
@... | 2.984375 | 3 |
app.py | KristoferLintonReid/hex_cam | 0 | 12766873 | <gh_stars>0
from flask import Flask, request, jsonify
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_rep... | 2.296875 | 2 |
src/emmental/scorer.py | vishalbelsare/emmental | 75 | 12766874 | <gh_stars>10-100
"""Emmental scorer."""
import logging
from functools import partial
from typing import Callable, Dict, List, Union
from numpy import ndarray
from emmental.metrics import METRICS
from emmental.utils.utils import array_to_numpy
logger = logging.getLogger(__name__)
class Scorer(object):
"""A clas... | 2.515625 | 3 |
Curso de Python Youtube/Aula15-Operacao-ternaria/Aula15-Operacao-ternaria.py | Rafael-Inacio/CursoPython | 0 | 12766875 |
looged_user = False
# if looged_user:
# msg = 'Usuário logado.'
# else:
# msg = 'Usuário não está logado.'
msg = 'Usuário logado' if looged_user else 'Usuário não está logado.'
print(msg)
| 2.5 | 2 |
vedro_pyppeteer/_screenshot_path.py | nikitanovosibirsk/vedro-pyppeteer | 0 | 12766876 | from pathlib import Path
from typing import Union
__all__ = ("ScreenshotPath",)
class ScreenshotPath:
def __init__(self, dir_: Path) -> None:
self.dir = dir_
self.rerun: Union[int, None] = None
self.timestamp: Union[int, None] = None
self.scenario_path: Union[Path, None] = None
... | 2.453125 | 2 |
python/GravaCnpj.py | mozarthasse/cnpjs | 0 | 12766877 | <reponame>mozarthasse/cnpjs
import psycopg2
from FilaDeLinhas import FilaDeLinhas
def GravacaoPgCopy(origem : FilaDeLinhas, tabela : str):
cond = psycopg2.connect(host='postgres-compose', dbname="postgres", user="postgres", password="<PASSWORD>")
curd = cond.cursor()
curd.copy_from(origem,tabela,sep=';',null='')... | 2.28125 | 2 |
app/api/serializers/post.py | parkgeonhu/drf-boilerplate | 1 | 12766878 | from app.models import *
from rest_framework import serializers
from .user import *
class PostSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True)
def create(self, validated_data):
return Post.objects.create(**validated_data)
class Meta:
model = Post... | 2.171875 | 2 |
main.py | Rhoana/soma_segmentation | 0 | 12766879 | import tensorflow as tf
import dataIO
import numpy as np
from datetime import datetime
from model import model
from parameters import *
# preprocess input data
def prepareDataTraining(seg_data, somae_data_raw):
somae_data = seg_data.copy()
somae_data[somae_data_raw==0]=0
seg_data = seg_data[:,:network_si... | 2.296875 | 2 |
utils/metrics.py | chansoopark98/CSNet-SOD | 0 | 12766880 | import tensorflow as tf
# class MeanIOU(tf.keras.metrics.MeanIoU):
# def update_state(self, y_true, y_pred, sample_weight=None):
# # y_true = tf.squeeze(y_true, -1)
# y_pred = tf.nn.softmax(y_pred)
# y_true = tf.argmax(y_true, axis=-1)
#
# return super().update_state(y_true, y_pred,... | 2.453125 | 2 |
test/integration/test_scopes.py | BBVA/MIST | 13 | 12766881 | import os
import platform
import pytest
from mist.action_run import execute_from_text
CHECK_FILE = "scopes.mist"
@pytest.mark.asyncio
async def test_check_if_bool_functions(examples_path):
with open(os.path.join(examples_path, CHECK_FILE), "r") as f:
content = f.read()
output = await execute_from_te... | 2.171875 | 2 |
Python/simple_array_sum.py | AntonioMM8506/HackerRank | 0 | 12766882 | <gh_stars>0
#!/bin/python
from __future__ import print_function
import os
import sys
#@param recieves a map as an argument
#@return the sum of all the numbers inside the map.
def simpleArraySum(ar):
ar_1 = list(ar)
total = 0
for i in ar_1:
total += i
return total
#End of simpleArraySum
... | 3.53125 | 4 |
tests/test_c_data_model/test_array.py | mrh1997/headlock | 2 | 12766883 | import pytest
from unittest.mock import patch
import headlock.c_data_model as cdm
from headlock.address_space.virtual import VirtualAddressSpace
@pytest.fixture
def carray_type(cint_type, addrspace):
return cdm.CArrayType(cint_type, 10, addrspace)
class TestCArrayType:
def test_init_returnsArrayCProxy(se... | 2.203125 | 2 |
gltf/__init__.py | An2op/3dTileConverter | 0 | 12766884 | from .gltf import Glb
from .slicer import Slicer
from .element import Element
| 1.03125 | 1 |
opts.py | ricbl/vrgan | 9 | 12766885 | <reponame>ricbl/vrgan<gh_stars>1-10
"""User configuration file
File organizing all configurations that may be set by user when running the
train.py script.
Call "python train.py for a complete and formatted list of available user options.
"""
import argparse
import time
from random import randint
def st... | 2.453125 | 2 |
botovod/agents/types.py | OlegYurchik/botovod | 7 | 12766886 | from __future__ import annotations
from typing import Iterator, Optional
class Entity:
def __init__(self, **raw):
self.raw = raw
def __getattr__(self, item):
if item in self.raw:
return self.raw[item]
return super().__getattribute__(item)
class Chat(Entity):
def __in... | 2.5 | 2 |
Day 6/Ex1: Hurdles Loop 1 Challenge.py | Nishi-16-K/100DaysCodeChallenge-Python- | 1 | 12766887 | #Reeborg's World Hurdle 1 Loop Challenge using for loop
def turn_right():
turn_left()
turn_left()
turn_left()
def step():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
for in in range(0,5):
step()
| 3.703125 | 4 |
bfassist/colours/rgbcolours.py | SanHime/bfassist | 1 | 12766888 | #############################################################################
#
#
# RGB/A Colour webGenFramework module to BFA c7
#
#
#############################################################################
""" This is a rgb/a colour module for bfa colours.
Dependencies:
None
note:: Author(s): Mi... | 2.546875 | 3 |
NCMusicAPI/logindb.py | ch4r04/NCMusicAPI-py | 0 | 12766889 | <reponame>ch4r04/NCMusicAPI-py
# -*- coding:utf-8 -*-
"""
@author: ‘ch4r0n‘
@contact: <EMAIL>
@site:
@software: PyCharm
@file: logindb.py
@time: 2018/10/8 上午12:00
"""
from pony.orm import *
from .const import Constant
import os
db = Database()
db.bind(provider='sqlite', filename=os.path.join(Constant.conf_dir, "ncmus... | 2.1875 | 2 |
setup.py | aaront/backcheck | 0 | 12766890 | <reponame>aaront/backcheck
# -*- coding: utf-8 -*-
import re
import ast
from setuptools import setup, find_packages
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('backcheck/__init__.py', 'rb') as f:
version = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
se... | 1.632813 | 2 |
decomp.py | MelyPic/labgaif | 0 | 12766891 | '''
Handle transactional file via github's labgaif/td2dot.py
Similar to integration tests inside maindecomposition but
trying them "from outside file".
Yesterday I got some strange error in the union/find str
but I cannot reproduce it anymore :(
It read:
if x.parent == x:
AttributeError: 'str' object has no attribu... | 2.234375 | 2 |
djauth/bin/ldap_modify.py | carthagecollege/django-djauth | 0 | 12766892 | <filename>djauth/bin/ldap_modify.py
# -*- coding: utf-8 -*-
"""
Shell script to search LDAP store by username or ID
"""
from django.conf import settings
from djauth.LDAPManager import LDAPManager
import sys
import hashlib, base64
import argparse
import ldap.modlist as modlist
import ldap
# set up command-line option... | 3.171875 | 3 |
KFold_ACC.py | wzhlearning/fNIRS-Transformer | 0 | 12766893 | import numpy as np
# Select dataset
dataset = ['A', 'B', 'C']
dataset_id = 0
print(dataset[dataset_id])
# Select model
models = ['fNIRS-T', 'fNIRS-PreT']
models_id = 0
print(models[models_id])
test_acc = []
for tr in range(1, 26):
path = 'save/' + dataset[dataset_id] + '/KFold/' + models[models_id] + '/' + str(... | 2.734375 | 3 |
shopping_cart/models.py | devsingh-code/django-digital-marketplace | 1 | 12766894 | <gh_stars>1-10
from django.db import models
from django.conf import settings
from books.models import Book
from django.db.models import Sum
# Create your models here.
class OrderItem(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
def __str__(self):
return self.book.title
cla... | 2.375 | 2 |
master/testdata/var/db/baetyl/cmd/bin/cmd.py | winnerineast/openedge | 2 | 12766895 | <reponame>winnerineast/openedge<filename>master/testdata/var/db/baetyl/cmd/bin/cmd.py
#!/usr/bin/env python
#
import time
if __name__ == '__main__':
while True:
try:
time.sleep(10)
except KeyboardInterrupt:
break
| 1.507813 | 2 |
django_mercadopago/migrations/0001_initial.py | victorpluna/django-mp | 1 | 12766896 | <filename>django_mercadopago/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Notification',
... | 1.726563 | 2 |
colossalai/engine/_base_engine.py | jiangz17THU/ColossalAI | 0 | 12766897 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from asyncio.log import logger
from typing import List
from torch.nn import Module
from torch.nn.modules.loss import _Loss
from torch.optim import Optimizer
from colossalai.logging import get_dist_logger
from torch import Tensor
from colossalai.engine.ophooks import reg... | 2.578125 | 3 |
functions/process_data.py | donglinwu6066/SDEdit | 330 | 12766898 | import torch
import os
def download_process_data(path="colab_demo"):
os.makedirs(path, exist_ok=True)
print("Downloading data")
torch.hub.download_url_to_file('https://image-editing-test-12345.s3-us-west-2.amazonaws.com/colab_examples/lsun_bedroom1.pth', os.path.join(path, 'lsun_bedroom1.pth'))
torch.... | 2.734375 | 3 |
ascent/datastore/v1/libraries/adaptors/ascent_es_adaptor.py | ahwspl/ascent-datastore | 0 | 12766899 | <reponame>ahwspl/ascent-datastore
import os
import json
import logging
import requests
import elasticsearch
import functools
from ..helpers import common_util as utils
from ..helpers.DBOperationError import DBOperationError
class AscentESAdaptor(object):
"""An adaptor to create and manage ElasticSearch, Neo4j, et... | 2.4375 | 2 |
geniepy/tests/unit/test_pcp_classifier.py | geralddzx/genie | 1 | 12766900 | <gh_stars>1-10
"""Test base classifier class."""
import pandas as pd
import geniepy.classmgmt.classifiers as clsfr
CLSFR_NAME = "pub_score"
SAMPLE_RECORD = pd.Series(["g", "e", "e", "k", "s"])
class TestClassifier:
"""Base Classifier pytest class."""
classifier = clsfr.Classifier("pub_score")
def test... | 2.859375 | 3 |
src/frequent_phrase_mining/frequent_pattern_mining.py | paperplanet/SegPhrase | 275 | 12766901 | from sets import Set
def frequentPatternMining(tokens, patternOutputFilename, threshold):
dict = {}
tokensNumber = len(tokens)
for i in xrange(tokensNumber):
token = tokens[i]
if token == '$':
continue
if token in dict:
dict[token].append(i)
else:
... | 3.0625 | 3 |
server/api.py | sideral/worney | 0 | 12766902 | import nltk
import random
import re
from flask import Flask, request
from flask_restful import Resource, Api
from gensim.models import KeyedVectors
from flask_cors import CORS
from functools import lru_cache
app = Flask(__name__)
api = Api(app)
CORS(app)
class RandomWordPair(Resource):
def get(self, degrees):
... | 2.8125 | 3 |
tools/schema.py | kmpm/py-aiogopro | 1 | 12766903 | from datetime import datetime
from collections import namedtuple
import re
from aiogopro.types import CommandType, StatusType
RESERVED_WORDS = ['type', 'class']
T1 = ' ' * 4
T2 = T1 * 2
T3 = T1 * 3
T4 = T1 * 4
SUBMODE_PREFIX = {
'resolution': 'res_',
'aspect_ratio': 'aspect_',
'fps': '... | 2.21875 | 2 |
getDomainAge/services/notification.py | ljnath/getDomainAge | 2 | 12766904 | from flask import flash
from getDomainAge.models.enums import NotificationCategory
class NotificationService:
"""
Service class for showing all kinds of notificatin in the webpage
"""
def notify_success(self, message: str) -> None:
"""
method to show success message
:param mes... | 2.765625 | 3 |
web/server/codechecker_server/migrations/report/versions/f8291ab1d6be_fix_setting_analysis_info_id_seq.py | ryankurte/codechecker | 1,601 | 12766905 | <filename>web/server/codechecker_server/migrations/report/versions/f8291ab1d6be_fix_setting_analysis_info_id_seq.py<gh_stars>1000+
"""Fix setting analysis_info_id_seq
Revision ID: f8291ab1d6be
Revises: <PASSWORD>
Create Date: 2021-07-15 16:49:05.354455
"""
# revision identifiers, used by Alembic.
revision = 'f8291ab... | 1.453125 | 1 |
pints/tests/shared.py | iamleeg/pints | 0 | 12766906 | <filename>pints/tests/shared.py
#
# Shared classes and methods for testing.
#
# This file is part of PINTS.
# Copyright (c) 2017-2018, University of Oxford.
# For licensing information, see the LICENSE file distributed with the PINTS
# software package.
#
from __future__ import absolute_import, division
from __futur... | 1.890625 | 2 |
api/modules/users/model.py | nikochiko/server | 43 | 12766907 | <reponame>nikochiko/server
from django.contrib.auth.models import User
from django.core.validators import URLValidator
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from api.modules.users.enums import PasswordVerificationModeChoice
class Profile(mode... | 2.171875 | 2 |
helpers/write_names_to_txt.py | JSC-NIIAS/TwGoA4aij2021 | 0 | 12766908 | train_imgs_path="path_to_train_images"
test_imgs_path="path_to_val/test images"
dnt_names=[]
import os
with open("dont_include_to_train.txt","r") as dnt:
for name in dnt:
dnt_names.append(name.strip("\n").strip(".json"))
dnt.close()
print(dnt_names)
with open("baseline_train.txt","w") as btr:
for fi... | 2.640625 | 3 |
hexgrid/enums.py | Notgnoshi/hexgrid | 1 | 12766909 | <reponame>Notgnoshi/hexgrid<gh_stars>1-10
from enum import Enum, auto
class HexagonType(Enum):
"""Hexagons can be either flat-topped or pointy-topped."""
POINTY = auto()
FLAT = auto()
class CoordinateSystem(Enum):
"""Describes the different coordinate systems available."""
OFFSET = auto()
OF... | 2.78125 | 3 |
DB/bdware.py | danielvicentini/distancebot | 1 | 12766910 | # -*- coding: utf-8 -*-
## Variaveis
# 21.07.2020
# DB Functions for DB writes and reports
import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('bot'))
from bdFluxQueries import TraceReport, OccupancyReport, BestDayReport, BestDay
from config import le_config
"... | 2.78125 | 3 |
solutions/reverse-bits.py | Shuailong/Leetcode | 3 | 12766911 | <reponame>Shuailong/Leetcode
#!/usr/bin/env python
# encoding: utf-8
"""
reverse-bits.py
Created by Shuailong on 2016-03-02.
https://leetcode.com/problems/reverse-bits/.
"""
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
... | 3.375 | 3 |
doxhooks/preprocessors.py | nre/Doxhooks | 1 | 12766912 | """
General-purpose and HTML lexical preprocessors.
The `preprocessors <preprocessor>`:term: accept lines of text
(`Preprocessor.insert_lines`) and files (`Preprocessor.insert_file`). A
preprocessor remembers all the input files that it opens
(`Preprocessor.input_paths`).
Preprocessor `directives <preprocessor direct... | 2.75 | 3 |
lldb/test/API/lang/swift/swiftieformatting/TestSwiftieFormatting.py | RLovelett/llvm-project | 0 | 12766913 | <gh_stars>0
# TestSwiftieFormatting.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://... | 2.03125 | 2 |
cgi-bin/serialize.py | autorouting/main | 3 | 12766914 | <gh_stars>1-10
def serializeCgiToServer(coors): #coors is a n by 2 2D array of doubles
string = ""
for i in range(0, len(coors)):
string += str(coors[i][0]) + "," + str(coors[i][1]) # add comma between x and y coor
string += ";" # add semicolon to seperate coors
string += "\n" #ending charac... | 3.078125 | 3 |
test/test_path.py | afermanian/signatory | 156 | 12766915 | <gh_stars>100-1000
# Copyright 2019 <NAME>. 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 appli... | 1.96875 | 2 |
samples/my_strategy_2.py | fredmontet/tars | 3 | 12766916 | <filename>samples/my_strategy_2.py
from tars import portfolios, traders, strategies
def func():
portfolio = portfolios.VirtualPortfolio({'ZUSD': 1000})
trader = traders.VirtualCryptoTrader(portfolio)
strategy = strategies.PredictionStrategy(trader, 'XETHZUSD', 0.2)
return strategy
| 1.820313 | 2 |
model/networks.py | FiveEyes/CycleGAN | 0 | 12766917 | import torch
import torchvision
from torch import nn
from torch import optim
from torch.nn import init
import torch.nn.functional as F
from torch.autograd import Variable
from torch import autograd
from torchvision import transforms, utils
import os
def init_weights(m):
classname = m.__class__.__nam... | 2.59375 | 3 |
src/cv_evaluate_climate_metrics.py | joAschauer/evaluating_methods_for_reconstructing_large_gaps_in_historic_snow_depth_time_series | 0 | 12766918 | <reponame>joAschauer/evaluating_methods_for_reconstructing_large_gaps_in_historic_snow_depth_time_series<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 15:27:51 2021
@author: aschauer
"""
import os
import logging
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as pl... | 2.15625 | 2 |
member_manager/apps.py | 4sfc/django-member-manager | 0 | 12766919 | '''MemberManagerConfig class'''
from django.apps import AppConfig
class MemberManagerConfig(AppConfig):
'''MemberMangerConfig sets up the MemberManager app'''
name = 'member_manager'
verbose_name = 'Member Manager'
| 1.703125 | 2 |
Project - Open Spaces - Script.py | mckenzie-h/EMG722-OpenSpace | 0 | 12766920 | <filename>Project - Open Spaces - Script.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#Importing required libaries for code to run
get_ipython().run_line_magic('matplotlib', 'notebook')
import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt
from cartopy.feature import ShapelyFeature
impor... | 3.203125 | 3 |
setup.py | GuoJing/c3po-grpc-gateway | 1 | 12766921 | <filename>setup.py
from c3po import __version__
from setuptools import setup, find_packages
setup(
name='c3po',
version=__version__,
description='A light weight Python gRPC transport layer gateway with tornado named c3po.',
author='GuoJing',
author_email='<EMAIL>',
license='MIT',
url='https... | 1.195313 | 1 |
wifi_attendance/views.py | elvinzeng/wifi-attendance | 14 | 12766922 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.db.models.aggregates import Min, Max
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
import qrcode
from cStringIO import StringIO
import uuid
from mobile_scanner.models import Online... | 2.15625 | 2 |
CommandRecognition/model.py | c-z-h123/https-github.com-Ryuk17-SpeechAlgorithms | 338 | 12766923 | <reponame>c-z-h123/https-github.com-Ryuk17-SpeechAlgorithms<filename>CommandRecognition/model.py
"""
@FileName: model.py
@Description: Implement model
@Author: Ryuk
@CreateDate: 2020/05/12
@LastEditTime: 2020/05/12
@LastEditors: Please set LastEditors
@Version: v0.1
"""
import torch
import torch.nn as nn
i... | 2.765625 | 3 |
reports/srp/code/symbol_classifier_test.py | klawr/deepmech | 1 | 12766924 | from os.path import join
import cv2
import numpy as np
from numpy.random import uniform
from sys import exit
import tensorflow as tf
model_path = join('models', 'symbol_classifier', 'model.h5')
model = tf.keras.models.load_model(model_path)
path = join('data', 'raw', 'n', '1.jpeg')
image_name = "data"
drawing = Fal... | 2.453125 | 2 |
check.py | psorus/xtech | 0 | 12766925 | import numpy as np
import os
import os.path
from rechtschreib import correct
folder="../../write/data/"
def fixstring(qq,bef=None):
# print("fixing",qq)
intags=False
inhash=False
ac=""
ret=""
stopat=[".","(",")",">","\n"]
lq=len(qq)
for ii,zw in enumerate(qq):
basei=[intags,inhash]
... | 2.734375 | 3 |
tests/test_choices.py | SamSchott/travertino | 0 | 12766926 | <reponame>SamSchott/travertino
from unittest import TestCase
from unittest.mock import Mock
from travertino.colors import NAMED_COLOR, rgb
from travertino.constants import TOP, GOLDENROD, REBECCAPURPLE
from travertino.declaration import Choices, BaseStyle
class PropertyChoiceTests(TestCase):
def assert_property(... | 2.765625 | 3 |
examples/sptam/motion.py | linpeisensh/dynaslam2py | 0 | 12766927 | import numpy as np
import g2o
class MotionModel(object):
def __init__(self,
timestamp=None,
initial_position=np.zeros(3),
initial_orientation=g2o.Quaternion(),
initial_covariance=None):
self.timestamp = timestamp
self.position = initial_positi... | 2.6875 | 3 |
nonbonded/backend/database/models/targets/__init__.py | SimonBoothroyd/nonbonded | 5 | 12766928 | from nonbonded.backend.database.models.targets.targets import OptimizationTarget
__all__ = [OptimizationTarget]
| 1.070313 | 1 |
nbgrader/alembic/versions/ea281d3f1673_added_organization_table.py | kwanso-waqas/nbgrader | 0 | 12766929 | """Added organization table
Revision ID: ea281d3f1673
Revises: <KEY>
Create Date: 2021-11-04 15:04:47.282526
"""
from uuid import uuid4
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = 'ea281d3f1673'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
de... | 1.359375 | 1 |
modules/old/generators.py | jperezvisaires/tfg-intphys | 1 | 12766930 | <filename>modules/old/generators.py
import numpy as np
import h5py
from skimage.io import imread
from skimage.transform import rescale
import matplotlib.pyplot as plt
from tensorflow.keras.utils import Sequence, to_categorical
class SegmentationObjectDataGenerator(Sequence):
'Generates data for Keras fit training ... | 2.5625 | 3 |
nidm/nidm-results/test/TestProvStoreLinks.py | khelm/nidm | 14 | 12766931 | <reponame>khelm/nidm
#!/usr/bin/env python
'''Test thats link to example files on the Prov Store are up to date
@author: <NAME> <<EMAIL>>, <NAME>
@copyright: University of Warwick 2014
'''
import unittest
from nidmresults.test.test_commons import *
import logging
import re
logging.basicConfig(level=logging.DEBUG)
log... | 2.15625 | 2 |
jsonrpc/__init__.py | yosida95/python-jsonrpc | 0 | 12766932 | <reponame>yosida95/python-jsonrpc
# -*- coding: utf-8 -*-
from .client import (
Error,
ServerProxy,
)
from .transport import (
TCPSocketTransport,
UnixDomainSocketTransport,
)
__all__ = [
# .client
'Error',
'ServerProxy',
# .transport
'TCPSocketTransport',
'UnixDomainSocketTran... | 1.671875 | 2 |
third_party/universal-ctags/ctags/Units/parser-python.r/python2-arglists.d/input.py | f110/wing | 4 | 12766933 | <filename>third_party/universal-ctags/ctags/Units/parser-python.r/python2-arglists.d/input.py
#!/usr/bin/env python2
def func01():
pass
def func02(a):
pass
def func03(a, b = 2):
pass
def func04(a = 1, b = 2):
pass
def func05(*args):
pass
def func06(**kwargs):
pass
def func07(*args, **kwargs):
... | 2.609375 | 3 |
mathy_envs/envs/__init__.py | mathy/mathy_envs | 1 | 12766934 | from .binomial_distribute import BinomialDistribute
from .complex_simplify import ComplexSimplify
from .poly_combine_in_place import PolyCombineInPlace
from .poly_commute_like_terms import PolyCommuteLikeTerms
from .poly_grouping import PolyGroupLikeTerms
from .poly_haystack_like_terms import PolyHaystackLikeTerms
from... | 1.164063 | 1 |
flair/training_files/ag_news/train_ag_news.py | AshishMahendra/flair | 1 | 12766935 | <filename>flair/training_files/ag_news/train_ag_news.py
from flair.models import TARSClassifier
from flair.data import Corpus
from flair.datasets import SentenceDataset
from flair.trainers import ModelTrainer
import pickle
import time,logging
log = logging.getLogger("flair")
import argparse
train_ds=[]
test_ds=[]
def ... | 2.28125 | 2 |
measurements/migrations/0003_auto_20200707_1237.py | JakubWolak/blood_pressure_monitor | 0 | 12766936 | # Generated by Django 3.0.8 on 2020-07-07 10:37
from django.db import migrations, models
import measurements.validators
class Migration(migrations.Migration):
dependencies = [
('measurements', '0002_auto_20200706_1258'),
]
operations = [
migrations.AlterField(
model_name='me... | 1.46875 | 1 |
satori.core/satori/core/entities/Role.py | Cloud11665/satori-git | 4 | 12766937 | <reponame>Cloud11665/satori-git
# vim:ts=4:sts=4:sw=4:expandtab
import logging
from django.db import models, DatabaseError
from satori.core.dbev import Events
from satori.core.models import Entity
@ExportModel
class Role(Entity):
"""Model. Base for authorization "levels".
"""
parent_entity = models.On... | 1.898438 | 2 |
GGProject/workflow/views.py | VarenTechInternship/greeterguru | 0 | 12766938 | <reponame>VarenTechInternship/greeterguru
from django.http import Http404, HttpResponse
from rest_framework import status
from django.views.generic import View
from rest_framework.permissions import IsAdminUser, AllowAny
from django.views.generic import View
from django.shortcuts import render
from scripts import admin... | 2 | 2 |
scripts/build_aln_store.py | wharvey31/project-diploid-assembly | 0 | 12766939 | <gh_stars>0
#!/usr/bin/env python3
import os
import argparse
import pandas as pd
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument(
'--bed-folder',
'-b',
dest='bed_folder',
type=str,
)
parser.add_argument(
'--chrom-sizes',
... | 2.71875 | 3 |
tests/system/test_examples.py | McCrearyD/simple_sagemaker | 16 | 12766940 | <reponame>McCrearyD/simple_sagemaker
import logging
import os
import shutil
import subprocess
import sys
from time import time
from .compare_outputs import isAsExpected
file_path = os.path.split(__file__)[0]
examples_path = os.path.abspath(os.path.join(file_path, "..", "..", "examples"))
sys.path.append(examples_path... | 1.875 | 2 |
raspberrypi/news.py | jbrucepayne/pitoys | 0 | 12766941 | <reponame>jbrucepayne/pitoys
import sys
import subprocess
# TODO: Find and download better news source
def get_news():
return "Breaking News! Area man converts old rotary telephone to internet connected super-device!"
| 1.929688 | 2 |
custodian/lib/python3.7/site-packages/ldap3/__init__.py | farrukh90/custodian | 1 | 12766942 | <reponame>farrukh90/custodian
"""
"""
# Created on 2013.05.15
#
# Author: <NAME>
#
# Copyright 2013 - 2020 <NAME>
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Softw... | 1.4375 | 1 |
GBM/GBMSlidingwindows_V2/GBMSlidingWindows_QualityControl/RawMeanColorMap.py | joshlyman/TextureAnalysis | 1 | 12766943 |
import csv
import matplotlib.pyplot as plt
rawmeanbeforeNormFile = '/Users/yanzhexu/Desktop/Research/Sliding box GBM/MyAlgorithm_V2/GBM_SlidingWindow_TextureMap/CE_slice22_T2_ROI_Texture_Map.csv'
rawmeanafterNormFile ='/Users/yanzhexu/Desktop/Research/Sliding box GBM/MyAlgorithm_V2/addYlabel/GBM_SlidingWindow_Textur... | 2.40625 | 2 |
setup.py | mugiseyebrows/mugi-sync | 0 | 12766944 | <reponame>mugiseyebrows/mugi-sync
from setuptools import setup, find_packages
with open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
packages = find_packages(),
name = 'mugisync',
version='0.0.7',
author="<NAME>",
author_email="<EMAIL>",
url='https://github.com/... | 1.234375 | 1 |
load_assets.py | pedroivoal/Dessoft-PF | 0 | 12766945 | <reponame>pedroivoal/Dessoft-PF
def load_assets():
assets = {}
# background do jogo
assets['background'] = pygame.image.load(r'img\spacebg.jpg').convert()
assets['background']= pygame.transform.scale(assets['background'],(largura,altura))
# tela inicial
assets['tela_init'] = pygame.image... | 2.390625 | 2 |
dataset.py | seujung/KoGPT2-LoRA-summarization | 0 | 12766946 | <reponame>seujung/KoGPT2-LoRA-summarization
import os
import glob
import torch
import ast
import numpy as np
import pandas as pd
from tqdm import tqdm, trange
from torch.utils.data import Dataset, DataLoader
MASK = '<unused0>'
SUMMARY = '<unused1>'
BOS = '</s>'
EOS = '</s>'
PAD = '<pad>'
class KoGPTSummaryDataset(Dat... | 2.484375 | 2 |
1 - Algorithms/2 - Strings/Super Reduced String.py | Terence-Guan/Python.HackerRank | 88 | 12766947 | <gh_stars>10-100
from collections import deque
import re
prev, curr = "", "aaabccddd"
while prev != curr:
prev, curr = curr, re.sub("(.)\1", "", curr)
print (curr)
def reduce(s):
d = deque()
for c in s:
if d and d[-1] == c:
d.pop()
else:
d.append()
print(*d if d else "Empty String", sep="")
s... | 2.984375 | 3 |
Day4/program2.py | CAG2Mark/Advent-Of-Code-Solutions | 0 | 12766948 | count = 0
fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
hex_not = "1234567890abcdef"
ecls = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
def check_pprt(pprt):
global count
flag = True
i = 0
while flag and i < len(fields):
flag = flag and fields[i] in pprt
i = i + 1
... | 2.859375 | 3 |
helper.py | Khushmeet/char-conv-classification | 1 | 12766949 | import numpy as np
import string
import pandas as pd
from keras.preprocessing.sequence import pad_sequences
char_limit = 1014
def get_data(path):
labels = []
inputs = []
df = pd.read_csv(path, names=['one','second','third'])
df = df.drop('second', axis=1)
data = df.values
for label,text in da... | 2.84375 | 3 |
examples/state_machine_examples/global_timers/global_timer_example_pwm_loop_no_events.py | ckarageorgkaneen/pybpod-api | 1 | 12766950 | <gh_stars>1-10
% Example state matrix: 3 global timers in "loop mode" blink port 1-3 LEDs at different rates.
% The timers are triggered in the first state. Next, the state machine goes into a state
% where it waits for two events:
% 1. Port1In momentarily enters a state that stops global timer 3. Port 3 will stop blin... | 2.375 | 2 |