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 |
|---|---|---|---|---|---|---|
libspn/tests/test_partition.py | pronobis/libspn | 22 | 45500 | <reponame>pronobis/libspn
#!/usr/bin/env python3
from context import libspn as spn
from test import TestCase
import numpy as np
import random
import tensorflow as tf
def assert_list_elements_equal(list1, list2):
"""Check if lists have the same elements."""
for l1 in list1:
if l1 not in list2:
... | 2.578125 | 3 |
setup.py | Giwasawa/dcdevaluation | 0 | 45501 | <gh_stars>0
from setuptools import setup
setup(name = 'dcdevaluation',
version = '0.8.0' ,
packages = ['dcdevaluation'] ,
zip_safe = False )
| 1.015625 | 1 |
cv2.py | PiAreSquared/RFPresence | 0 | 45502 | <gh_stars>0
#Created by <NAME>
#12 September 2018
#import the necessary packages
import numpy as np
import argparse
import imutils
import cv2
#reads the images
img_rgb = cv2.imread('/home/vishal/Downloads/simpsons.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('/home/vishal/Download... | 2.765625 | 3 |
dist/snippets/maps_http_places_textsearch_incomplete_address/maps_http_places_textsearch_incomplete_address.py | Mike-Tran/openapi-specification | 37 | 45503 | # [START maps_http_places_textsearch_incomplete_address]
import requests
url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=123%20main%20street&key=YOUR_API_KEY"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
# [END maps_http... | 2.875 | 3 |
util/reporting.py | ecradock/wifihawk | 2 | 45504 | <gh_stars>1-10
class Reporting(object):
def __init__(self, verbose=False, debug=False):
self.verbose_flag = verbose
self.debug_flag = debug
def error(self, msg):
pass
def debug(self, msg):
pass
def verbose(self, msg):
pass
| 2 | 2 |
tests/test_properties.py | Kapiche/gcloud-python-orm | 1 | 45505 | import six
import unittest2
from gcloud.datastore import helpers, key, set_default_dataset_id
from gcloudorm import model, properties
class TestProperties(unittest2.TestCase):
_DATASET_ID = 'DATASET'
def setUp(self):
set_default_dataset_id(self._DATASET_ID)
def testBooleanProperty(self):
... | 2.71875 | 3 |
main.py | cmungall/ontology-term-usage | 2 | 45506 | # TODO: figure out how to put this in the app/ folder and still use serverless
# This line: `handler: main.handler`
# How do we specify a path here, as per uvicorn?
import os
from enum import Enum
from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI, Query
# for lambda; see https://... | 2.171875 | 2 |
migrations/versions/0035.py | NewAcropolis/api | 1 | 45507 | <filename>migrations/versions/0035.py
"""empty message
Revision ID: 0035 add basic email template
Revises: 0034 add send_after to emails
Create Date: 2019-10-30 00:01:13.441215
"""
# revision identifiers, used by Alembic.
revision = '0035 add basic email template'
down_revision = '0034 add send_after to emails'
fro... | 1.585938 | 2 |
1/7/Project/utils/iloc.py | ZacksAmber/Udacity-Data-Structure-Algorithms | 1 | 45508 | <filename>1/7/Project/utils/iloc.py
def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
... | 3.625 | 4 |
app/services/user.py | StakeBeat/api-server | 0 | 45509 | from typing import Dict, List
import bcrypt
from app.session import SessionManager
from app.models.user import User
from app.models.validator import Validator
class UserService:
def __init__(self) -> None:
pass
def create(self, payload: Dict[str, str]) -> User:
hashed_pw = bcrypt.hashpw(payl... | 2.296875 | 2 |
txtorcon/circuit.py | kneufeld/txtorcon | 0 | 45510 | <filename>txtorcon/circuit.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement
import time
import datetime
from twisted.python.failure import Failure
from twisted.python import log
from t... | 2.234375 | 2 |
setup.py | cowanml/samplemangler | 0 | 45511 | # -*- encoding: utf-8 -*-
import glob
import io
import re
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
return io.open(
join(dirname(__file__), *n... | 1.992188 | 2 |
Mundo 1/ex030.py | judigunkel/judi-exercicios-python | 0 | 45512 | """
30 - Crie um programa que leia um número inteiro qualquer e mostre na tela se
ele é par ou ímpar
"""
num = int(input('\033[35mDigite um número qualquer: \033[m'))
if num % 2 == 0:
print(f'O número {num} é \033[34mPAR\033[m')
else:
print(f'O número {num} é \033[34mÍMPAR\033[m.')
| 3.96875 | 4 |
scripts/pastry.py | arthurwpessoa/machine_learning | 2 | 45513 | <filename>scripts/pastry.py
# Required libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import datetime, re
#Reading pastry dataset
df = pd.read_csv('../datasets/coffee_shop/pastry.csv')
# Drops null values
df.dropna(inplace = True)
# Replaces column to remove sp... | 2.828125 | 3 |
pyexcel_io/writers/__init__.py | vinraspa/pyexcel-io | 52 | 45514 | """
pyexcel_io.writers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
file writers
:copyright: (c) 2014-2020 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
"""
from pyexcel_io.plugins import IOPluginInfoChainV2
IOPluginInfoChainV2(__name__).add_a_writer(
relative_plugin_cla... | 1.78125 | 2 |
Interview-Preparation/Facebook/Parenthesis-valid-parenthesis.py | shoaibur/SWE | 1 | 45515 | class Solution:
def isValid(self, s: str) -> bool:
if not s: return True
if len(s) % 2: return False
if s[0] in ']})': return False
maps = {'(':')', '{':'}', '[':']'}
stack = []
for char in s:
if char in '({[':
stack.appen... | 3.6875 | 4 |
genpac/template.py | kaixinguo360/genpac | 2,331 | 45516 | <gh_stars>1000+
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, absolute_import,
division, print_function)
from ._compat import string_types
from .util import get_resource_path, read_file
# 模板文件
# is_buildin == True时为内建模板文件,在脚本源码目录下寻找
class TemplateFile(object):
def __in... | 1.867188 | 2 |
datawinners/questionnaire/tests/test_questionnaire_builder.py | ICT4H/dcs-web | 1 | 45517 | <filename>datawinners/questionnaire/tests/test_questionnaire_builder.py
import unittest
from mock import Mock, MagicMock
from mangrove.form_model.validators import UniqueIdExistsValidator
from mangrove.utils.test_utils.database_utils import safe_define_type, uniq
from mangrove.bootstrap import initializer
from mangro... | 2.515625 | 3 |
changelog/constants.py | automation-liberation/deployment-helper | 0 | 45518 | <reponame>automation-liberation/deployment-helper
from enum import Enum
class ChangelogEntryEnum(Enum):
ADDED = 'Added'
CHANGED = 'Changed'
FIXED = 'Fixed'
REMOVED = 'Removed'
| 1.960938 | 2 |
copy_release_bin.py | AlexanderYunker1983/YBuild | 0 | 45519 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import threading
import traceback
import sys
import os
import shutil
import zipfile
from subprocess import Popen, PIPE
from re import search
from datetime import datetime
from call_helper import CallHelper
from os.path import basename
class OtherException(Exception):
... | 2.203125 | 2 |
lists/fruits.py | renataeva/python-basics | 1 | 45520 | <reponame>renataeva/python-basics
fruits = ['pineapple', 'lemon', 'pear', 'watermelon', 'tomato', 'apple']
first, second, *middle, firstlast, last = fruits
print(f'''Первый элемент: {first}
Второй: {second}
Посередине: {middle}
Предпоследний: {firstlast}
Последний: {last}''')
| 4.0625 | 4 |
turterra/utils/sequence_utility.py | BTheDragonMaster/turterra | 0 | 45521 | from collections import Counter
import typing
from pathlib import Path
import subprocess
import os
def run_muscle(guide_alignment, in_file, out_file):
command = ['muscle', '-quiet', '-profile', '-in1', guide_alignment, '-in2', in_file, '-out', out_file]
subprocess.check_call(command)
def add_sequences_to_... | 2.796875 | 3 |
full-problems/nextSparseBinaryNum.py | vikas-t/DS-Algo | 0 | 45522 | <filename>full-problems/nextSparseBinaryNum.py
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/next-sparse-binary-number/0
def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
m... | 3.859375 | 4 |
Baekjoon/Python/18108.py | KHJcode/Algorithm-study | 2 | 45523 | print(int(input()) - 543)
| 2.046875 | 2 |
week_2/invertendo_strings.py | angelitabrg/lih_lab_python2 | 0 | 45524 | '''
A função inverte strings e coloca todas as letras em maiúsculo:
'''
def fazAlgo(string):
pos = len(string)-1
string = string.upper()
while pos >= 0:
print(string[pos], end="")
pos = pos - 1
fazAlgo("amora")
| 4.25 | 4 |
py_projects_boilerplates/sphinx_loguru_pytest_boiler/app/modules/hello_world/tools/tools.py | rypaik/PYTHON | 0 | 45525 | <gh_stars>0
#from config import console, log
from config import console
from loguru import logger
import sys
#TODO: factory function to create logger
# setting up Logger
logger.add(sys.stderr, format="{time} {level} {message}", level="INFO")
logger.add("./common/loguru_log/Tools_{time}.log", rotation="500 MB")
# @log... | 2.8125 | 3 |
scripts/write_quran_pages.py | AmmarRabie/auto-combine-moshaf | 0 | 45526 | <reponame>AmmarRabie/auto-combine-moshaf
'''
Write quran pages for in each aya. creates folder quran_pages, this folder conatains 604 file equals the number of
quran pages. each file corresponds ayat in this page.
also find all beginning of each sura and ending.
'''
import xml.etree.ElementTree as ET
import os
import... | 2.9375 | 3 |
fairways/io/generic/net.py | dan-win/fairways_py | 0 | 45527 | <reponame>dan-win/fairways_py
from .base import (BaseQuery, ReaderMixin, WriterMixin)
from .serde import (serialize_json, deserialize_json)
import pickle
import urllib.parse
class HttpQueryTemplate:
# NOTE: Make more stable solution to create hash (take into account complex cases like "application/json;charset=... | 2.515625 | 3 |
perfrunner/tests/gsi.py | bochun/perfrunner | 18 | 45528 | from perfrunner.helpers.cbmonitor import timeit, with_stats
from perfrunner.tests import PerfTest
from perfrunner.workloads.kvgen import kvgen
class IndexTest(PerfTest):
COLLECTORS = {
'secondary_stats': True,
'secondary_debugstats': True,
'secondary_debugstats_bucket': True,
'sec... | 2.046875 | 2 |
Exam24-25/ChristmasGifts.py | Mirkonito/Softuni-Python-Basic | 1 | 45529 | command = input()
kids = 0
adults = 0
while command != "Christmas":
peoples_age = int(command)
if peoples_age <= 16:
kids += 1
elif peoples_age > 16:
adults += 1
command = input()
if command == "Christmas":
total_toys_price = kids * 5
total_sweater_price = adults * 15
pri... | 3.921875 | 4 |
main.py | endeesa/optimization-algorithms | 0 | 45530 | import os
import logging
import conjugatedescent
import coordinatedescent
import gradientdescent
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def _choose_operation(requested_operation: str):
if requested_operation == 'CONJUGATE_GRADIENT':
optimizer = conjugatedescent.Conjug... | 3.046875 | 3 |
wall.py | Kimeg/Raycasting-Visualization-in-3D | 0 | 45531 | <gh_stars>0
from static import *
from point import Point
class Wall:
def __init__(self, x1, y1, x2, y2, color, pg, screen):
self.p1 = Point(x1, y1)
self.p2 = Point(x2, y2)
self.color = color
self.pg = pg
self.screen = screen
return
def draw(self):
... | 3.234375 | 3 |
dll_test.py | heicj/data-structures | 0 | 45532 | import unittest
from dll import Node, DoubleLinkedList
class TestIt(unittest.TestCase):
def test_1(self):
"""make a node"""
n1 = Node('A')
self.assertEqual(n1._value, 'A')
def test_2(self):
"""make a test head is set when add first node"""
n1 = Node('A')
dl = DoubleLinkedList()
dl.append(n1)
self... | 3.5625 | 4 |
spectrassembler.py | antrec/spectrassembler | 11 | 45533 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Spectrassembler main program
@author: <NAME>
"""
from __future__ import print_function
from time import time
import sys
import argparse
from functools import partial
from multiprocessing import Pool
import numpy as np
from Bio import SeqIO
from scipy.sparse import coo... | 2.25 | 2 |
comprobo_final_project/scripts/models/robot.py | comprobo-final-project/genetic_racer | 0 | 45534 | <reponame>comprobo-final-project/genetic_racer
#!usr/bin/env python
"""
The real world robot class which has been made modular to mirror the simulation
robot class. It connects to april tags in the real world (or Gazebo) and can run
the most fit organism in the same way as done in simulation.
"""
import rospy
import ... | 2.59375 | 3 |
stab.py | disulfidebond/STAB | 0 | 45535 | <reponame>disulfidebond/STAB
#!/usr/bin/python
import sys
import time
import hashlib
import argparse
def listOfSamplesForSNP(snpList, snpPos):
resList = []
for itm in snpList:
if itm[0] == snpPos:
resList.append(itm[1])
return resList
def listOflowCovSNPSamples(calledSNPlist, lowCovLi... | 2.375 | 2 |
data_processing/ddh5_Plotting/ddH5_Fluxsweep_Plotting.py | PITT-HATLAB/data_processing | 0 | 45536 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 16:59:08 2021
@author: Hatlab_3
"""
from data_processing.ddh5_Plotting.utility_modules.FS_utility_functions import fit_fluxsweep
from data_processing.Helper_Functions import find_all_ddh5
from plottr.apps.autoplot import autoplotDDH5, script, main
import numpy as np
im... | 2.109375 | 2 |
super32assembler/assembler/assembler.py | xsjad0/Super32 | 1 | 45537 | <reponame>xsjad0/Super32
"""
Assembler Module
"""
import logging
from bitstring import Bits
REG_SIZE = 4 # bytes
class Assembler():
"""Assembler class"""
def __init__(self, architecture):
self.__delimiters = ['(', ')', ',']
self.__symboltable = {}
self.__architecture = architecture... | 2.71875 | 3 |
demo/caya/dataobj.py | sugarflower/caya | 0 | 45538 | <gh_stars>0
import json
import os
import zipfile
class DataObj:
def __init__(self, workspace="dataobj", name="default"):
self.workspace = workspace
self.name = name
self.home = self.homepath()
self.iter_pos = 0
self.read()
def keys(self):
return list(self.da... | 2.9375 | 3 |
manager/urls.py | amshula/DetectiveDragons | 5 | 45539 | """app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | 2.765625 | 3 |
kube/tools/repr.py | nearmap/kubefs | 3 | 45540 | <reponame>nearmap/kubefs<filename>kube/tools/repr.py
from typing import Optional
def disp_secret_string(input: Optional[str]) -> str:
return "SET" if input is not None else "UNSET"
def disp_secret_blob(input: Optional[str]) -> Optional[str]:
return "[%s bytes]" % len(input) if input is not None else None
| 1.890625 | 2 |
orchid_app/utils/pushbullet.py | ktheiss22/Orchids | 3 | 45541 | <filename>orchid_app/utils/pushbullet.py
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | 2.171875 | 2 |
tests/ut/datavisual/data_transform/test_data_loader.py | fapbatista/mindinsight | 216 | 45542 | # Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | 1.992188 | 2 |
data-structures/linked_list/test_linked_list.py | GeorgeCloud/data-structures-and-algorithms | 0 | 45543 | from linked_list import LinkedList
from node import Node
from mergeList import ll_merge
# import pytest
def test_linked_list_creation():
"""Validating if Linked List was Created."""
ll = LinkedList([2, 3, 4, 5])
assert Node(2).val is ll.head.val
assert isinstance(ll.head.val, int)
def test_insert_i... | 3.453125 | 3 |
skyportal/models/taxonomy.py | bparazin/skyportal | 52 | 45544 | <reponame>bparazin/skyportal
__all__ = ['Taxonomy']
import sqlalchemy as sa
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import JSONB
from baselayer.app.models import (
Base,
DBSession,
restricted,
AccessibleIfRelatedRowsAreAccessible,
CustomUserAccessControl,
)
fro... | 2.234375 | 2 |
src/modules/podcast/tasks/rss.py | DmitryBurnaev/podcast-service | 5 | 45545 | <filename>src/modules/podcast/tasks/rss.py
import os
from jinja2 import Template
from core import settings
from common.storage import StorageS3
from common.utils import get_logger
from modules.podcast.models import Podcast, Episode
from modules.podcast.tasks.base import RQTask, FinishCode
logger = get_logger(__name_... | 2.046875 | 2 |
crawler/chengdulib.py | zixinzeng-jennifer/public-culture-activity | 0 | 45546 | # -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup
from cultureBigdata.items import CultureNewsItem, CultureBasicItem, CultureEventItem
from selenium import webdriver
import re
import time
class ChengdulibSpider(scrapy.Spider):
name = 'chengdulib'
# 爬去机构动态所需的参数
news_u... | 2.828125 | 3 |
acoustic_fixture/testing/acoustic_fixture_calibration.py | XDleader555/acoustic_laser | 1 | 45547 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" calibration_rig.py: trilateration microphone calibration
Since trilateration doesn't account for the acoustic properties of the sound
source, the results will be skewed. To account for this, it's possible
to use machine learning to build a lookup table-like... | 2.921875 | 3 |
startup/users/30-user-Kim.py | mrakitin/profile_collection-smi | 0 | 45548 | <reponame>mrakitin/profile_collection-smi
#Align GiSAXS sample
import numpy as np
def run_giwaxs_Kim(t=1):
# define names of samples on sample bar
sample_list = ['7-1_wideangle_10nm_MIM', '7-2_wideangle_20nm_MIM', '7-3_wideangle_4nm_MIM', '7-4_wideangle_Hf0.75', '7-5_wideangle_Hf0.25','7-6_wideangle_Z... | 2.03125 | 2 |
__init__.py | HAL-42/AlchemyCat | 8 | 45549 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@contact: <EMAIL>
@software: PyCharm
@file: __init__.py
@time: 2020/1/8 0:15
@desc:
"""
from alchemy_cat.acplot.utils import CHW2HWC, HWC2CHW, RGB2BGR, BGR2RGB
from alchemy_cat.py_tools import quick_init | 1.085938 | 1 |
dev/add_images_to_db.py | johncoleman83/stamp | 0 | 45550 | #!/usr/bin/python3
"""
generates DB from Getty API
"""
import json
import models
User = models.User
Image = models.Image
storage = models.storage
def load_from_json_file(filename):
"""creates json object from file"""
with open(filename, mode='r', encoding='utf-8') as f_io:
my_dict = json.loads(f_io.re... | 3.078125 | 3 |
virtualscreening/vina/spark/vina_utils.py | rodrigofaccioli/drugdesign | 3 | 45551 | <filename>virtualscreening/vina/spark/vina_utils.py
import os
import ntpath
import json
from math import sqrt
#from json_utils import create_json_file
def get_files_mol2(mypath):
only_mol2_file = []
for root, dirs, files in os.walk(mypath):
for file in files:
if file.endswith(".... | 2.65625 | 3 |
toadie/toadie.py | dgonzo/toadie | 1 | 45552 | <gh_stars>1-10
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2016 <NAME>"
__license__ = "Apache License 2.0"
__version__ = "0.1.1a1"
import click
from .libs.dependencies import Tools
from .libs.components import StackComponent
import logging
import os
import errno
import re
import subproc... | 2.078125 | 2 |
nfproc.py | tvaleev/NATSimTools | 0 | 45553 | <gh_stars>0
import os
import sys
import fileinput
import re
import random
import math
from operator import itemgetter, attrgetter
import subprocess
from optparse import OptionParser
import copy
import time
import argparse
from dateutil import parser as dparser
import calendar
import pylab as P
import numpy as np
from... | 2.25 | 2 |
app/tests/teams_tests/test_views.py | njmhendrix/grand-challenge.org | 101 | 45554 | <reponame>njmhendrix/grand-challenge.org
import pytest
from django.conf import settings
from django.test import Client
from tests.factories import TeamFactory, TeamMemberFactory
from tests.utils import (
assert_viewname_redirect,
assert_viewname_status,
get_view_for_user,
validate_admin_or_participant_... | 2.125 | 2 |
src/tfNetwork/cost.py | RaymondLZhou/deep-neural-networks | 0 | 45555 | <filename>src/tfNetwork/cost.py
import tensorflow as tf
def compute_cost(Z3, Y):
logits = tf.transpose(Z3)
labels = tf.transpose(Y)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))
return cost
| 2.609375 | 3 |
Calculator.py | Terozaki/ubiquitous-fiesta | 0 | 45556 | <gh_stars>0
import math
running = True
#Functions
#Basic Calculation Function
def calc(x,y,s):
if s == 'add':
return x + y
if s == 'sub':
return x - y
if s == 'mul':
return x * y
if s == 'div':
return x / y
#Lowest Common Multiple Function
... | 3.46875 | 3 |
array/1300_sum_of_mutated_array_closest_to_target/1300_sum_of_mutated_array_closest_to_target.py | zdyxry/LeetCode | 6 | 45557 | <reponame>zdyxry/LeetCode<filename>array/1300_sum_of_mutated_array_closest_to_target/1300_sum_of_mutated_array_closest_to_target.py<gh_stars>1-10
class Solution(object):
def findBestValue(self, arr, target):
arr.sort(reverse = True)
while arr and target >= arr[-1]*len(arr):
temp = arr[-... | 2.984375 | 3 |
light_control/colors.py | XenonMolecule/led-lightstrip | 0 | 45558 | <filename>light_control/colors.py
# Converts RGB to GRB which is needed by the lightstrip
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""... | 3.125 | 3 |
tests/test_grid/test_continent_cells.py | wpreimes/io_utils | 0 | 45559 | <reponame>wpreimes/io_utils<filename>tests/test_grid/test_continent_cells.py
# -*- coding: utf-8 -*-
from io_utils.grid.grid_functions import read_cells_for_continent
def test_read_cells_for_continent():
try:
read_cells_for_continent('notexistingname')
except ValueError:
assert True
else:
... | 1.976563 | 2 |
wallee/models/subscription_product_version_retirement_create.py | bluedynamics/wallee-python-sdk | 0 | 45560 | <filename>wallee/models/subscription_product_version_retirement_create.py
# coding: utf-8
import pprint
import six
from enum import Enum
class SubscriptionProductVersionRetirementCreate:
swagger_types = {
'product_version': 'int',
'respect_terminiation_periods_enabled': 'bool',
'tar... | 2.078125 | 2 |
test/programytest/config/brain/test_dynamic.py | cdoebler1/AIML2 | 345 | 45561 | import unittest
from programy.clients.events.console.config import ConsoleConfiguration
from programy.config.brain.dynamic import BrainDynamicsConfiguration
from programy.config.file.yaml_file import YamlConfigurationFile
class BrainDynamicsConfigurationTests(unittest.TestCase):
def test_with_data(self):
... | 2.625 | 3 |
materials_io/csv.py | jat255/MaterialsIO | 10 | 45562 | <gh_stars>1-10
from materials_io.base import BaseSingleFileParser
from tableschema.exceptions import CastError
from tableschema import Table
from typing import List
import logging
logger = logging.getLogger(__name__)
class CSVParser(BaseSingleFileParser):
"""Reads comma-separated value (CSV) files
The conte... | 2.75 | 3 |
getmap.py | psiang/OSMcrop | 0 | 45563 | <gh_stars>0
'''
pygetmap:
Download web map by cooridinates
'''
# Longitude 经度
# Latitude 纬度
# Mecator x = y = [-20037508.3427892,20037508.3427892]
# Mecator Latitue = [-85.05112877980659,85.05112877980659]
import math
from math import floor, pi, log, tan, atan, exp
from threading import Thread, Lock
import urllib.... | 2.4375 | 2 |
scripts/query_building/eval.py | harol-tch/DeepShallowParsingQA | 6 | 45564 | <gh_stars>1-10
import re
import os
import ujson as json
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from common.linkers.candidate_generator.earlCG import EARLCG
from config import config
from common.dataset.qald_6_ml import Qald_6_ml
from common.dataset.qald_7_ml import Qald_7_ml
from common.d... | 2.03125 | 2 |
setup.py | 2231puppy/Hoist | 0 | 45565 | from setuptools import setup, find_packages
import codecs
import os
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
long_description = "\n" + fh.read()
VERSION = '0.0.3'
DESCRIPTION = 'Communicate with other machines via the local netwo... | 1.484375 | 1 |
sympy_test1.py | eilifm/rit_missing_data | 1 | 45566 | from sympy import *
x1, x2, y, b0, b1, b2, b12 = symbols('x1 x2 y b0 b1 b2 b12')
eq = Eq(b0 + (b1*x1) + (b2*x2) + (b12*x1*x2), y)
expr = solve(eq, x1)[0]
print(expr)
# str1 = "x1:x2"
# str1 = "(" + str1 + ")"
# print(str1.replace(':', '*'))
| 3.59375 | 4 |
renderer/plane.py | darsovit/pyRayTracerChallenge | 2 | 45567 | #! python
#
#
from renderer.shape import Shape
from renderer.bolts import Vector, EPSILON
class Plane(Shape):
def LocalNormal( self, localPoint ):
return Vector( 0, 1, 0 )
def LocalIntersect(self, localRay):
if abs(localRay.Direction()[1]) < EPSILON:
return []
timeToInters... | 2.765625 | 3 |
netket/custom/ab_initio_ham.py | yannra/netket | 0 | 45568 | <filename>netket/custom/ab_initio_ham.py
import netket as nk
from netket.custom.fermionic_hilbert import Fermions
from netket.custom.fermion_operator import SparseHermitianFermionOperator, FermionSumOperators, FermionTotalSpinNumberOperator
import numpy as np
class AbInitio(FermionSumOperators):
def __init__(self... | 2.265625 | 2 |
src/xdevice/_core/report/encrypt.py | OpenHarmony-mirror/test_xdevice | 0 | 45569 | #!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | 2.125 | 2 |
Algorithm/Easy/1-500/452Remove Linked List Elements.py | MartinYan623/Lint-Code | 0 | 45570 | <reponame>MartinYan623/Lint-Code<filename>Algorithm/Easy/1-500/452Remove Linked List Elements.py<gh_stars>0
"""
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
class Solution:
"""
@param: head: a ListNode
@param: val: An integ... | 3.4375 | 3 |
shooter/cache.py | smpio/kube-snapshooter | 0 | 45571 | <reponame>smpio/kube-snapshooter<gh_stars>0
import kubernetes.client
from kubernetes.config.dateutil import parse_rfc3339
class SnapshotCache:
def __init__(self):
self._ns_cache = {}
self.api = kubernetes.client.CustomObjectsApi()
def get_snapshots(self, namespace):
try:
r... | 2.28125 | 2 |
utils/rsa.py | vsgobbi/nfe-library | 0 | 45572 | from base64 import b64encode
from hashlib import sha1
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
class Rsa:
@classmethod
def sign(cls, text, privateKeyContent):
digest = SHA.new(text)
rsaKey = RSA.importKey(privateKeyContent)
s... | 2.578125 | 3 |
sundaytasks/example/simple_plugin2/__init__.py | olafura/sundaytasks-py | 0 | 45573 | from tornado import gen, httpclient
from tornado.escape import json_decode
import logging
@gen.coroutine
def receiver(args):
logging.info("Enter simple_plugin")
logging.debug("args: %s", str(args))
http_client = httpclient.AsyncHTTPClient()
response = yield http_client.fetch("http://localhost:5984/_ses... | 2.171875 | 2 |
equipment_assigments/models.py | amado-developer/ReadHub-RestfulAPI | 0 | 45574 | <gh_stars>0
from django.db import models
'''
Equipment_Assigment
id_user (FK)
id_equipment (FK)
'''
class Equipment_Assigment(models.Model):
'''
id_user = models.ForeignKey(
'Users.User',
on_delete = models.CASCADE,
null = False,
blank = False
)
'''
id_equipment = mode... | 2.109375 | 2 |
api/organisations/managers.py | mevinbabuc/flagsmith | 1,259 | 45575 | <reponame>mevinbabuc/flagsmith
from django.db.models import Manager
from permissions.models import ORGANISATION_PERMISSION_TYPE
class OrganisationPermissionManager(Manager):
def get_queryset(self):
return super().get_queryset().filter(type=ORGANISATION_PERMISSION_TYPE)
| 1.9375 | 2 |
setup.py | machinezone/kubespec | 7 | 45576 | from setuptools import find_packages, setup
with open("requirements.txt") as f:
requirements = f.read().splitlines()
with open("README.md") as f:
readme = f.read()
setup(
name="kubespec",
version="0.1.dev20200203",
url="https://github.com/machinezone/kubespec",
author="<NAME>",
author_em... | 1.4375 | 1 |
website/tantalus/forms.py | KiOui/TOSTI | 1 | 45577 | import logging
from django import forms
from tantalus.services import get_tantalus_client, TantalusException
class TantalusProductAdminForm(forms.ModelForm):
"""Tantalus Product Admin Form."""
tantalus_id = forms.ChoiceField(required=True)
def __init__(self, *args, **kwargs):
"""Initialize Tan... | 2.15625 | 2 |
plot.py | felipenwelter/maintenance-schedule | 0 | 45578 | import matplotlib.pyplot as plt
#---------------------------------------------------------------
# Function plot:
# Plot cost x generation graphic
# Parameters:
# itens - cost of each generation
# itens2 - number of feasible solutions at each generation
#-------------------------------------------------------... | 3.671875 | 4 |
Eth_Hunt.py | iceland2k14/ETH_Hunt | 18 | 45579 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
@author: iceland
"""
import bit
import time
import binascii
import random
import sys
from eth_hash.auto import keccak
from fastecdsa import curve
from fastecdsa.point import Point
from multiprocessing import Event, Process, Queue, Value, cpu_count
#=====... | 2.359375 | 2 |
sa/profiles/Harmonic/bNSG9000/profile.py | prorevizor/noc | 84 | 45580 | __author__ = "fedoseev.ns"
from noc.core.profile.base import BaseProfile
class Profile(BaseProfile):
name = "Harmonic.bNSG9000"
| 1.296875 | 1 |
StealthwatchCloud/send_detailed_alerts_2.py | CiscoDevNet/CiscoSecurityAPIsStartNow | 7 | 45581 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python example script showing SecureX Cloud Analytics Alerts.
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
... | 2.578125 | 3 |
ToBeOrWhatToBe/beOrNotToBe-preprocessor.py | bassamriman/ToBeOrWhatToBe-Seq2seq | 0 | 45582 | from __future__ import print_function
import argparse
import os
import re
import nltk.data
parser = argparse.ArgumentParser()
parser.add_argument('--source-dir', help="Source data directory", default="./dataset/original_data")
parser.add_argument('--target-dir', help="Traget data directory", default="./dataset/pre_p... | 3.046875 | 3 |
django_basics/logging.py | pinehq/django_basics | 0 | 45583 | from logging import StreamHandler
from ipware import get_client_ip
class EnhancedStreamHandler(StreamHandler, object):
def emit(self, record):
record.ip = ''
record.email = ''
try:
request = record.args[0]
record.ip, _ = get_client_ip(request)
record.a... | 2.03125 | 2 |
main.py | wspalding/evolution | 0 | 45584 | from genetic_algo import Genetic_algorithm, Network_info
import train_cfar10 as cfar10
import tensorflow as tf
print("GPU Available: ", tf.test.is_gpu_available())
nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test = cfar10.get_cifar10()
dataset = {
# 'name': 'cifar10',
'num_classes... | 2.421875 | 2 |
Data.py | Elia1996/GestionaleVendite | 0 | 45585 | <gh_stars>0
import datetime
def Hour():
return datetime.datetime.now().strftime("%H:%M")
def Data():
return datetime.datetime.now().strftime("%d/%m/%Y")
| 2.859375 | 3 |
gnss_tec/tec.py | andremartinon/gnss-tec | 24 | 45586 | # coding=utf8
"""Class to compute total electron content."""
from .gnss import *
class TecError(Exception):
"""Class for Tec related errors."""
pass
class Tec(object):
"""Total electron content object.
Attributes
----------
timestamp : datetime.datetime instance
date and time of the... | 2.90625 | 3 |
permissionedforms/forms.py | wagtail/django-permissionedforms | 5 | 45587 | <filename>permissionedforms/forms.py
from django import forms
class Options:
"""
An object that serves as a container for configuration options. When a class is defined using
OptionCollectingMetaclass as its metaclass, any attributes defined on an inner `class Meta`
will be copied to an Options instan... | 2.734375 | 3 |
invoicer/_login/__init__.py | mtik00/invoicer | 0 | 45588 | <gh_stars>0
from flask import (
Blueprint, render_template, request, flash, redirect, url_for, session)
from flask_login import login_user, logout_user, login_required, current_user
from ..common import is_safe_url
from ..password import verify_password, hash_password
from ..models import User
from ..logger impor... | 2.421875 | 2 |
tests/api/mocks.py | gmos2104/poke-query | 0 | 45589 | class MockRequests:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_data = json_data
self.get_method_called = False
def __call__(self, *args, **kwargs):
self.get_method_called = True
self.response = MockResponse(json_data=self.json_data)
retur... | 2.875 | 3 |
rllib/environment/mujoco/half_cheetah.py | shenao-zhang/DCPU | 8 | 45590 | """Half-Cheetah Environment with full observation."""
import gym.error
from .locomotion import LocomotionEnv
try:
from gym.envs.mujoco.half_cheetah_v3 import HalfCheetahEnv
except (ModuleNotFoundError, gym.error.DependencyNotInstalled):
HalfCheetahEnv = object
class MBHalfCheetahEnv(LocomotionEnv, HalfCheet... | 2.1875 | 2 |
src/HafrenHaver/orientation.py | InnovAnon-Inc/HafrenHaver | 2 | 45591 | #! /usr/bin/env python3
from math import pi
from enum import Enum
class Orientation (Enum):
NORTH = 0
EAST = 1 # "est"
SOUTH = 2
WEST = 3 # "weest"
def radians (self):
if self == NORTH: return pi / +2
if self == EAST: return 0
if self == SOUTH: return pi
if self == WEST: return pi / -2
raise Except... | 4.03125 | 4 |
plugin.video.tistheseason/resources/lib/plugins/m3u.py | bobbybark/tantrumrepo | 3 | 45592 | """
m3u.py --- Jen Plugin for accessing m3u data
Copyright (C) 2018
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any la... | 2.4375 | 2 |
safenotes/displayer.py | Guilherme-Vasconcelos/safenotes | 1 | 45593 | from safenotes.helpers import display_colored_text
from safenotes.colors import red, blue
from typing import Callable, Dict
from os import system
from sys import exit
import safenotes.files_accessor as files_accessor
import questionary
class Displayer:
"""
Class for displaying all notes, handling user action... | 3.578125 | 4 |
leetcode/1217_play_with_chips.py | jacquerie/leetcode | 3 | 45594 | # -*- coding: utf-8 -*-
class Solution:
def minCostToMoveChips(self, chips):
count_even, count_odd = 0, 0
for chip in chips:
if chip % 2 == 0:
count_even += 1
else:
count_odd += 1
return min(count_even, count_odd)
if __name__ == '_... | 3.75 | 4 |
nuplan/planning/metrics/evaluation_metrics/common/clearance_from_static_agents.py | motional/nuplan-devkit | 128 | 45595 | from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, List, Optional
import numpy as np
import numpy.typing as npt
from nuplan.common.actor_state.agent import Agent
from nuplan.common.actor_state.ego_state import EgoState
from nuplan.common.actor_state.vehicle_parameters impor... | 2.5625 | 3 |
cosme/v1/wagtail_hooks.py | contactr2m/cosme | 0 | 45596 | import logging
from six.moves.urllib.parse import urlsplit
from django.conf import settings
from django.conf.urls import url, re_path
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.utils.html import escape, format_html_join
from wagtail.admin.menu import MenuItem
from ... | 1.84375 | 2 |
filebarn/views.py | popas90/filebarn | 0 | 45597 | from flask import render_template, flash, redirect
from flask import session, url_for, request, g
from flask.ext.login import login_user, logout_user
from flask.ext.login import current_user, login_required
from filebarn import app, db, lm
from .forms import LoginForm
from .models import User
@app.route('/secret/<use... | 2.546875 | 3 |
TBS/jewelry/models/merchandise.py | v1ct0r5u3n/TBS | 0 | 45598 | # -*- coding: utf-8 -*-
from django.db import models
from datetime import date
from django.utils import timezone
from user.models import Person,Customer
from .price_category import PriceCategory
from core.models import Address
from core.mixins import TimeStampedMixin,PartComposMixin,ThumbnailMixin
from core.utils impor... | 2.125 | 2 |
src/m1_hangman.py | griernm/21-FunctionalDecomposition | 0 | 45599 | """
Hangman.
Authors: <NAME> and <NAME>.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
# DONE: 2. Implement Hangman using your Iterative Enhancement Plan.
####### Do NOT attempt this assignment before class! #######
import random
word = ''
guesses = []
def main():
word = get_word()
guesses.clear()
... | 4.25 | 4 |