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 |
|---|---|---|---|---|---|---|
utils/base.py | vietnamican/mmdetection | 0 | 44000 | from typing import Dict, Iterable, List, Optional, Union
from functools import partial
import torch
import torch.nn as nn
from torch.nn import functional as F
import pytorch_lightning as pl
class BaseException(Exception):
def __init__(
self,
parameter,
types: List):
me... | 2.390625 | 2 |
SolarCalculator/PdfCreator/jsonipy.py | Ouzx/SolarCalculator | 0 | 44001 | <reponame>Ouzx/SolarCalculator<filename>SolarCalculator/PdfCreator/jsonipy.py
import json
ex_data = {
"info": {
"system_name": "<NAME>",
"location": "1232154.4464, 564654615.4652456"
},
"element_1": {
"yearly_revenue": "$18.488,88",
"pay_off_time": "4 Yıl",
"investme... | 2.0625 | 2 |
pychemia/__init__.py | quanshengwu/PyChemia | 1 | 44002 | <filename>pychemia/__init__.py
"""
PyChemia is a python library for automatize atomistic-level calculations. The library provide an API to manipulate
structures, store structures and properties in a Mongo database, search for new structures of a given composition,
interact with several atomistic simulation codes and vi... | 2.484375 | 2 |
maasaic/apps/users/managers.py | fceruti/maasaic | 0 | 44003 | <filename>maasaic/apps/users/managers.py
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
"""
A custom user manager to deal with emails as unique identifiers for auth
instead of usernames. The default that's used is "UserManager"
"""
def create_user(self, ... | 2.90625 | 3 |
molecule/alertmanager-latest/tests/test_alertmanager-latest.py | atosatto/ansible-alertmanager | 2 | 44004 | <reponame>atosatto/ansible-alertmanager
import os
import re
from github import Github
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
gh = Github(os.getenv('GITHUB_API_TOKEN', None))
am_last_release = re... | 1.976563 | 2 |
tkinter/scrolled-frame-canvas/scrolledframe.py | whitmans-max/python-examples | 140 | 44005 | import tkinter as tk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scr... | 3.15625 | 3 |
goaway/objecthandle.py | anpere/goaway | 0 | 44006 | import logging
import goaway.globalvars as globalvars
logger = logging.getLogger(__name__)
DATA_STORE_HANDLE_KIND_ATTR = "__store"
NAME_ATTR = "__name"
class ObjectHandle(object):
"""
Represents a shared object in a datstore.
Instances of this class are returned by object handle constructors.
Applic... | 2.953125 | 3 |
wax/modules/mask_std_test.py | eserie/wax-ml | 42 | 44007 | <reponame>eserie/wax-ml<filename>wax/modules/mask_std_test.py
# Copyright 2021 The WAX-ML Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICEN... | 1.875 | 2 |
dcc.py | CRVV/dcc | 0 | 44008 | import os
import mimetypes
import chardet
UTF8 = ('utf-8', 'ascii')
WANTED_CHARSET = UTF8
FILE_PATH = '.'
THRESHOLD = 0.6
# Chardet cannot recognize ISO-8859-1 charset.
RECOGNIZE_8859_2_AS_8859_1 = True
LOG_FILE_CONVERTED = '/dcclog/converted'
LOG_FILE_UNCONVERTED = '/dcclog/unconverted'
LOG_FILE_CAN_NOT_DETECT = '/... | 2.390625 | 2 |
setup.py | JotaSe/text2emotion-library | 30 | 44009 | <gh_stars>10-100
from setuptools import setup, find_packages
def readme():
with open('README.md', encoding="utf8") as f:
README = f.read()
return README
setup(
name="Text2Emotion",
version="0.0.1",
description="Detecting emotions behind the text, Text2Emotion package will hel... | 1.859375 | 2 |
Repaso Examenes/enero2015/enero2015backtracking.py | Mi7ai/Algoritmia | 0 | 44010 | <gh_stars>0
from Utils.bt_scheme import BacktrackingVCSolver, PartialSolutionWithVisitedControl
def solver(C, A, B):
class PartialSolution(BacktrackingVCSolver):
def __init__(self, ds, SA, SB):
self.ds = ds
self.n = len(ds)
self.SA = SA
self.SB = SB
def is_solution(self):
return self.n == len(C) ... | 3.125 | 3 |
build/render/html/components.py | eimfach/robingruenke.com | 0 | 44011 | <gh_stars>0
from calendar import month_abbr
from os import getcwd
from re import findall, search, split
import numpy
def pagehero(doc, introduction, topic, author, website, enable_subscriptions=False):
with doc.tag("div", klass="heading-container"):
with doc.tag("h1", klass="content-heading", id="pagetitl... | 2.6875 | 3 |
bin/Lib/test/test_asyncio/__init__.py | yousafsyed/casperjs | 36 | 44012 | import os
import sys
import unittest
from test.support import run_unittest, import_module
# Skip tests if we don't have threading.
import_module('threading')
# Skip tests if we don't have concurrent.futures.
import_module('concurrent.futures')
def suite():
tests = unittest.TestSuite()
loader = unittest.TestL... | 2.265625 | 2 |
blog/apps.py | suryakc/django-rest-api | 0 | 44013 | """ Blog App """
from django.apps import AppConfig
class BlogConfig(AppConfig):
""" Blog config """
default_auto_field = 'django.db.models.BigAutoField'
name = 'blog'
| 1.46875 | 1 |
accounts/views.py | omid-taj/Deepfake-Detection-Website | 1 | 44014 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
# Create your views here.
from django.views.generic import View
... | 2.265625 | 2 |
text_studio/pipeline.py | tevnpowers/thesis | 2 | 44015 | <filename>text_studio/pipeline.py
"""Sequence of text processing components.
A text processing pipeline is a sequence of text processing components,
namely text_studio.Annotator and text_studio.Action objects that are
executed in order to produce newly annotated data and/or insights.
"""
from collections import Ordere... | 3.28125 | 3 |
pe-solution/src/main/python/pep_206.py | filippovitale/pe | 0 | 44016 | <gh_stars>0
"""
Concealed Square
Problem 206
Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
where each “_” is a single digit.
"""
from math import sqrt
from common import is_square
def solve(mask: str):
# digits = len(mask)
# ceiling = (10 ** digits) ** 2
for n in range(1... | 3.359375 | 3 |
python/matrix/matrix.py | jjkeyser/exercism | 0 | 44017 | class Matrix:
def __init__(self, matrix_string):
self.row_string = matrix_string.splitlines()
self.matrix = [[int(num) for num in row.split()] for row in self.row_string]
def row(self, index):
return self.matrix[index -1]
def column(self, index):
return [row[index -1] for r... | 3.390625 | 3 |
EduKTM/GKT/GKTNet.py | fannazya/EduKTM | 0 | 44018 | <gh_stars>0
# coding: utf-8
# 2022/3/1 @ fannazya
__all__ = ["GKTNet"]
import json
import networkx as nx
import torch
from torch import nn
import torch.nn.functional as F
from EduKTM.utils import GRUCell, begin_states, get_states, expand_tensor, \
format_sequence, mask_sequence_variable_length
class GKTNet(nn.Mo... | 2.390625 | 2 |
trace/trace.py | slash-segmentation/DP2 | 0 | 44019 | from data_viewer import *
from volume3d_util import *
from contour_processing import *
import cv
from best_path import *
inputStack = "o:\\images\\neuropil\\seg"
outputFolder = "o:\\trace_output"
box = Box()
box.cornerA = [0, 0, 200]
box.cornerB = [700, 500, 210]
v = loadImageStack(inputStack, box)
writeStack(outpu... | 2.453125 | 2 |
amfe/num_exp_toolbox.py | c-meyer/github-spielwiese | 0 | 44020 | <filename>amfe/num_exp_toolbox.py
# Copyright (c) 2017, Lehrstuhl fuer Angewandte Mechanik, Technische
# Universitaet Muenchen.
#
# Distributed under BSD-3-Clause License. See LICENSE-File for more information
#
"""
Numerical Experiments Toolbox.
Example
-------
"""
__all__ = ['apply_async']
try:
import dill
ex... | 2.921875 | 3 |
chiya/cogs/commands/reminder.py | Kadantte/chiya | 3 | 44021 | <filename>chiya/cogs/commands/reminder.py
import asyncio
import logging
import discord
from discord.commands import Option, SlashCommandGroup, context, slash_command
from discord.ext import commands
from chiya import config, database
from chiya.utils import embeds
from chiya.utils.helpers import get_duration
from chi... | 2.484375 | 2 |
ijal_interlinear/line.py | davidjamesbeck/IJAL-interlinear | 0 | 44022 | import pandas as pd
from xml.etree import ElementTree as etree
from pprint import pprint
from yattag import *
import pdb
#------------------------------------------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#----------------------------------------------------... | 2.5625 | 3 |
amazonmusic/genre.py | matt2005/amazon-music | 5 | 44023 | """
Genre class
"""
class Genre(object):
"""
Represents a genre for MyMusic
Key properties are:
* `id` - ID of the artist (Amazon ASIN)
* `name` - Artist name.
* `coverUrl` - URL containing cover art for the artist.
* `genre` - Genre of the album.
* `rating` - Average review score (ou... | 3.125 | 3 |
src/dl_plus/__main__.py | un-def/dl-plus | 30 | 44024 | from dl_plus.cli import main
main()
| 1.078125 | 1 |
tests/conftest.py | marqov/procrastinate | 0 | 44025 | <filename>tests/conftest.py<gh_stars>0
import os
import signal as stdlib_signal
from contextlib import closing
import aiopg
import psycopg2
import pytest
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from procrastinate import aiopg_connector
from procrastinate import app as app_m... | 2.171875 | 2 |
mrp_system/models.py | mgeorge8/django_time | 1 | 44026 | <gh_stars>1-10
from django.db import models
import datetime
#from django.contrib.sites.models import Site
class Vendor(models.Model):
TYPE_CHOICES = (
('manufacturer', 'manufacturer'),
('distributor', 'distributor'),
)
name = models.CharField(max_length=128, unique=True)
vendor_type... | 2.15625 | 2 |
testing/tests/test_dummy.py | MaurizioBella/BotyPy | 0 | 44027 | <gh_stars>0
# -*- coding: utf-8 -*-
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pytest
def sum(num1, num2):
"""It returns sum of two numbers"""
return num1 + num2
# make sure to start function name with test
@pytest.mark... | 3.4375 | 3 |
Data/Dataset.py | mrluin/SANet-PyTorch | 1 | 44028 | import torch
import numpy as np
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF
import torchvision.transforms as transforms
import random
import glob
import os
from PIL import Image
'''
require fix the random seeds
'''
# PotsdamDataset
rgb_means = [0.3366, 0.3599, 0.3333]
rgb_stds =... | 2.390625 | 2 |
autonetkit/design/ip_addressing/ipv4.py | ZhiHaoi/autonetkit | 91 | 44029 | import ipaddress
from collections import defaultdict
from autonetkit.design.utils import filters
from autonetkit.design.utils.general import group_by
from autonetkit.network_model.types import LAYER3_DEVICES
def assign_loopbacks(topology):
"""
@param topology:
"""
layer3_nodes = [n for n in topology... | 2.515625 | 3 |
Lab 6/2_isSquare.py | Hubert-HD/Lab_ADA | 0 | 44030 | """ Ejercicio 1 """
def isSquare(num):
"""" Devuelve verdadero si el número es un cuadrado, caso contrario devuelve falso """
start = 1
end = num
while start <= end:
mid = int(start + (end - start) / 2)
square = mid * mid
if square == num:
return True
if square > num:
en... | 3.796875 | 4 |
GRND/NCTRS.py | STRATOLOGIC/SpacePyLibrary | 22 | 44031 | #******************************************************************************
# (C) 2018, <NAME>, Austria *
# *
# The Space Python Library is free software; you can redistribute it and/or *
# modif... | 1.679688 | 2 |
variants/migrations/0047_auto_20190701_1625.py | brand-fabian/varfish-server | 14 | 44032 | <filename>variants/migrations/0047_auto_20190701_1625.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-07-01 16:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("variants",... | 1.390625 | 1 |
team_9/cocos/utest/pyglet_mockup1/pyglet/resource/__init__.py | Donnyvdm/dojo19 | 1 | 44033 | from __future__ import division, print_function, unicode_literals
path = []
def reindex(*args,**kwargs):
pass
| 1.554688 | 2 |
runintervals/src/runintervals/app.py | rachelkelly/intervals | 0 | 44034 | """
Run Intervals. Takes 3 values from user, counts down intervals.
wanted: Data class that holds state
"""
from datetime import timedelta
import time
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
class RunIntervals(toga.App):
"""
__init__ values in __init__.py:
runsNu... | 3.359375 | 3 |
docker/predictor/models/neural_network.py | MaximAdler/Cryptocurrency-Price-Prediction | 2 | 44035 | <reponame>MaximAdler/Cryptocurrency-Price-Prediction<filename>docker/predictor/models/neural_network.py
import pandas as pd
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.layers import LSTM
from keras.layers import Dropout
from ut... | 2.890625 | 3 |
course_selection/migrations/0021_auto_20150905_0817.py | PrincetonUSG/ReCal | 13 | 44036 | <filename>course_selection/migrations/0021_auto_20150905_0817.py<gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0020_auto_20150903_0501'),
]
op... | 1.53125 | 2 |
utils.py | floschne/TERAN | 0 | 44037 | <filename>utils.py
from collections import OrderedDict
import numpy
from models.teran import TERAN
def get_model(config):
model = TERAN(config)
return model
def dot_sim(x, y):
return numpy.dot(x, y.T)
def cosine_sim(x, y):
x = x / numpy.expand_dims(numpy.linalg.norm(x, axis=1), 1)
y = y / nu... | 2.5625 | 3 |
mantrap/utility/shaping.py | simon-schaefer/mantrap | 7 | 44038 | <reponame>simon-schaefer/mantrap<filename>mantrap/utility/shaping.py
import torch
def check_ego_state(x: torch.Tensor, enforce_temporal: bool = False) -> bool:
assert not torch.any(torch.isnan(x))
if enforce_temporal:
assert x.size() == torch.Size([5])
else:
assert x.numel() in [4, 5]
... | 2.203125 | 2 |
cookbooks/imagery/files/default/za_ngi_50k_prepare_vrt.py | pnorman/chef | 91 | 44039 | <gh_stars>10-100
#!/usr/bin/env python
# The MIT License (MIT)
# Copyright (c) 2016 <NAME> (htonl)
# 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 limitati... | 2.015625 | 2 |
solutions/day_1/dayone.py | tylerkkp/adventofcode2020 | 0 | 44040 | # Advent of Code
# Day 1 Problem 1
import pandas as pd
nums = pd.read_csv('adventofcode2020_day1.csv')
numlist = nums.values.tolist()
flatList = [item for elem in numlist for item in elem]
for i in range(len(flatList)):
testnum = int(flatList[i])
neednum = 2020 - testnum
if neednum in flatList:
... | 3.640625 | 4 |
adv_cache_tag/tests/__init__.py | pgcd/django-adv-cache-tag | 29 | 44041 | from django import VERSION
if VERSION < (1, 6):
# Before django 1.6, Django was not able to find tests in tests/tests.py
from .tests import *
| 1.484375 | 1 |
motion_analysis/gui/widgets/__init__.py | gemlongman/motion_preprocessing_tool | 0 | 44042 | <reponame>gemlongman/motion_preprocessing_tool<gh_stars>0
from .animation_editor_widget import AnimationEditorWidget
from .animation_player_widget import AnimationPlayerWidget
from .blend_animation_controller_widget import BlendAnimationControllerWidget
from .character_widget import CharacterWidget
from .figure_contro... | 0.890625 | 1 |
sync.py | delanym/kala | 0 | 44043 | <filename>sync.py
# When does the synodic new moon come back to the same nakshatra. How many revolutions?
# By how many degrees does the new moon travel each synodic month? A: 29,105216732 degrees
# So in 12,368916655 months the new moon will have returned to the same sign, but it would
# have overshot or fallen short... | 3.359375 | 3 |
openbook_circles/validators.py | TamaraAbells/okuna-api | 164 | 44044 | <filename>openbook_circles/validators.py
from rest_framework.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from openbook_circles.models import Circle
def circle_id_exists(circle_id):
count = Circle.objects.filter(id=circle_id).count()
if count == 0:
raise ... | 2.25 | 2 |
classes_and_testsTest/DocumentationFromUnitTestsTestData/DataSet1_py_ClassFile.py | anconaesselmann/LiveUnit | 0 | 44045 | <reponame>anconaesselmann/LiveUnit<filename>classes_and_testsTest/DocumentationFromUnitTestsTestData/DataSet1_py_ClassFile.py
class DataClassFile():
def functionName1(self):
""" One Function (without parameters) with one test function (with single line comments)
where the documentation had not been ... | 2.171875 | 2 |
Python/Numpy/002_Shape_and_Reshape.py | o-silva-1/HackerRank | 0 | 44046 | <gh_stars>0
# https://www.hackerrank.com/challenges/np-shape-reshape/problem?h_r=next-challenge&h_v=zen
import numpy as np
arr = input().split(' ')
np_arr = np.array(arr, int)
np_arr.shape = (3, 3)
print(np_arr)
| 3.578125 | 4 |
dbus-sma/bms_test.py | madsci1016/SMAVenusDriver | 7 | 44047 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from bms_state_machine import BMSChargeStateMachine, BMSChargeModel, BMSChargeController
# 48V 16S LiFePO4 Battery
# Absorption: 58V (56.4 for longer life)
# Float: 54.4V
# Restart bulk voltage: Float-0.8 (max of 54V)
# Inverter Cut-off: 42.8V-48V (depending ... | 2.546875 | 3 |
geometry/eolearn/tests/test_morphology.py | dreampedia20/eo-learn | 1 | 44048 | <filename>geometry/eolearn/tests/test_morphology.py<gh_stars>1-10
"""
Credits:
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
This source code is licensed un... | 2.1875 | 2 |
ECUSimulation/components/base/message/abst_bus_message.py | arturmrowca/IVNS | 8 | 44049 | <filename>ECUSimulation/components/base/message/abst_bus_message.py
from components.base.automotive_component import AutomotiveComponent
import uuid
class AbstractBusMessage(AutomotiveComponent):
'''
This abstract class defines the interface of
a Bus Message
'''
MAX_DATAFIELD_SIZE = 0
... | 3.03125 | 3 |
mundo 1/029.py | thiagofreitascarneiro/Curso-de-Python---Curso-em-Video | 1 | 44050 | vel = int(input('digite a velocidade do carro:'))
multa = (vel - 80)*7
if vel>80:
print(f'MULTADO! você excedeu o limite permitido que é 80Km/h e vai pagar uma multa de {multa}')
| 3.703125 | 4 |
utils/errors.py | DiNitride/gafbot | 51 | 44051 | import discord
from discord.ext import commands
class UserBlacklisted(commands.CommandError):
"""
An exception when the user is blacklisted from the bot
"""
pass
| 2.390625 | 2 |
Tests/Methods/Simulation/test_Electrical.py | IrakozeFD/pyleecan | 2 | 44052 | # -*- coding: utf-8 -*-
import pytest
from numpy import pi
from os.path import join
from pyleecan.Classes.LamSlotWind import LamSlotWind
from pyleecan.Classes.SlotW11 import SlotW11
from pyleecan.Classes.WindingDW1L import WindingDW1L
from pyleecan.Classes.CondType12 import CondType12
from pyleecan.Functions.load impo... | 2.484375 | 2 |
gym_frozen_lake/learner.py | bemova/Q_reinforcement_learning | 1 | 44053 | import numpy as np
def random_policy(env):
counter = 0
total_rewards = 0
reward = None
rewardTracker = []
while reward != 1:
env.render()
state, reward, done, info = env.step(env.action_space.sample())
total_rewards += reward
if done:
rewardTracker.appen... | 2.65625 | 3 |
python/math/0008_string_to_integer.py | linshaoyong/leetcode | 6 | 44054 | <filename>python/math/0008_string_to_integer.py<gh_stars>1-10
class Solution(object):
def myAtoi(self, _str):
"""
:type str: str
:rtype: int
"""
valid = set(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'])
signs = set(['-', '+'])
ns = []
ss = _str.s... | 3.3125 | 3 |
tests/test_api.py | pinntech/pinn-python | 2 | 44055 | """
:copyright: (c) 2019 Pinn Technologies, Inc.
:license: MIT
"""
def test_import():
import pinn
def test_configuration_error():
import pinn
try:
pinn.User.create()
except pinn.errors.ConfigurationError:
pass
def test_authentication_error():
import pinn
pinn.secret_key = '... | 2.15625 | 2 |
brief/__init__.py | madre/PersonalWeb | 0 | 44056 | #coding=utf-8
"""
__create_time__ = '13-10-29'
__author__ = 'Madre'
"""
| 1.0625 | 1 |
dtreeviz/__init__.py | alitrack/dtreeviz | 1,905 | 44057 | <gh_stars>1000+
from .version import __version__
from dtreeviz.classifiers import clfviz
| 1.015625 | 1 |
frites/conn/conn_sliding_windows.py | StanSStanman/frites | 0 | 44058 | """Sliding windows for connectivity functions."""
from frites.io import set_log_level, logger
import numpy as np
def define_windows(times, windows=None, slwin_len=None, slwin_start=None,
slwin_stop=None, slwin_step=None, verbose=None):
"""Define temporal windows.
This function can be used... | 3.328125 | 3 |
solutions/347.top-k-frequent-elements/top-k-frequent-elements.py | wangsongiam/leetcode | 3 | 44059 | <gh_stars>1-10
import heapq
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
m = {}
for n in nums:
if n in m:
m[n] += 1
else:
m[n] = 0
... | 2.96875 | 3 |
squirrelfriends/utils/storage.py | jacobyxu/squirrel-and-friends | 2 | 44060 | <gh_stars>1-10
import numpy as np
import pandas as pd
import logging
def num2size(num, suffix="B"):
"""Convert byte num to formated size string.
"""
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /... | 3.109375 | 3 |
IRN/train.py | Barry-Menglong-Yao/conll2019-snopes-crawling | 1 | 44061 | <reponame>Barry-Menglong-Yao/conll2019-snopes-crawling
import os
import torch
import random
import numpy as np
from network.image_reconstrcution_network import ImageReconstrcutionNetwork
from trainer import ImageReconstrcutionTrainer
from util.config import Config
def init_seeds(seed=0):
#torch.manual_seed(seed)
... | 2.328125 | 2 |
Harvest_Actor-Critic/source/networks/utils.py | jbr-ai-labs/BAROCCO | 3 | 44062 | import torch
from torch import nn
from torch.autograd import Variable
from torch.distributions import Categorical
from torch.nn import functional as F
def classify(logits):
if len(logits.shape) == 1:
logits = logits.view(1, -1)
distribution = Categorical(F.softmax(logits, dim=1))
atn = distributio... | 2.53125 | 3 |
getproxies.py | saisyam/ebay-scraper | 0 | 44063 | <gh_stars>0
import requests
import sys
import json
from useragent import *
from bs4 import BeautifulSoup
def write_proxies(html):
f = open("proxies.txt", "w")
soup = BeautifulSoup(html, "html5lib")
table = soup.find("table", {'id':'proxylisttable'})
rows = table.find('tbody').find_all('tr')
for r i... | 2.78125 | 3 |
tests/core/actions/list_task_statuses/test_list_task_statuses_request.py | Himon-SYNCRAFT/taskplus | 0 | 44064 | from taskplus.core.actions import ListTaskStatusesRequest
def test_list_user_roles_request_without_parameters():
request = ListTaskStatusesRequest()
assert request.filters is None
assert request.is_valid() is True
def test_list_user_roles_request_with_empty_filters():
request = ListTaskStatusesRequ... | 2.5625 | 3 |
src/platform/c2rs.py | nanpuyue/nc | 0 | 44065 | #!/usr/bin/env python3
import os
import re
import sys
def main():
if len(sys.argv) != 2:
print("Usage: %s input-file" % sys.argv[0])
sys.exit(1)
macro_pattern = re.compile("#define\s+(\w+)\s+([a-zA-Z0-9_\-]+)\s*(.*)")
consts_pattern = re.compile("\s*([A-Z_0-9]+)\s*=\s*([0-9\-\.xXa-fA-F]+... | 2.984375 | 3 |
main.py | dusansimic/analiza-melanoma | 0 | 44066 | <reponame>dusansimic/analiza-melanoma
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import math
from plotting import *
from sys import argv
asymmetryDataList = []
borderDataList = []
hsvStdDevDataList = []
hsvMeansDataList = []
with open(argv[1], 'r') as csvfile:
for line in csvfile.readl... | 2.546875 | 3 |
libs/__init__.py | lianwutech/datasync | 1 | 44067 | <reponame>lianwutech/datasync
__author__ = 'daviddeng'
| 0.964844 | 1 |
benchmarks/call_benchmark.py | usalko/nogil | 1 | 44068 | <reponame>usalko/nogil
import time
# N = 1000
N = 1000000
UNROLL = 10
loop_delta = 2.0 * N * UNROLL / 1e9
def call0():
pass
def call2(a, b):
pass
def call4(a, b, c, d):
pass
def call4_dflt(a, b, c=3, d=4):
pass
def call_vararg(*args, **kwargs):
pass
def benchmark_loop():
# global loop_del... | 3.171875 | 3 |
assess_quality.py | brawer/PronunBot | 0 | 44069 | <gh_stars>0
#!/usr/bin/env python3
#
# Copyright (c) 2018 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
#
# Tool for assessing the quality of recorded pronunciations
#
# For each recorded phrase or word, this tool asks the user to assess
# (“vet”) the recorded pronunciations. After hearing all the available
# variant... | 2.90625 | 3 |
src/structure.py | WhiteRobe/DBVTranslator | 0 | 44070 | import xlwt
class DRIVER:
# An Interface
def parse(self, s):
return None # Return an tuple
class TABLE:
def __init__(self, sentence, driver):
self.comment, self.table_name, self.columns, self.engine, self.charset = driver.parse(sentence)
def output(self, xls):
bold_title = x... | 2.625 | 3 |
Python_version/elips.py | RomaniukVadim/ellipsometric-calculator | 0 | 44071 | #!/usr/env python3
import argparse
import math
def main():
parser = argparse.ArgumentParser(description='Ellipsometry calculator (console version).')
parser.add_argument("--x2", dest='zname', type=argparse.FileType('r'), help='specify zipfile')
parser.add_argument("-d", dest='dname', type=argparse.Fi... | 3.0625 | 3 |
tests/aliyun_iot_test.py | tenstone/xiaoyun-smart-speaker-server | 1 | 44072 | <filename>tests/aliyun_iot_test.py<gh_stars>1-10
# -*- coding: utf-8-*-
import unittest
import os
os.sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from app.components import logger
from app.components.aliyun_iot import IotServer
class TestComponentsAliyunIOT(unittest.TestCase):
"""
表格计算
... | 2.359375 | 2 |
sdk/python/pulumi_openstack/objectstorage/container_object.py | pulumi/pulumi-openstack | 34 | 44073 | <gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overlo... | 1.640625 | 2 |
Leetcode/Python Solutions/Depth-First Search/numberofDistinctIslands.py | Mostofa-Najmus-Sakib/Applied-Algorithm | 1 | 44074 | """
LeetCode Problem: 694. Number of Distinct Islands
Link: https://leetcode.com/problems/number-of-distinct-islands/
Language: Python
Written by: <NAME>
Time Complexity: O(n)
Space Complexity: O(n)
X => Start
O => Out of bound or water
U => Up
L => Left
R => Right
D => Down
"""
class Solution:
def computePa... | 3.734375 | 4 |
eyelab/views/ui/ui_layergroup_entry.py | MedVisBonn/eyelab | 0 | 44075 | <reponame>MedVisBonn/eyelab
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'ui_layergroup_entry.ui'
##
## Created by: Qt User Interface Compiler version 6.1.3
##
## WARNING! All changes made in this file will be lost when ... | 1.59375 | 2 |
ScriptConverter2/scriptConverter2.py | Darkttd/Editor-fo-Kirino-Engine | 2 | 44076 | <reponame>Darkttd/Editor-fo-Kirino-Engine
import os
import sys
import re
import openpyxl
if __name__ == "__main__":
if len(sys.argv) != 2:
print ('usage: python ' + sys.argv[0] + ' scriptName')
exit()
wb = openpyxl.load_workbook(sys.argv[1])
outputScript = None
for sheetname in wb.she... | 2.3125 | 2 |
codes/d_agents/off_policy/sac/sac_agent.py | linklab/link_rl | 0 | 44077 | <filename>codes/d_agents/off_policy/sac/sac_agent.py
# https://spinningup.openai.com/en/latest/algorithms/sac.html
# https://github.com/pranz24/pytorch-soft-actor-critic
# https://github.com/ku2482/soft-actor-critic.pytorch/blob/master/code/agent.py
# https://github.com/cyoon1729/Policy-Gradient-Methods/blob/master/sac... | 1.898438 | 2 |
chap12/download_xkcd.py | asadmoosvi/automate-the-boring-stuff-solutions | 0 | 44078 | <filename>chap12/download_xkcd.py
import requests, os, bs4
import logging
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.INFO)
url = 'https://xkcd.com'
os.makedirs('xkcd', exist_ok=True)
while True:
try:
limit = int(input('How many comics would you like to download? '))
... | 3.0625 | 3 |
UVa Online Judge/v2/271.py | mjenrungrot/algorithm | 1 | 44079 | <reponame>mjenrungrot/algorithm
# =============================================================================
# Author: <NAME> - https://github.com/mjenrungrot/
# FileName: 271.py
# Description: UVa Online Judge - 271
# ===========================================================================... | 3.640625 | 4 |
setup.py | Liam-Deacon/antlr4-vba-parser | 1 | 44080 | <reponame>Liam-Deacon/antlr4-vba-parser
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# type: ignore
"""Setup script for package."""
import os
import sys
import configparser
import datetime
import distutils.cmd
import distutils.log
import subprocess
import glob
import shutil
from pathlib import Path
setup_kwargs = {}... | 1.992188 | 2 |
IdeaProjects/matplotDev/matplotlibDev1.py | sinomiko/project | 1 | 44081 | <reponame>sinomiko/project<filename>IdeaProjects/matplotDev/matplotlibDev1.py
# encoding: utf-8
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#matplotlib inline
# 4.1. 一维数据集
#
# 在下面的所有例子中,我们将按照存储在 NumPy ndarray 对象中的数据绘制图表。当然,matplotlib 也能够按照以不同的 Python 格式存储的数据(如列表对象)绘制图表。首先,我们需要用于绘制图表的数据。为... | 2.796875 | 3 |
tests/test_storages.py | ghuinker/django-easy-tenants | 30 | 44082 | from django.core.files.uploadedfile import SimpleUploadedFile
from easy_tenants import tenant_context_disabled
from easy_tenants.storage import TenantFileSystemStorage
def test_default_storage(tenant_ctx, settings):
tenant_id = str(tenant_ctx.id)
s = TenantFileSystemStorage()
file = SimpleUploadedFile("t... | 2.125 | 2 |
tests/config.py | mizzy/maglica | 15 | 44083 | <filename>tests/config.py<gh_stars>10-100
# $ nosetests -v --rednose --with-coverage tests/config.py
from nose.tools import *
import maglica.config
def test_config_load():
config = maglica.config.load('etc/maglica.conf.example')
eq_(config.hosts[0], "host0.example.com")
eq_(config.hosts[1], "host1.exampl... | 1.820313 | 2 |
services/scope_external_service.py | projekt-scope/scope-admin | 2 | 44084 | # FIXME this class is not done yet
import logging
import platform
import subprocess
LOGGER = logging.getLogger("scope-admin")
class ScopeExternalService:
def __init__(self, tag, paramsDict):
self._tag = tag
self._name = paramsDict["name"]
self._description = paramsDict["description"]
... | 2.546875 | 3 |
pipelines/h1c/idr2/v1/bad_ants/H1C_IDR2_bad_ants.py | HERA-Team/hera_pipelines | 0 | 44085 | #!/usr/bin/env python
"""Script for producing bad_ants text files."""
JDs = [
2458098,
2458099,
2458101,
2458102,
2458103,
2458104,
2458105,
2458106,
2458107,
2458108,
2458109,
2458110,
2458111,
2458112,
2458113,
2458114,
2458115,
2458116,
245... | 2.84375 | 3 |
Health_Care_Unit/health_main.py | Swagnick99/YouCure | 7 | 44086 | <filename>Health_Care_Unit/health_main.py<gh_stars>1-10
from flask import Flask, render_template, Blueprint, url_for, request, redirect
from flask_login import login_required, current_user
from . import symptomsuggestion as symp
main = Blueprint("health_main", __name__)
found_symptoms = list()
dict_symp_tup = ... | 2.8125 | 3 |
DN/ioUtils.py | dendisuhubdy/dwt | 206 | 44087 | <filename>DN/ioUtils.py
import numpy as np
import skimage
import skimage.io
import scipy.io as sio
import skimage.transform
import sys
np.random.seed(0)
VGG_MEAN = [103.939, 116.779, 123.68]
def read_mat(path):
return np.load(path)
def write_mat(path, m):
np.save(path, m)
def read_ids(path):
return ... | 2.09375 | 2 |
dagmc_h5m_file_inspector/__init__.py | fusion-energy/dagmc_h5m_file_inspector | 0 | 44088 |
from .core import get_volumes_from_h5m
from .core import get_materials_from_h5m
from .core import get_volumes_and_materials_from_h5m
| 1.03125 | 1 |
tests/test_state.py | dexterous/celery-cloudwatch | 32 | 44089 | <reponame>dexterous/celery-cloudwatch<gh_stars>10-100
import unittest
from celery_cloudwatch.state import State
class TestPickleErrors(unittest.TestCase):
def assert_success(self, s, task_name):
self.assertEquals(s.task_event_sent[task_name], 1)
self.assertEquals(s.task_event_started[task_name], ... | 2.28125 | 2 |
main.py | impressive8/Practice | 197 | 44090 | # ===================================
# Import the libraries
# ===================================
import numpy as np
from matplotlib import pylab as plt
import imaging
import utility
import os,sys
# ===================================
# Which stages to run
# ===================================
do_add_noise = False
d... | 1.953125 | 2 |
coldsweat/fetcher.py | jeroenh/coldsweat | 106 | 44091 | # -*- coding: utf-8 -*-
'''
Description: the feed fetcher
Copyright (c) 2013—2016 <NAME>
Portions are copyright (c) 2013 <NAME>
License: MIT (see LICENSE for details)
'''
import sys, os, re, time, urlparse
from datetime import datetime
from peewee import IntegrityError
import feedparser
import requests
from requests... | 2.34375 | 2 |
app/repositories/BaseRepository.py | owlvey/owlvey_sre | 0 | 44092 | <filename>app/repositories/BaseRepository.py<gh_stars>0
from app.components.ConfigurationComponent import ConfigurationComponent
import mysql.connector
from app.core.BaseFrame import BaseFrame
class BaseRepository:
def __init__(self, configuration: ConfigurationComponent):
self._configuration = configura... | 2.09375 | 2 |
data/type_registry/__init__.py | wax911/anime-meta | 2 | 44093 | <reponame>wax911/anime-meta
from .type_registries import CoreEntityCodec, CacheLogEntityCodec, SigningPolicyEntityCodec, \
IndexEntityCodec, AdBreakEntityCodec, EpisodeEntityCodec, SeasonEntityCodec, SeriesEntityCodec, \
ImageContainerEntityCodec, MoviePanelEntityCodec, SearchMetaEntityCodec, SeriesPanelEntityC... | 0.8125 | 1 |
lib/project.py | IASamoylov/vk-photo-downloader | 0 | 44094 | <gh_stars>0
from .options import Options
from .os_wrapper import OSWrapper
from .photo_parser import PhotoParser
from .vk_api import Api as VK_api
class Project:
def __init__(self, options: Options):
"""
:param options: Parsed command-line arguments
"""
self.options = options
... | 2.671875 | 3 |
redis-py-pubsub/publisher.py | bhavyagaur99/learn-redis-python | 0 | 44095 | import redis
import time
import json
redis_host = 'localhost'
redis_port = '6379'
channel = "hello-channel"
publisher = redis.Redis(host=redis_host, port=redis_port)
count = 0
while True:
count += 1
message = {
'text': 'Hello World',
'count': count
}
publisher.publish(channel, json.du... | 2.59375 | 3 |
leo/modes/velocity.py | ATikhonov2/leo-editor | 1,550 | 44096 | # Leo colorizer control file for velocity mode.
# This file is in the public domain.
# Properties for velocity mode.
properties = {
"commentEnd": "*#",
"commentStart": "#*",
"lineComment": "##",
}
# Attributes dict for velocity_main ruleset.
velocity_main_attributes_dict = {
"default": "nu... | 1.6875 | 2 |
phanterpwa/interface/Admin/production.py | PhanterJR/phanterpwa | 2 | 44097 | <reponame>PhanterJR/phanterpwa
from phanterpwa.server import PhanterPWATornado
if __name__ == "__main__":
import os
projectPath = os.path.dirname(__file__)
print(projectPath)
AppRunv = PhanterPWATornado(projectPath)
try:
AppRunv.run()
except KeyboardInterrupt:
AppRunv.stop()
| 1.742188 | 2 |
Trojan.Android.GM/gmbot/apps/smsg_r/smsapp/admin_extra_views.py | 010001111/Vx-Suites | 2 | 44098 | import logging
from bson.objectid import ObjectId
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.translation import u... | 2.015625 | 2 |
phasing/utils/tag_bam_post_phasing.py | ArthurDondi/cDNA_Cupcake | 205 | 44099 | <reponame>ArthurDondi/cDNA_Cupcake
__author__ = "<EMAIL>"
"""
Tagging BAM files with phasing info
"""
import pysam
from csv import DictReader
def main(read_bam, hap_info, output_bam, celltype_file=None):
d = {}
celltype_info = {}
#for r in DictReader(open('phased.partial.cleaned.hap_info.txt'),delimiter... | 2.375 | 2 |