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 |
|---|---|---|---|---|---|---|
src/ParseIngredientsBase.py | GregCKrause/hello-openai | 0 | 12782151 | # Standard library
import argparse
import os
# Third party
import openai
# Consts
PROMPT = """
Given a cooking ingredient and quantity, return only the ingredient name
2 cups flour
Flour
Cinnamon ~1 tablespoon
Cinnamon
About one tsp salt
Salt
1.5-2 cups grated raw zucchini
Raw zucchini
1c walnuts (optional)
Walnuts
... | 2.984375 | 3 |
reviews/views.py | YaroslavChyhryn/EshopReviewAPI | 0 | 12782152 | from .serializers import ReviewSerializer, ShopSerializer, UserReviewSerializer
from rest_framework import viewsets
from rest_framework.pagination import LimitOffsetPagination
from .models import ReviewModel, ShopModel
from rest_framework.generics import ListAPIView
from rest_framework import filters
from django.db.mod... | 2.015625 | 2 |
graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_object.py | cmueh/graalpython | 0 | 12782153 | # Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# The Universal Permissive License (UPL), Version 1.0
#
# Subject to the condition set forth below, permission is hereby granted to any
# person obtaining a copy of this software, a... | 1.234375 | 1 |
code/python/modules/loggerOld.py | jnromero/steep | 0 | 12782154 | <gh_stars>0
from __future__ import print_function,division,absolute_import
import os
from twisted.python import log
import time
import sys
import pickle
#start the logger
class TwistedLogger:
def __init__(self,config):
self.fileCount=1
self.entries=0
self.fullLogFile=config['fullLogFile']
... | 2.421875 | 2 |
leetcode/0-250/260-1071. Greatest Common Divisor of Strings.py | palash24/algorithms-and-data-structures | 23 | 12782155 | # 1071. Greatest Common Divisor of Strings
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if len(str1) == len(str2):
return str1 if str1 == str2 else ''
else:
if len(str1) < len(str2):
str1, str2, = str2, str1
if str1[:len(str... | 3.515625 | 4 |
netbox/dcim/exceptions.py | BrnoPCmaniak/netbox | 6 | 12782156 | <reponame>BrnoPCmaniak/netbox
class LoopDetected(Exception):
"""
A loop has been detected while tracing a cable path.
"""
pass
| 1.648438 | 2 |
venv/lib/python3.8/site-packages/poetry/core/masonry/utils/include.py | GiulianaPola/select_repeats | 2 | 12782157 | /home/runner/.cache/pip/pool/14/6a/45/959613aab7d0674a9eb24e47bacc8b7eaa8cef7583b8cdb8b75e967ae6 | 0.804688 | 1 |
ftp_client/ftp_client.py | nathanwiens/sdk-samples | 44 | 12782158 | <reponame>nathanwiens/sdk-samples
"""
This app will create a file and then upload it to an FTP server.
The file will be deleted when the app is stopped.
"""
from csclient import EventingCSClient
from ftplib import FTP
cp = EventingCSClient('ftp_client')
TEMP_FILE = 'my_file.txt'
cp.log('ftp_client send_ftp_file()...... | 2.8125 | 3 |
tests/test_base58check.py | joeblackwaslike/base58check | 1 | 12782159 | <filename>tests/test_base58check.py<gh_stars>1-10
import unittest
import base58check
TEST_DATA = [
(b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT',
b'\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde'),
(b'3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC',
b'\x05\xf8\x15\xb06\xd9\xbb\x... | 2 | 2 |
mining_rewards/mining_rewards.py | terra-project/research | 43 | 12782160 | <gh_stars>10-100
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import argparse
import math
# common hack to import from sibling directory utils
# alternatives involve making all directories packages, creating setup files etc
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__)... | 1.890625 | 2 |
scripts/load_data.py | nilsleiffischer/covid19 | 4 | 12782161 | <filename>scripts/load_data.py
import pandas as pd
def load_jhu_data():
data = pd.read_csv(
'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv',
index_col=1)
data.index = data.index + (" (" + d... | 2.875 | 3 |
lib/packer.py | mitodl/concourse-packer-resource | 0 | 12782162 | # stdlib
import subprocess
from typing import List
# local
from lib.io import read_value_from_file
from lib.log import log, log_pretty
# =============================================================================
#
# private utility functions
#
# =====================================================================... | 2.40625 | 2 |
libra_client/lbrtypes/account_config/constants/account_limits.py | violas-core/violas-client | 0 | 12782163 | <filename>libra_client/lbrtypes/account_config/constants/account_limits.py
from libra_client.move_core_types.language_storage import ModuleId, CORE_CODE_ADDRESS
ACCOUNT_LIMITS_MODULE_NAME = "AccountLimits"
ACCOUNT_LIMITS_MODULE = ModuleId(CORE_CODE_ADDRESS, ACCOUNT_LIMITS_MODULE_NAME)
ACCOUNT_LIMITS_WINDOW_STRUCT_NAME... | 1.445313 | 1 |
app/api/test_api.py | totoro0104/fastapi-example | 2 | 12782164 | from typing import Optional
from fastapi import APIRouter, Depends
import httpx
from app.models.models import User
from app.schema import User_Pydantic
router = APIRouter()
@router.get("/")
async def homepage():
# httpx代替requests进行异步请求
async with httpx.AsyncClient() as client:
res = await client.ge... | 2.578125 | 3 |
backpack/extensions/firstorder/fisher/__init__.py | maryamhgf/backpack | 0 | 12782165 | <gh_stars>0
from torch.nn import (
Conv1d,
Conv2d,
Linear,
BatchNorm1d,
BatchNorm2d
)
from backpack.extensions.backprop_extension import BackpropExtension
from . import (
conv1d,
conv2d,
linear,
batchnorm1d,
batchnorm2d
)
class Fisher(BackpropExtension):
def __init_... | 2.21875 | 2 |
lib/surface/kms/keys/versions/get_certificate_chain.py | google-cloud-sdk-unofficial/google-cloud-sdk | 2 | 12782166 | # -*- coding: utf-8 -*- #
# Copyright 2020 Google 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.org/licenses/LICENSE-2.0
#
# Unless requir... | 1.796875 | 2 |
ReconnaissanceFaciale/RecoFaciale.py | BasileAmeeuw/DroneDelivreur | 0 | 12782167 | #import libraries
import face_recognition
import numpy as np
from PIL import Image, ImageDraw
import matplotlib.image as mpimg
from IPython.display import display
import cv2
import os, re
import pyrebase
import time
cv2.VideoCapture(0).isOpened()
from dronekit import connect, VehicleMode, LocationGlobalRelative
import... | 2.140625 | 2 |
.openapi-generator/update_type_with_interface.py | AntoineDao/honeybee-schema-dotnet | 0 | 12782168 | import re, os, json
root = os.path.dirname(os.path.dirname(__file__))
source_folder = os.path.join(root, 'src', 'HoneybeeSchema', 'Model')
#NamedReferenceable
class_files = [x for x in os.listdir(source_folder) if (x.endswith("Abridged.cs") and not x.endswith("SetAbridged.cs") and not x.endswith("PropertiesAbridged.... | 2.171875 | 2 |
concentric/users/migrations/0005_user_name.py | guidotheelen/concentric | 0 | 12782169 | <filename>concentric/users/migrations/0005_user_name.py
# Generated by Django 3.0.10 on 2020-11-27 23:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20201127_2250'),
]
operations = [
migrations.AddField(
... | 1.460938 | 1 |
datasets/tr_cpi_parser.py | davidpaulkim/Stock-Market-Price-Prediction | 8 | 12782170 | <reponame>davidpaulkim/Stock-Market-Price-Prediction<gh_stars>1-10
# src= "https://tcmb.gov.tr/wps/wcm/connect/EN/TCMB+EN/Main+Menu/Statistics/Inflation+Data/Consumer+Prices"
cpi_values = """02-2021 15.61 0.91
01-2021 14.97 1.68
12-2020 14.60 1.25
11-2020 14.03 2.30
10-2020 11.89 2.13
09-2020 11.75 0.97
08-2020 11.77 0... | 2.5 | 2 |
dailyplot.py | nerrull/hackatown2018 | 38 | 12782171 | <filename>dailyplot.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# This code is part of the Solar3Dcity package
# Copyright (c) 2015
# <NAME>
# Delft University of Technology
# <EMAIL>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and asso... | 1.695313 | 2 |
controller.py | woxiang-H/auto-beaver | 0 | 12782172 | import sys
import os
from settings import beaver_broker_ip, beaver_broker_port, autotestdir, beaver_datanode_file, gflagsfile, config_path, log_dir, index_forsearch, pb_forsearch
import psutil
import time
import numpy as np
import requests
#MEM_MAX = psutil.virtual_memory().total
MEM_MAX = 0.8*32*1024*1024*1024 ... | 1.96875 | 2 |
process.py | JamesMilnerUK/facebook-pop-viz | 2 | 12782173 | <reponame>JamesMilnerUK/facebook-pop-viz
from osgeo import gdal, ogr
from os import remove, getcwd
from os.path import isfile, join, basename
import sys
import numpy as np
import traceback
from shutil import copyfile
# this allows GDAL to throw Python Exceptions
gdal.UseExceptions()
def single_band( input_... | 2.421875 | 2 |
bionumpy/string_matcher.py | knutdrand/bionumpy | 0 | 12782174 | <filename>bionumpy/string_matcher.py<gh_stars>0
from bionumpy.rollable import RollableFunction
from bionumpy.sequences import as_sequence_array
import itertools
import numpy as np
import bionumpy as bnp
import re
from bionumpy.sequences import Sequence
class StringMatcher(RollableFunction):
def __init__(self, matc... | 2.515625 | 3 |
tests/fractalmusic/deepcopy/test_fm_deepcopy.py | alexgorji/musurgia | 0 | 12782175 | import os
from musicscore.musictree.treescoretimewise import TreeScoreTimewise
from musurgia.unittest import TestCase
from musurgia.fractaltree.fractalmusic import FractalMusic
path = str(os.path.abspath(__file__).split('.')[0])
class Test(TestCase):
def setUp(self) -> None:
self.score = TreeScoreTimew... | 2.46875 | 2 |
chisch/utils/jsonutils.py | zhaowenxiang/chisch | 0 | 12782176 | <filename>chisch/utils/jsonutils.py
#! -*- coding: utf-8 -*-
import simplejson
from django.db import models
from dss.Serializer import serializer
from django.db.models.query import QuerySet
def to_json(obj, **kwargs):
exclude_attr = kwargs['exclude_attr'] if kwargs and 'exclude_attr' in kwargs else []
incl... | 2.265625 | 2 |
dashboard/processors.py | JayaramanSudhakar/yorek-ssis-dashboard | 0 | 12782177 | from dashboard import app
from distutils.util import strtobool
@app.context_processor
def utility_processor():
def tile_color(kpi_value):
result = 'green'
#if (kpi_value == 0) :
# result = 'primary'
if (kpi_value > 0) :
result = 'red'
return result
retur... | 2.234375 | 2 |
tests/trees_tests/splay_tree_test.py | warmachine028/datastax | 5 | 12782178 | <filename>tests/trees_tests/splay_tree_test.py
from __future__ import annotations
import random
import unittest
from datastax.errors import (
NodeNotFoundWarning,
DeletionFromEmptyTreeWarning,
DuplicateNodeWarning
)
from datastax.trees import SplayTree
from tests.trees_tests.common_helper_functions import... | 2.625 | 3 |
mlight/session.py | GitHK/mlight | 0 | 12782179 | <filename>mlight/session.py
from collections import deque
import motor.motor_asyncio
class DBSession:
def __init__(self, mongo_uri, database_name):
self.mongo_uri = mongo_uri
self.database_name = database_name
self.client = motor.motor_asyncio.AsyncIOMotorClient(mongo_uri)
self.re... | 2.5 | 2 |
tests/shops/rsonline.py | MrLeeh/shopy | 0 | 12782180 | <reponame>MrLeeh/shopy
"""
Copyright 2015 by <NAME>
"""
from shopy.shop import Shop
with open('../shops/rsonline.json', 'r') as f:
shop = Shop.from_json(f)
iterator = shop.find("Batterien AAA 1.5V")
for item in iterator:
print(item, item.images) | 2.765625 | 3 |
src/utils/formatting.py | AdityaSidharta/ML_server_framework | 1 | 12782181 | <reponame>AdityaSidharta/ML_server_framework
import pandas as pd
def df_na_value(df, schema):
column_names = schema.get_col_names()
for column_name in column_names:
if column_name in df.columns:
column_na_value = schema.get_col_na_value(column_name)
df[column_name] = df[column_... | 2.96875 | 3 |
tools/SolBinding/Config/BaseConfig.py | wzhengsen/engine-x | 0 | 12782182 | <gh_stars>0
#!/usr/bin/env python3
# Copyright (c) 2021 - wzhengsen
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... | 1.726563 | 2 |
code/arc081_a_01.py | KoyanagiHitoshi/AtCoder | 3 | 12782183 | <reponame>KoyanagiHitoshi/AtCoder<filename>code/arc081_a_01.py<gh_stars>1-10
from collections import Counter
N=int(input())
A=Counter(list(map(int,input().split())))
x=[0,0]
for a in A:
if A[a]>1:x.append(a)
if A[a]>3:x.append(a)
x.sort()
print(x[-1]*x[-2]) | 3.21875 | 3 |
python/data_structures/stack.py | educauchy/algorithms | 0 | 12782184 | from typing import List, Optional, Any
class StackOverflow(Exception):
pass
class StackUnderflow(Exception):
pass
class Stack():
def __init__(self, capacity: int = 10):
"""
:param capacity: Maximum capacity of stack
:var top: Index of the current top element
:var contain... | 3.796875 | 4 |
test/test_matcher/test_marketorder.py | Miksus/ecosys | 2 | 12782185 | <gh_stars>1-10
import pytest
import sys
sys.path.append('..')
from ecosys.trading_platform.matcher.stockmarket import StockMatcher
def test_last_price_only_market_orders():
market = StockMatcher()
market.place_ask(quantity=50, order_type="market", party="Market Asker")
market.place_bid(quantity=100, orde... | 2.484375 | 2 |
setup.py | aymericvie/EvoNetworks | 0 | 12782186 | <reponame>aymericvie/EvoNetworks
import os
os.system("pip install numpy")
os.system("pip install matplotlib")
os.system("pip install networkx")
os.system("pip install tqdm")
| 1.46875 | 1 |
platform/hwconf_data/zgm13/upgrade/sdk_2_7_3_Patch/upgradeUtility.py | lenloe1/v2.7 | 0 | 12782187 | <filename>platform/hwconf_data/zgm13/upgrade/sdk_2_7_3_Patch/upgradeUtility.py
# SDK 2.7.3 Patch upgrade utilities
# Remove property with propertyId
# Note this function returns an xmldevice which should be passed back up to the
# upgradeDispatch level. Example:
# newXmlDevice = removePropertyLine(xmlDevice, "CMU.HA... | 2.390625 | 2 |
examples/search_index.py | leafcoder/aliyun-tablestore-python-sdk | 68 | 12782188 | <filename>examples/search_index.py
# -*- coding: utf8 -*-
from example_config import *
from tablestore import *
import time
import json
table_name = 'SearchIndexExampleTable'
index_name = 'search_index'
nested_index_name = 'nested_search_index'
client = None
def term_query_with_multiple_version_response(table_name, ... | 2.65625 | 3 |
pagination/page.py | pmaigutyak/mp-pagination | 0 | 12782189 |
import functools
import collections
from django.template.loader import render_to_string
from pagination.settings import MARGIN_PAGES_DISPLAYED, PAGE_RANGE_DISPLAYED
class PageRepresentation(int):
def __new__(cls, x, querystring):
obj = int.__new__(cls, x)
obj.querystring = querystring
r... | 2.28125 | 2 |
molecule/common/tests/test_containerd.py | incubateur-pe/containerd | 1 | 12782190 | <reponame>incubateur-pe/containerd<gh_stars>1-10
"""Role testing files using testinfra."""
def test_containerd_installed(host):
containerd = host.file("/usr/bin/containerd")
assert containerd.exists
assert containerd.user == "root"
assert containerd.group == "root"
assert containerd.mode == 0o755
... | 1.75 | 2 |
day16/part1.py | tatoonz/advent-of-code-2021 | 0 | 12782191 | import sys
input = bin(int(sys.stdin.readline().strip(), base=16))[2:]
# filling missing leading 0
input = input.zfill(-(-len(input)//4)*4)
def decode(msg):
if msg == '' or int(msg) == 0:
return 0
version = int(msg[0:3], 2)
type_id = int(msg[3:6], 2)
if type_id == 4:
last_group = F... | 2.765625 | 3 |
Server/Python/src/dbs/dao/MySQL/BlockParent/Insert.py | vkuznet/DBS | 8 | 12782192 | #!/usr/bin/env python
""" DAO Object for BlockParents table """
from dbs.dao.Oracle.BlockParent.Insert import Insert as OraBlockParentInsert
class Insert(OraBlockParentInsert):
pass
| 1.78125 | 2 |
arm_prosthesis/external_communication/models/dto/save_gesture_dto.py | paulrozhkin/arm_prosthesis_raspberry | 2 | 12782193 | from arm_prosthesis.external_communication.models.dto.entity_dto import EntityDto
from arm_prosthesis.external_communication.models.dto.gesture_dto import GestureDto
from gestures_pb2 import SaveGesture
class SaveGestureDto(EntityDto):
def __init__(self):
self._time_sync = 0
self._gestur... | 2.265625 | 2 |
soke-scripts/process/load.py | Wilfongjt/soke | 0 | 12782194 | from process.process import Process
class Load(Process):
def __init__(self, settings=None):
Process.__init__(self, settings=settings)
# import_file_name is full local file name or url to source
#self.import_file_list=import_file_list
#self.dataframe=None
#self.dictionary={}
... | 2.640625 | 3 |
es_dumpvec.py | eugene-yang/DESIRES18-QBD-Experiments | 0 | 12782195 | <filename>es_dumpvec.py<gh_stars>0
import argparse
from pathlib import Path
import pandas as pd
import numpy as np
import scipy.sparse as sp
import json, warnings, socket, pickle, sys, re
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
from helpers import pbar
parser = argparse.Argume... | 2.8125 | 3 |
pulumi/infra/fargate_service.py | ebcarty/grapl | 0 | 12782196 | import json
from typing import List, Mapping, Optional, Sequence, Tuple, Union, cast
import pulumi_aws as aws
import pulumi_docker as docker
from infra.cache import Cache
from infra.config import (
DEPLOYMENT_NAME,
REAL_DEPLOYMENT,
SERVICE_LOG_RETENTION_DAYS,
configured_version_for,
)
from infra.ec2 im... | 1.789063 | 2 |
src/python/WMCore/WMBS/MySQL/Fileset/ListFilesetByTask.py | khurtado/WMCore | 21 | 12782197 | <gh_stars>10-100
#!/usr/bin/env python
"""
_ListFilesetByTask_
MySQL implementation of Fileset.ListFilesetByTask
"""
__all__ = []
from WMCore.Database.DBFormatter import DBFormatter
class ListFilesetByTask(DBFormatter):
sql = """SELECT id, name, open, last_update FROM wmbs_fileset
WHERE id IN (SE... | 2.515625 | 3 |
Interpolation/TridiagonalSol.py | ssklykov/collection_numCalc | 0 | 12782198 | # -*- coding: utf-8 -*-
"""
Solution of a system of linear equations with tridiagonal matrix
Developed in the Spyder IDE
@author: ssklykov
"""
def Solution(a, b, c, d):
for i in range(1, len(d)): # Range always not included the last value
# Below the literal implementation from the book
a[i] /= b... | 3.734375 | 4 |
dungeonMaster.py | p0l0satik/pyprak | 0 | 12782199 | d = {}
nvis = set()
s = input()
while " " in s:
k, v = s.split()
if k == v:
continue
nvis.add(k)
nvis.add(v)
d.setdefault(v, [])
d.setdefault(k, [])
if v not in d[k]:
d[k].append(v)
if k not in d[v]:
d[v].append(k)
s = input()
now = [s,]
out = input()
while l... | 3.28125 | 3 |
colvar/compilers.py | kzinovjev/colvar | 0 | 12782200 | X_INDEX_INCREMENTS = {"x": 0, "y": 1, "z": 2}
def compile_constant(schema):
return {"type": "x",
"params": {"value": schema["value"]}}
def compile_cartesian(schema):
return {"type": "x",
"params": {
"index": schema["atom"] * 3 + X_INDEX_INCREMENTS[schema["type"]]
... | 2.4375 | 2 |
Solutions/Correlation does not imply causation.py | GuardsmanPanda/ProjectLovelace | 0 | 12782201 | <filename>Solutions/Correlation does not imply causation.py
def mean(a): return sum(a)/len(a)
def std(a):
m = mean(a)
return (sum((x - m)**2 for x in a)/len(a))**0.5
def correlation_coefficient(x, y):
xm, ym = mean(x), mean(y)
return sum((x[i]-xm)*(y[i]-ym) for i in range(len(x)))/std(x)/std(y)/len(x)... | 2.859375 | 3 |
testing/micro-bench/server/app.py | jgrunert/Microservice-Fault-Injection | 5 | 12782202 | import random
import string
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def root():
return jsonify(result=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(2 ** 10)))
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0')
| 2.625 | 3 |
01-DesenvolvimentoDeSistemas/02-LinguagensDeProgramacao/01-Python/01-ListaDeExercicios/02-Aluno/Edno/035.py | moacirsouza/nadas | 1 | 12782203 | # (01-Gabarito/035.py)) Desenvolva um programa que leia o comprimento de três retas e diga ao
# usuário se elas podem ou não formar um triângulo.
hipotenusa = float(input('Digite o valor do que será a hipotenusa\t: '))
cateto_a = float(input('Digite o valor do que será o cateto adjacente\t: '))
cateto_o = float(input(... | 4.21875 | 4 |
desafio042.py | RickChaves29/Desafios-Python | 0 | 12782204 | print('<>'*20)
print('Analizador de trangulo')
print('<>'*20)
r1 = float(input('Primeiro valor: '))
r2 = float(input('Segundo valor: '))
r3 = float(input('Terceiro valor: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os valores podem forma um triangulo')
if r1 == r2 == r3:
print('Tipo: E... | 4.09375 | 4 |
fairseq/modules/multibranch.py | ishine/lite-transformer | 543 | 12782205 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from . import MultiheadAttention
class MultiBranch(nn.Module):
def __init__(self, branches, embed_dim_list):
super().__init__()
self.branches = nn.ModuleList(branches)
self.embed_dim_list = embed_dim_lis... | 2.28125 | 2 |
ComputerVision/AruCO_Board.py | mateusribs/DissertacaoMestrado | 0 | 12782206 | <reponame>mateusribs/DissertacaoMestrado<filename>ComputerVision/AruCO_Board.py
import numpy as np
import cv2 as cv
dictionar = cv.aruco.getPredefinedDictionary(cv.aruco.DICT_4X4_50)
board = cv.aruco.GridBoard_create(2, 2, 0.05, 0.005, dictionar)
img = board.draw((680,500), 10, 1)
cv.imwrite('aruco_board.png', img)
... | 2.796875 | 3 |
src/infrastructure/translators/holiday_translator.py | gabrielleandro0801/holidays-importer | 0 | 12782207 | <reponame>gabrielleandro0801/holidays-importer
from datetime import datetime
from typing import Any
from src.domain.holiday import Holiday
DATE: dict = {
'FROM': '%Y-%m-%d',
'TO': '%Y/%m/%d'
}
def format_date(date: str) -> str:
formatted_date: datetime = datetime.strptime(date, DATE["FROM"])
return ... | 3.40625 | 3 |
setup.py | alekbuza/python-sgetopt | 1 | 12782208 | <filename>setup.py
#!/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# T... | 1.351563 | 1 |
tests/repository/test_memory.py | kobibleu/easyrepo | 0 | 12782209 | <filename>tests/repository/test_memory.py
from typing import Optional
import pytest
from pydantic import BaseModel
from easyrepo.model.paging import PageRequest
from easyrepo.repository.memory import MemoryRepository
class TestModel(BaseModel):
id: Optional[int]
name: str
class DictRepo(MemoryRepository[d... | 2.234375 | 2 |
pie4t/assist.py | beardad1975/pie4t | 1 | 12782210 | <reponame>beardad1975/pie4t
from time import time
import arcade
import pymunk
from pymunk.vec2d import Vec2d
from . import common
class DotMark:
def __init__(self, x=0, y=0):
self.enabled = False
self.x = x
self.y = y
self.timestamp = time()
def lazy_setup(self):
... | 2.46875 | 2 |
api/rules.py | poldracklab/bids-core | 1 | 12782211 | import fnmatch
from . import jobs
from . import config
log = config.log
#
# {
# At least one match from this array must succeed, or array must be empty
# "any": [
# ["file.type", "dicom" ] # Match the file's type
# ["file.name", "*.dcm" ] # Match a shell glob for the ... | 2.1875 | 2 |
experiments/webcam_pose2csv.py | Nao-Y1996/situation_recognition | 0 | 12782212 | <filename>experiments/webcam_pose2csv.py
import argparse
import logging
import time
import os
import csv
import datetime
import numpy as np
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
import sys
# sys.path.remove('/opt/ros/melodic/lib/python2.7/dist-packages')
... | 2.4375 | 2 |
access-benty-fields.py | aibhleog/arXiv-order | 0 | 12782213 | '''
Script used to pull voting information from benty-fields.com.
Must be logged in to access the benty-fields.
NOTES:
1) benty-fields mostly organizes paper suggestions based upon voting
history and chosen preferences (machine learning involved), so these
voting totals can be considered as a control sample (i... | 3.09375 | 3 |
src/traingame/__version__.py | timolesterhuis/traingame | 0 | 12782214 | <filename>src/traingame/__version__.py
__title__ = "traingame"
__description__ = "Train your own AI and race it!"
__url__ = ""
__version__ = "0.4.0"
__author__ = "<NAME>"
__author_email__ = "<EMAIL>"
| 1.3125 | 1 |
Conditional/Lista 1/Thiago/11.py | Vitor-ORB/algorithms-and-programming-1-ufms | 7 | 12782215 | <reponame>Vitor-ORB/algorithms-and-programming-1-ufms
# Recebe o horário em h m s divididos apenas por espaço.
def entrada():
h, m, s = map(int, input(
"Insira o horário separado apenas por espaço: ").split())
return h, m, s
# Calcula a diferença entre os horários de começo e fim.
def calculo(... | 3.953125 | 4 |
exercise_report_slack/util/slack_api_util.py | yamap55/exercise_report_slack | 0 | 12782216 | <filename>exercise_report_slack/util/slack_api_util.py
"""Slack APIを操作する関数群"""
from time import sleep
from typing import Any, Callable, Dict, List, Optional
from exercise_report_slack.settings import client
from slack_sdk.web.slack_response import SlackResponse
def get_channel_id(name: str) -> str:
"""
指定された... | 2.921875 | 3 |
src/models/board.py | hadizakialqattan/sudoku | 6 | 12782217 | import pygame
# local import
from base.base import GUIBase
from solver.solver import Solver
class Board(GUIBase):
"""Screen Board
:param board: Sudoku board represent as two dimensional array
:type board: list
:param size: screen dimensions (pixels) (width, height)
:type size: tuple
:param ... | 3.453125 | 3 |
web-app/src/models/quizgame/QuizGameQuizGameQuestionScore.py | philipp-mos/iubh-quiz-app | 0 | 12782218 | from ... import db
class QuizGameQuizGameQuestionScore(db.Model):
__tablename__ = 'quiz_game_quiz_game_question_scores'
id = db.Column(
db.Integer,
primary_key=True
)
quizgame_id = db.Column(
db.Integer(),
db.ForeignKey(
'quiz_games.id',
ondel... | 2.40625 | 2 |
train_model.py | Yunodo/Seq2Seq | 1 | 12782219 | <gh_stars>1-10
import os
import numpy as np
import trax
import jax
import jax.numpy as np
from prepare_data import text_data_generator
from model import biLSTMwithAttn
from training_loop import create_training_loop
%load_ext tensorboard
vocab_file = 'en_8k.subword' # one of: 'subword', 'sentencepiece', 'char'
BATCH... | 2.390625 | 2 |
opencamlib-read-only/src/get_revision.py | play113/swer | 0 | 12782220 | import commands
# import subprocess
import sys
import os
f = open("revision.h", "w")
# change directory to src/
os.chdir(sys.argv[1])
# run svnversion to get the revision number
rev_number = commands.getoutput("svnversion")
print "get_revision.py: got revision: ",rev_number
# commands is deprecated, should use s... | 2.546875 | 3 |
siswrapper/__init__.py | mario33881/siswrapper | 1 | 12782221 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ._version import __version__
from .siswrapper import Siswrapper
| 1.132813 | 1 |
asset-metadata/src/main.py | Screenly/playground | 0 | 12782222 | """
Example headers
{
"X-Screenly-hostname": "srly-jmar75ko6xp651j",
"X-Screenly-screen-name": "dizzy cherry",
"X-Screenly-location-name": "Cape Town",
"X-Screenly-hardware": "x86",
"X-Screenly-version": "v2",
"X-Screenly-lat": "-33.925278",
"X-Screenly-lng": "18.423889",
"X-Screenly-ta... | 2.546875 | 3 |
pages/themes/beginners/exceptions/Task_and_HW/get_user_data_exception_handling.py | ProgressBG-Python-Course/ProgressBG-VC2-Python | 0 | 12782223 | <reponame>ProgressBG-Python-Course/ProgressBG-VC2-Python<filename>pages/themes/beginners/exceptions/Task_and_HW/get_user_data_exception_handling.py<gh_stars>0
def get_string_from_user(msg):
while True:
try:
user_name = input(msg)
except:
print("\n***Oops, something went wrong! Try again!\n")
else:
retur... | 3.21875 | 3 |
physicellToXYZ.py | hallba/PhysicellVMD | 0 | 12782224 | import numpy as np
from scipy.io import loadmat # this is the SciPy module that loads mat-files
import matplotlib.pyplot as plt
from datetime import datetime, date, time
import pandas as pd
import math
'''
#Contains "basic_agents"
cells = loadmat("output00000064_cells.mat")
#contains "multiscale_microenvironment"
micr... | 2.59375 | 3 |
webdriver_test_tools/testcase/ie.py | connordelacruz/webdriver-test-tools | 5 | 12782225 | <filename>webdriver_test_tools/testcase/ie.py<gh_stars>1-10
from .webdriver import *
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class IETestCase(WebDriverTestCase):
"""Implementation of :class:`WebDriverTestCase
<webdriver_test_tools.testcase.webdriver.WebDriverTestCase>` u... | 2.15625 | 2 |
news/tests.py | VanirLab/VOS | 0 | 12782226 | from django.core import mail
from django.test import TestCase, TransactionTestCase
from django.contrib.auth.models import User
from news.models import News
class NewsTest(TestCase):
def test_feed(self):
response = self.client.get('/feeds/news/')
self.assertEqual(response.status_code... | 2.265625 | 2 |
utils.py | ktho22/tacotron2 | 0 | 12782227 | <reponame>ktho22/tacotron2
import numpy as np
from scipy.io.wavfile import read
import torch
import time
import os
from os.path import join, exists
def get_mask_from_lengths(lengths):
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))
mask = (ids < lengt... | 2.21875 | 2 |
_pkg_Studios/pkgStudio_kuhq/mod_KuWrite.py | tianlunjiang/_NukeStudio_v2 | 6 | 12782228 | <reponame>tianlunjiang/_NukeStudio_v2<filename>_pkg_Studios/pkgStudio_kuhq/mod_KuWrite.py
def _version_():
ver='''
version 1.1
- add more render types
- fix precomp render directory problem (`render/` to `elements/`)
- add render dialog UI with threading
- fixing naming error in render file, av... | 1.484375 | 1 |
tests/functional/adapter/test_basic.py | dbt-labs/dbt-snowflake | 51 | 12782229 | <reponame>dbt-labs/dbt-snowflake<filename>tests/functional/adapter/test_basic.py
import pytest
from dbt.tests.adapter.basic.test_base import BaseSimpleMaterializations
from dbt.tests.adapter.basic.test_singular_tests import BaseSingularTests
from dbt.tests.adapter.basic.test_singular_tests_ephemeral import (
BaseS... | 1.757813 | 2 |
sim/lib/inference.py | MPI-SWS/simulator | 0 | 12782230 | import time
import bisect
import numpy as np
import pandas as pd
import networkx as nx
import scipy
import scipy.optimize
import scipy as sp
import os
import matplotlib.pyplot as plt
import random
from bayes_opt import BayesianOptimization
from bayes_opt.util import UtilityFunction, Colours
import asyncio
import thre... | 1.96875 | 2 |
example/todos/models.py | pawnhearts/django-reactive | 21 | 12782231 | <reponame>pawnhearts/django-reactive<gh_stars>10-100
from django.db import models
from django_reactive.fields import ReactJSONSchemaField
from .constants import TODO_SCHEMA, TODO_UI_SCHEMA, set_task_types
class Todo(models.Model):
"""
A collection of task lists for a todo.
"""
name = models.CharFie... | 2.0625 | 2 |
caelus/post/__init__.py | sayerhs/cpl | 0 | 12782232 | # -*- coding: utf-8 -*-
"""
Provides log analysis and plotting utilities
.. currentmodule: caelus.post
.. autosummary::
:nosignatures:
~funcobj.functions.PostProcessing
~logs.SolverLog
~plots.CaelusPlot
"""
from .logs import SolverLog
from .funcobj import PostProcessing
| 1.09375 | 1 |
modules/info.py | merlinfuchs/clancy | 0 | 12782233 | <filename>modules/info.py
from dbots.cmd import *
from dbots import rest
class InfoModule(Module):
@Module.command()
async def avatar(self, ctx, user: CommandOptionType.USER):
"""
Get the avatar url for an user
"""
resolved = ctx.resolved.users.get(user)
if resolved is ... | 2.515625 | 3 |
ctf/nsec/2018/reverse/MarsAnalytica-20/solveMA.py | Sylhare/Flag | 0 | 12782234 | <filename>ctf/nsec/2018/reverse/MarsAnalytica-20/solveMA.py
# https://blog.rpis.ec/2018/05/northsec-2018-marsanalytica.html
import angr
def constrain_stdin(st):
for _ in range(19):
k = st.posix.files[0].read_from(1)
st.solver.add(k > 0x20)
st.solver.add(k < 0x7f)
st.posix.files[0].seek... | 2.421875 | 2 |
test/downloadAckunMusic.py | 1254517211/test-1 | 5 | 12782235 | #!/bin/env python
# coding=utf8
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64
import requests
import json
import urllib
import time
import random
import datetime
import hashlib
# 获得响应头信息中的Content-Type域
def urlOpenGetHeaders(url):
req = urllib.request.Reque... | 2.609375 | 3 |
fiber/__init__.py | ehmadzubair/django-fiber | 0 | 12782236 | __version__ = '1.9.dev0'
| 1.070313 | 1 |
translations/migrations/0034_auto_20200423_1115.py | aniruddha-adhikary/translateforsg-backend | 2 | 12782237 | <filename>translations/migrations/0034_auto_20200423_1115.py
# Generated by Django 3.0.5 on 2020-04-23 03:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('translations', '0033_populate_ordering_categories'),
]
operations = [
migration... | 1.5625 | 2 |
VSR/DataLoader/Dataset.py | Kadantte/VideoSuperResolution | 1,447 | 12782238 | <reponame>Kadantte/VideoSuperResolution
# Copyright (c) 2017-2020 <NAME>.
# Author: <NAME>
# Email: <EMAIL>
# Update: 2020 - 2 - 7
import re
from concurrent import futures
from pathlib import Path
import copy
import yaml
from .VirtualFile import ImageFile, RawFile
from ..Util import Config, to_list
try:
from ... | 2.203125 | 2 |
2015/Day6.py | trajkan/AdventOfCode | 0 | 12782239 | <filename>2015/Day6.py
""" Day 6: Probably a fire hazard """
import json
import re
with open('input_d6.txt') as f:
data = f.readlines()
lights_grid = []
for x in range(1000):
for y in range(1000):
lights_grid.append([x, y, 0])
xy_regex = re.compile(r'([0-9,]*) through ([0-9,]*)')
# action = ''
for ins... | 3.140625 | 3 |
python/beginner/sum-earnings_ljsauer.py | saumyasingh048/hacktoberithms | 16 | 12782240 | <filename>python/beginner/sum-earnings_ljsauer.py
"""
Challenge: Write a function that accepts a comma-separated
string input of earning/spending activity and returns the sum
of earning as a single int value.
Requirements: If input is empty or invalid, return 0; if spending
(negative values) is greater than earning d... | 3.984375 | 4 |
src/single_byte_cipher.py | kaltsimon/crypto-challenges | 0 | 12782241 | <filename>src/single_byte_cipher.py
"""Decrypt a message that was XOR'd against a single character."""
from encode_decode import decode_hex
from fixed_xor import xor
import requests
from operator import itemgetter
def xor_with_char(bytes, char):
"""XOR a sequence of bytes with a single character."""
return x... | 3.640625 | 4 |
itscsapp/research/apps.py | danyRivC/itscsapp | 0 | 12782242 | from django.apps import AppConfig
class ResearchConfig(AppConfig):
name = "itscsapp.research"
verbose_name = "Research"
| 1.148438 | 1 |
modules/losses.py | michael-iuzzolino/CascadedDistillation | 0 | 12782243 | <gh_stars>0
"""Custom losses."""
import torch
import torch.nn as nn
def categorical_cross_entropy(pred_logits, y_true_softmax):
"""Categorical cross entropy."""
log_softmax_pred = nn.LogSoftmax(dim=1)(pred_logits)
soft_targets = y_true_softmax.detach().clone() # Stop gradient
cce_loss = -(soft_targets * log_... | 2.328125 | 2 |
tests/continuous_integration/test_05_network.py | simonvh/ANANSE | 0 | 12782244 | import os
import numpy as np
import pytest
from ananse.network import Network
from .test_02_utils import write_file
@pytest.fixture
def binding_fname():
return "tests/example_data/binding2.tsv"
@pytest.fixture
def network():
genome = "tests/data/genome.fa"
if not os.path.exists(genome):
write_... | 2.125 | 2 |
setup.py | zhouxiexuan/pDeep3 | 10 | 12782245 | import setuptools
from configparser import ConfigParser
from pkg_resources import parse_version
from sys import platform
assert parse_version(setuptools.__version__) >= parse_version('36.2')
config = ConfigParser(delimiters=['='])
config.read('settings.ini')
cfg = config['DEFAULT']
license_options = {
'apache2': ... | 2.25 | 2 |
utils/aes_test.py | aidan-lane/MastersProject | 0 | 12782246 | <filename>utils/aes_test.py
"""Unittest for aes.py
"""
import unittest
import random
import string
from os.path import exists
import string
from utils import aes
class TestAes(unittest.TestCase):
def test_key_gen(self):
""" Test AES private key generation
"""
# Test default (32 bytes)
... | 2.9375 | 3 |
awx/sso/urls.py | gitEdouble/awx | 17 | 12782247 | <gh_stars>10-100
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
from django.conf.urls import url
from awx.sso.views import (
sso_complete,
sso_error,
sso_inactive,
saml_metadata,
)
app_name = 'sso'
urlpatterns = [
url(r'^complete/$', sso_complete, name='sso_complete'),
url(r'^error... | 1.507813 | 2 |
ShopperMiles/products/migrations/0001_initial.py | juansahe/shoppy | 0 | 12782248 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-06-28 20:54
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('providers', '0001_initial'),
]
... | 1.648438 | 2 |
104_manejoCadenas/funcionSorted.py | josuerojasq/netacad_python | 0 | 12782249 | #La función "sorted()" toma un argumento (una lista) y devuelve una nueva lista,
# con los elementos ordenados del argumento.
# Demostración de la función sorted()
firstGreek = ['omega', 'alfa', 'pi', 'gama']
firstGreek2 = sorted(firstGreek)
print(firstGreek)
print(firstGreek2)
print()
lista1 = ['T', 'e', 'x', 't', '... | 4.15625 | 4 |
src/scrawl/moves/text.py | astromancer/graphical | 0 | 12782250 | import matplotlib.pyplot as plt
from matplotlib.text import Text
class DragHandler(object):
# NOTE: DOES NOT HANDLE TEXT WITH ARBITRARY TRANSFORMS!!!!
"""
A simple class to handle Drag n Drop.
This is a simple example, which works for Text objects only
"""
def __init__(self, figure=None):
... | 3.84375 | 4 |