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 |
|---|---|---|---|---|---|---|
experiments/experiments_2/bs3_exp11_2_runner.py | petrroll/msc-neuro | 1 | 35000 | <filename>experiments/experiments_2/bs3_exp11_2_runner.py
import os
import sys
sys.path.append(os.getcwd())
import utils.runners as urun
#
# Dropout is `keep_prob` probability not `dropout rate` (as in TF2.x)
#
if __name__ == "__main__":
exp_folder = "experiments_2"
exp = "bs3_exp11"
exp_rev = "2"
r... | 2.125 | 2 |
library/aq6315.py | mjasperse/telepythic | 2 | 35001 | <gh_stars>1-10
"""
AQ6315E DATA EXTRACTOR
Extracts all visible traces from Ando AQ-6315E Optical Spectrum Analyser
Usage: ./aq6315.py [filename]
If specified, extracted data is saved to CSV called "filename"
Relevant list of commands available at
http://support.us.yokogawa.com/downloads/TMI/COMM/AQ6317B/AQ631... | 2.515625 | 3 |
src/test_uint8.py | disconnect3d/PicoBlade-asm | 4 | 35002 | from src.uint8 import uint8
def test_constructor1():
assert int(uint8(20)) == 20
def test_constructor2():
assert uint8(256) == uint8(0)
assert uint8(260) == uint8(4)
assert uint8(-1) == uint8(255)
assert uint8(-5) == uint8(251)
assert uint8(-5) != uint8(252)
def test_add_other():
asser... | 3.03125 | 3 |
tests/lid_driven_cavity/test.py | nazmas/SNaC | 0 | 35003 | <gh_stars>0
#!/usr/bin/env python
def test_ldc():
import numpy as np
import os
from read_single_field_binary import read_single_field_binary
data_ref = np.loadtxt("data_ldc_re1000.txt")
if "data_x" in os.getcwd():
data,xp,yp,zp,xu,yv,zw = read_single_field_binary("vey_fld_0001500.bin",np.arr... | 2.21875 | 2 |
zoom/_assets/standard_apps/icons/index.py | zodman/ZoomFoundry | 8 | 35004 | """
icons index
"""
import zoom
class MyView(zoom.View):
"""Index View"""
def index(self):
"""Index page"""
zoom.requires('fontawesome4')
content = zoom.tools.load('icons.html')
subtitle = 'Icons available as part of FontAwesome 4<br><br>'
return zoom.page(content,... | 2.609375 | 3 |
python/AI/data/zero_mean.py | Vahegian/GiantTrader | 10 | 35005 | <reponame>Vahegian/GiantTrader<gh_stars>1-10
'''
This script takes one 'npy' file that contains market data
of multiple markets and produces 3 files "train.npy", "test.npy", "val.npy".
The script calculates the mean image of the dataset and substracts it from
each image.
'''
import numpy as np
def save_file(dir, d... | 2.875 | 3 |
src/JobManager/Tasks.py | ROOSTER-fleet-management/rooster_fleet_manager | 6 | 35006 | <reponame>ROOSTER-fleet-management/rooster_fleet_manager<filename>src/JobManager/Tasks.py<gh_stars>1-10
#! /usr/bin/env python
import rospy
import actionlib
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from tf.transformations import quaternion_from_euler
from std_msgs.msg import UInt8
from enum import E... | 2.1875 | 2 |
user.py | sdress/dojo-users | 0 | 35007 | # import the function that will return an instance of a connection
from mysqlconnection import connectToMySQL
# model the class after the friend table from our database
class User:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['first_name']
self.last_name = data['l... | 3.515625 | 4 |
tiktokpy/client/user.py | returnWOW/tiktokpy | 1 | 35008 | <filename>tiktokpy/client/user.py
import os
import asyncio
from typing import List
import traceback
import pyppeteer
from pyppeteer.page import Page
from tqdm import tqdm
import pdb
import time
from tiktokpy.client import Client
from tiktokpy.utils.client import catch_response_and_store, catch_response_in... | 2.328125 | 2 |
amazon-top-results.py | dlameter/amazon-top-results | 0 | 35009 | <filename>amazon-top-results.py
import json
import time
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdr... | 2.71875 | 3 |
plugins/vpn.py | alobbs/autome | 0 | 35010 | import os
import plugin
import pluginconf
util = plugin.get("util")
FILE_COUNTER = "~/.vpn_counter"
FILE_VPN_SH = "~/.vpn_sh"
EXPECT_SCRIPT = """#!/usr/bin/expect
spawn {cmd}
expect -exact "Enter Auth Username:"
send -- "{user}\\n"
expect -exact "Enter Auth Password:"
send -- "{password}\\n"
interact
"""
class V... | 2.5625 | 3 |
jasypt4py/generator.py | fareliner/jasypt4py | 7 | 35011 | <gh_stars>1-10
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
from abc import ABCMeta, abstractmethod
from Crypto import Random
from jasypt4py.exceptions import ArgumentError
class PBEParameterGenerator(object):
__metaclass__ = ABCMeta
@staticmethod
de... | 2.984375 | 3 |
__init__.py | zznop/bn-kconfig-recover | 18 | 35012 | <filename>__init__.py
"""
Binary Ninja plugin for recovering kernel build configuration settings using BNIL
"""
import argparse
import logging
from binaryninja import (BinaryViewType, BinaryView, PluginCommand,
SaveFileNameField, get_form_input, BackgroundTaskThread)
class RecoverKConfigBackg... | 2.25 | 2 |
openapi_core/schema/operations/exceptions.py | grktsh/openapi-core | 0 | 35013 | <filename>openapi_core/schema/operations/exceptions.py
from openapi_core.schema.exceptions import OpenAPIMappingError
class OpenAPIOperationError(OpenAPIMappingError):
pass
class InvalidOperation(OpenAPIOperationError):
pass
| 1.585938 | 2 |
rlkit/envs/non_mujoco_half_cheetah_vel.py | hammer-wang/FOCAL-ICLR | 24 | 35014 | <gh_stars>10-100
import numpy as np
from gym import spaces
from gym import Env
#from rlkit.envs.mujoco.half_cheetah import HalfCheetahEnv
from rlkit.envs import register_env
@register_env('cheetah-vel')
class HalfCheetahVelEnv(Env):
def __init__(self, task={}, n_tasks=2, randomize_tasks=True, max_epi... | 2.46875 | 2 |
src/openprocurement/planning/api/validation.py | pontostroy/api | 3 | 35015 | # -*- coding: utf-8 -*-
from openprocurement.api.validation import (
validate_json_data,
validate_data,
validate_accreditation_level,
validate_accreditation_level_mode,
)
from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents
from openprocurement.planning.a... | 2.125 | 2 |
Ago-Dic-2020/Ejemplos/clase-2.py | bryanbalderas/DAS_Sistemas | 41 | 35016 | # Importando librerías
from numpy import array
# Listas y arreglos
a = array(['h', 101, 'l', 'l', 'o'])
x = ['h', 101, 'l', 'l', 'o']
print(a)
print(x)
print("Tamaño: ", len(x))
# Condicionales
if isinstance(x[1], int):
x[1] = chr(x[1])
elif isinstance(x[1], str):
pass
else:
raise TypeError("Tipo no sop... | 3.734375 | 4 |
constants.py | lanthony42/Snek | 0 | 35017 | <gh_stars>0
import math
SCREEN_WIDTH = 1400
SCREEN_HEIGHT = 800
TEXT = (5, 5)
FPS = 60
BASE_SIZE = 10
EYE_SIZE = 4
PUPIL_SIZE = EYE_SIZE - 2
BASE_SPEED = 2
MIN_DISTANCE = 1
MAX_DISTANCE = MIN_DISTANCE + 3
SIZE_INC = 15
EYE_INC = SIZE_INC * 4
PUPIL_INC = SIZE_INC * 8
GROWTH_INC = SIZE_INC * 20
BOOST_MIN = 10
BOOST_FA... | 2.609375 | 3 |
app/routers/auth.py | nicolunardi/travela-server | 0 | 35018 | <reponame>nicolunardi/travela-server<gh_stars>0
from fastapi import APIRouter, Depends, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.controllers.authControllers import login_user, register_user
from app.schemas.users import UserCreate
from app.schemas.tokens ... | 2.34375 | 2 |
clib/links/model/recognition/vggnet.py | Swall0w/clib | 1 | 35019 | import chainer
import chainer.functions as F
import chainer.links as L
class VGGNet(chainer.Chain):
"""
VGGNet
- It takes (224, 224, 3) sized image as imput
"""
def __init__(self, n_class=1000):
super(VGGNet, self).__init__()
with self.init_scope():
self.conv1_1 = L.C... | 2.875 | 3 |
scraper.py | TheLady/say_what | 0 | 35020 | import sqlite3
import requests
from bs4 import BeautifulSoup
from login import keys
import config
ARTICLE_SEARCH_URL = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key={key}'
SUNLIGHT_CONGRESS_URL = 'http://congress.api.sunlightfoundation.com/{method}?{query}&apikey={key}'
def get_json(url):
ret... | 2.984375 | 3 |
beatsaver/entity/MapTestplay.py | jundoll/bs-api-py | 0 | 35021 | <gh_stars>0
# load modules
from dataclasses import dataclass
from typing import Union
from ...beatsaver.entity import UserDetail
# definition class
@dataclass(frozen=True)
class MapTestplay:
createdAt: str
feedback: str
feedbackAt: str
user: Union[UserDetail.UserDetail, None]
video: str
# defi... | 2.90625 | 3 |
django_settings_diff/cli.py | GreenBankObservatory/django-settings-diff | 0 | 35022 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""docstring"""
from __future__ import print_function, unicode_literals
import argparse
import sys
from .settingsdiff import dump_settings, diff_settings
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"settings_path_1",
nar... | 2.578125 | 3 |
Project 1-1/evaluate.py | marridG/2020-EI339_Team_Project | 0 | 35023 | <filename>Project 1-1/evaluate.py<gh_stars>0
import os
import types
import typing
import numpy as np
import constants
import environment
import policy
import update
class EvaluateEnv:
def __init__(self, show_details: bool = True):
self.env_obj = environment.Easy21Env()
self.show_details = show_de... | 2.546875 | 3 |
axelrod/tests/unit/test_mock_player.py | dashiellfryer/Axelrod | 0 | 35024 | <reponame>dashiellfryer/Axelrod
import unittest
from axelrod import Action, MockPlayer, Player
C, D = Action.C, Action.D
class TestMockPlayer(unittest.TestCase):
def test_strategy(self):
for action in [C, D]:
m = MockPlayer(actions=[action])
p2 = Player()
self.assertE... | 2.953125 | 3 |
covidtracker/writer_flatcurve.py | mfkasim91/covid19-gradient-tracker | 2 | 35025 | <reponame>mfkasim91/covid19-gradient-tracker<filename>covidtracker/writer_flatcurve.py
import os
import datetime
import numpy as np
from jinja2 import Template
from scipy.stats import hypergeom
import matplotlib.pyplot as plt
import covidtracker as ct
from covidtracker.dataloader import DataLoader
from covidtracker.mod... | 2.125 | 2 |
SNDG/BioMongo/Model/exceptions.py | ezequieljsosa/sndg-bio | 0 | 35026 | '''
Created on Jun 15, 2016
@author: eze
'''
class NotFoundException(Exception):
'''
classdocs
'''
def __init__(self, element):
'''
Constructor
'''
self.elementNotFound = element
def __str__(self, *args, **kwargs):
return "NotFoundException(%s)" %... | 2.890625 | 3 |
Strings/tablePrinter.py | shoalcellos/AutomateTheBoringStuff | 0 | 35027 | <gh_stars>0
# Solution to the practise problem
# https://automatetheboringstuff.com/chapter6/
# Table Printer
def printTable(tableList):
"""Prints the list of list of strings with each column right justified"""
colWidth = 0
for row in tableList:
colWidth = max(colWidth, max([len(x) for x in ro... | 4.03125 | 4 |
src/layers/layers.py | jabalazs/gating | 10 | 35028 | import torch
import torch.nn as nn
from ..utils.torch import pack_forward
from .pooling import GatherLastLayer
class CharEncoder(nn.Module):
FORWARD_BACKWARD_AGGREGATION_METHODS = ["cat", "linear_sum"]
def __init__(
self,
char_embedding_dim,
hidden_size,
char_fw_bw_agg_method... | 2.359375 | 2 |
backend/handlers/graphql/mutation_utils/mutationmethod.py | al-indigo/vmemperor | 0 | 35029 | import json
import uuid
from dataclasses import dataclass
from typing import Callable, Sequence, Any, Optional, Tuple, Union, List, Generic, TypeVar
from serflag import SerFlag
from handlers.graphql.graphql_handler import ContextProtocol
from handlers.graphql.utils.string import camelcase
from xenadapter.task import ge... | 2.015625 | 2 |
infra/utils.py | BrandoZhang/alis | 176 | 35030 | <filename>infra/utils.py<gh_stars>100-1000
import os
import shutil
import subprocess
from distutils.dir_util import copy_tree
from shutil import copyfile
from typing import List, Optional
import click
import git
from omegaconf import DictConfig
def copy_objects(target_dir: os.PathLike, objects_to_copy: List[os.PathL... | 2.328125 | 2 |
App/templatetags/app_extras.py | kholdarbekov/Petrol | 0 | 35031 | from django import template
from django.utils import timezone
register = template.Library()
@register.filter
def sold(oil, delta_months='12'):
total = 0
curTime = timezone.localtime(timezone.now())
from_time = curTime - timezone.timedelta(days=int(delta_months)*30)
for t in oil.trades.filter(dateTime... | 2.109375 | 2 |
tests/sdk/test_util.py | unparalleled-js/py42 | 1 | 35032 | from datetime import datetime
import py42.util as util
def test_convert_timestamp_to_str_returns_expected_str():
assert util.convert_timestamp_to_str(235123656) == "1977-06-14T08:07:36.000Z"
def test_convert_datetime_to_timestamp_str_returns_expected_str():
d = datetime(2020, 4, 19, 13, 3, 2, 3)
assert... | 3.265625 | 3 |
heartrate.py | mtimkovich/python-fitbit | 0 | 35033 | <gh_stars>0
#!/usr/bin/env python
"""Script for fetching my min and max heart rate over the past 15 minutes."""
import time
from config import *
from gather_keys_oauth2 import OAuth2Server
if __name__ == '__main__':
server = OAuth2Server(client_id, client_secret)
server.browser_authorize()
fb = server.fi... | 2.953125 | 3 |
wienerschnitzelgemeinschaft/src/Dmytro/src/train_triplet.py | guitarmind/HPA-competition-solutions | 0 | 35034 | import argparse
import collections
import os
import cv2
import numpy as np
import pandas as pd
import pretrainedmodels
import torch
import torch.optim as optim
import torchsummary
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torchvision import datasets, models, transforms
from tqdm... | 2 | 2 |
tools/armature.py | kayteh/cats-blender-plugin | 3 | 35035 | <gh_stars>1-10
# MIT License
# Copyright (c) 2017 GiveMeAllYourCats
# 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, co... | 1.507813 | 2 |
lentil/fourier.py | andykee/lentil | 6 | 35036 | import functools
import numpy as np
def dft2(f, alpha, npix=None, shift=(0, 0), offset=(0, 0), unitary=True, out=None):
"""Compute the 2-dimensional discrete Fourier Transform.
This function allows independent control over input shape, output shape,
and output sampling by implementing the matrix triple p... | 3.671875 | 4 |
setup.py | db48x/flask-digest | 8 | 35037 | <gh_stars>1-10
from setuptools import setup, find_packages
setup(
name = 'Flask-Digest',
version = '0.2.1',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/vctandrade/flask-digest',
description = 'A RESTful authentication service for Flask applications',
long_descri... | 1.304688 | 1 |
model/contact.py | tarsic99/Python-training- | 0 | 35038 | <reponame>tarsic99/Python-training-
class Contact:
def __init__(self, first_name = None, last_name = None, mobile_phone = None):
self.first_name = first_name
self.last_name = last_name
self.mobile_phone = mobile_phone | 2.8125 | 3 |
src/mrnet/stochastic/kmc.py | kamronald/mrnet | 0 | 35039 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import N_A
from numba import jit
import copy
__author__ = "<NAME>, <NAME>, <NAME>"
__email__ = "<EMAIL>"
__copy... | 2.953125 | 3 |
Testing/Python/TestLinearOrthotropicMaterial.py | Numerics88/vtkbone | 3 | 35040 | <reponame>Numerics88/vtkbone<gh_stars>1-10
from __future__ import division
import sys
import numpy
from numpy.core import *
import vtk
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
import vtkbone
import traceback
import unittest
class TestLinearOrthotropicMaterial (unittest.TestCase):
def test_is... | 1.976563 | 2 |
hailo_model_zoo/datasets/create_kitti_depth_tfrecord.py | markgrobman/hailo_model_zoo | 2 | 35041 | <reponame>markgrobman/hailo_model_zoo
#!/usr/bin/env python
import os
import argparse
import tensorflow as tf
import numpy as np
from PIL import Image
def _int64_feature(values):
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=va... | 2.640625 | 3 |
tellurium/notebooks/__init__.py | kirichoi/tellurium | 73 | 35042 | """
notebook imports
"""
from __future__ import absolute_import
import warnings
import ipywidgets
import IPython
from .notebooktools import *
from .ontologysearch import OntologySearch
from .parameterslider import ParameterSlider
from .speciessearch import SearchBySpeciesForm
# except ImportError:
# warnings.war... | 1.390625 | 1 |
fashion/warehouse/fashion.core/xform/generateJinja2.py | braddillman/fashion | 1 | 35043 | '''
Created on 2018-12-21
Copyright (c) 2018 <NAME>
Generate code from a model and a jinja2 template.
'''
import logging
from pathlib import Path
from jinja2 import FileSystemLoader, Environment
from jinja2.exceptions import TemplateNotFound
from munch import munchify
from fashion.mirror import Mirror
# Module l... | 2.328125 | 2 |
algorithm/821.py | ChuangbinWang/leetcode | 0 | 35044 | <gh_stars>0
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
pl = []
ret = [0] * len(S)
for i in range(0, len(S)):
if S[i] == C:
pl.append(i)
for... | 3.21875 | 3 |
_solved/_solutions/visualization_02_seaborn14.py | jorisvandenbossche/ICES-python-data | 1 | 35045 | <reponame>jorisvandenbossche/ICES-python-data
# Optional solution with tidy data representation (providing x and y)
monthly_victim_counts_melt = monthly_victim_counts.reset_index().melt(
id_vars="datetime", var_name="victim_type", value_name="count"
)
sns.relplot(
data=monthly_victim_counts_melt,
x="dateti... | 2.8125 | 3 |
Grokking-Algorithms/Selection_Sort.py | AzuLiu/Algorithms-by-Python | 1 | 35046 | def findSmallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
newarr = []
for i in range(len(arr)):
smallest... | 4 | 4 |
library/source1/mdl/structs/__init__.py | anderlli0053/SourceIO | 199 | 35047 | from ....utils.byte_io_mdl import ByteIO
from ....shared.base import Base | 1.085938 | 1 |
web2py-appliances-master/VideoLibrary/languages/it.py | wantsomechocolate/WantsomeBeanstalk | 4 | 35048 | {
'Hello World':'<NAME>',
'Welcome to web2py':'Ciao da wek2py',
}
| 1.125 | 1 |
rtmBot/izyrtm_prop.py | izyrtm/izyrtm-server | 1 | 35049 | domain='https://monbot.hopto.org'
apm_id='admin'
apm_pw='New<PASSWORD>!'
apm_url='https://monbot.hopto.org:3000'
db_host='monbot.hopto.org'
db_user='izyrtm'
db_pw='<PASSWORD>!'
db_datadbase='monbot' | 0.820313 | 1 |
get_pos_data.py | chinnadhurai/lm-context-analysis | 42 | 35050 | import sys
if len(sys.argv) < 2:
print('Need the dataset name!')
exit(0)
for split in ['train', 'valid', 'test']:
with open('data/'+sys.argv[1]+'/'+split+'.txt', 'r') as f1, open(
'data/'+sys.argv[1]+'_pos_only/'+split+'.txt', 'r') as f2, open(
'data/'+sys.argv[1]+'_pos/'+split... | 2.78125 | 3 |
cupy/linalg/norm.py | umitanuki/chainer | 0 | 35051 | <gh_stars>0
def norm(x, ord=None, axis=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def cond(x, p=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def det(a):
# TODO(beam2d): Implement it
raise NotImplementedError
def matrix_rank(M, tol=None):
# TODO(beam2... | 2.921875 | 3 |
examples/optical_elements/examples_refractive_interface.py | srio/minishadow | 1 | 35052 | <reponame>srio/minishadow
import numpy
from shadow4.sources.source_geometrical.source_geometrical import SourceGeometrical
from shadow4.beamline.optical_elements.refractors.s4_conic_interface import S4ConicInterface, S4ConicInterfaceElement
from shadow4.tools.graphics import plotxy
from shadow4.syned.element_coord... | 2 | 2 |
recipes/transabyss/setup.py | ieguinoa/bioconda-recipes | 0 | 35053 | <filename>recipes/transabyss/setup.py
import subprocess
from setuptools import setup, find_packages, Extension
setup(
name='transabyss',
version='1.54',
author='transabyss',
license='Free Software License',
packages=['transabyss'],
scripts=['scripts/transabyss', 'scripts/transabyss-merge'],
)
| 1.226563 | 1 |
ffs/__init__.py | clbarnes/ffs | 0 | 35054 | from .classes import Entry, EntryJso
from .spec_version import SPEC_VERSION
from .version import version as __version__ # noqa: F401
from .version import version_tuple as __version_info__ # noqa: F401
__all__ = ["Entry", "EntryJso", "SPEC_VERSION"]
| 1.085938 | 1 |
src/main/gui/core/functions.py | UntactOrder/UntactOrder.PosServer | 0 | 35055 | <reponame>UntactOrder/UntactOrder.PosServer
# ///////////////////////////////////////////////////////////////
#
# BY: <NAME>
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scripts, any informa... | 1.390625 | 1 |
DeepJH/agents/actor_critic_agents/explorer.py | microsoft/Dr-Jekyll-and-Mr-Hyde-The-Strange-Case-of-Off-Policy-Policy-Updates | 2 | 35056 | from multiprocessing.dummy import Value
from agents.Base_Agent import Base_Agent
import copy
import numpy as np
import torch
import torch.nn.functional as F
from torch.optim import Adam
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def _... | 2.4375 | 2 |
python/nlusvc/spacy/svc/perform_pos_parse.py | jiportilla/ontology | 0 | 35057 | <filename>python/nlusvc/spacy/svc/perform_pos_parse.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pandas as pd
from pandas import DataFrame
from spacy.lang.en import English
from tabulate import tabulate
from base import BaseObject
class PerformPosParse(BaseObject):
""" Perform POS (Part-of-Speech) P... | 3.046875 | 3 |
causal_world/intervention_actors/visual_actor.py | michaelfeil/CausalWorld | 2 | 35058 | <reponame>michaelfeil/CausalWorld
from causal_world.intervention_actors.base_actor import \
BaseInterventionActorPolicy
import numpy as np
class VisualInterventionActorPolicy(BaseInterventionActorPolicy):
def __init__(self, **kwargs):
"""
This intervention actor intervenes on all visual compo... | 2.84375 | 3 |
app/utils.py | AnthonyBloomer/covid-cli | 3 | 35059 | <reponame>AnthonyBloomer/covid-cli
import csv
import time
from datetime import datetime
from prettytable import PrettyTable
from .api import countries, country, totals, us_states
def to_csv(data):
fieldnames = set()
for event in data:
fieldnames |= event.keys()
with open("%s.csv" % int(time.time... | 3.015625 | 3 |
yann/utils/timer.py | michalwols/yann | 32 | 35060 | from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from datetime import datetime
import torch.cuda
from ..viz.plot import plot_timeline
def time(name=None, sync=False):
return Task(name=name, sync=sync, log=True)
class Task:
__slots__ = ('name', 'start_time', 'end_time', 'met... | 2.5 | 2 |
conans/client/client_cache.py | jbaruch/conan | 0 | 35061 | <filename>conans/client/client_cache.py
import os
from conans.errors import ConanException
from conans.util.files import save, load, normalize
from conans.model.settings import Settings
from conans.client.conf import ConanClientConfigParser, default_client_conf, default_settings_yml
from conans.model.values import Val... | 2.46875 | 2 |
tppm/auth.py | timtumturutumtum/TraktPlaybackProgressManager | 36 | 35062 | <reponame>timtumturutumtum/TraktPlaybackProgressManager<filename>tppm/auth.py
# coding: utf-8
""" Trakt Playback Manager """
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import json
import os.path
def save(path, data):
with io.open(path, 'w', encoding='utf-8', newline=... | 2.34375 | 2 |
srt.py | glegoux/srt | 0 | 35063 | #!/usr/bin/env python3
import sys
import os.path
import re
from datetime import date, datetime, time, timedelta
# helper
def is_timeformat(s):
p = re.compile('^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}$')
if p.match(s) is None:
return False
else:
return True
def is_time_line(l):
p = re.c... | 3.140625 | 3 |
pykeyset/core/font/font.py | staticintlucas/pykeyset | 1 | 35064 | from typing import Optional
from .glyph import Glyph
class Font:
def __init__(
self,
name: str,
em_size: float,
cap_height: float,
x_height: float,
line_height: float,
slope: float,
char_spacing: float,
):
raise NotImplementedError
... | 3.5625 | 4 |
models/SoftmaxTriplet.py | anonymous1computervision/REID | 1 | 35065 | <gh_stars>1-10
# encoding: utf-8
import copy
import itertools
import numpy as np
import torch
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch import nn, optim
from .resnet import ResNet
def weights_init_kaiming(m):
classname = m.__class__.__name__
if classname.find('Lin... | 2.015625 | 2 |
data-exporter/brix/settings.py | dzwiedziu-nkg/credo-api-tools | 0 | 35066 | <reponame>dzwiedziu-nkg/credo-api-tools
import csv
DIR = 'credo-data-export/detections'
CSV = 'credo-data-export/credocut.tsv'
PLOT = 'credo-data-export/credocut.plot'
JSON = 'credo-data-export/credocut.json'
DEVICES = 'credo-data-export/device_mapping.json'
PNG = 'credo-data-export/png'
CREDOCUT = 10069
DELIMITER='\... | 2.03125 | 2 |
Calibration/EcalAlCaRecoProducers/python/alcastreamEcalPhiSym_cff.py | ckamtsikis/cmssw | 852 | 35067 | # The following comments couldn't be translated into the new config version:
#------------------------------------------------
#AlCaReco filtering for phi symmetry calibration:
#------------------------------------------------
#
# Passes events that are coming from the online phi-symmetry stream
#
#
import FWCore.P... | 1.125 | 1 |
{{cookiecutter.project_name}}/core/vertebral.py | rzavarce/cookiecutter-vertebral | 0 | 35068 | <gh_stars>0
import re
import json
import logging
import hmac
import base64
import hashlib
import jsonschema
from uuid import uuid4
from aiohttp import web
from pathlib import Path
from yaml import safe_load
from http import HTTPStatus
from datetime import datetime, timezone
from {{cookiecutter.project_name}}.routes ... | 1.96875 | 2 |
2021/day14/1.py | tomhel/AoC_2019 | 1 | 35069 | def load():
with open("input") as f:
yield next(f).strip()
next(f)
for x in f:
yield x.strip().split(" -> ")
def pair_insertion():
data = list(load())
polymer, rules = list(data[0]), dict(data[1:])
for _ in range(10):
new_polymer = [polymer[0]]
for... | 3.140625 | 3 |
dev/cluster/__init__.py | ustcml/TorchML | 0 | 35070 | # Author: <NAME>
# Email: <EMAIL>
# Date:
from .KMeans import KMeans
| 1.21875 | 1 |
mandelbrot.py | parkman217/python-mandelbrot | 0 | 35071 | <filename>mandelbrot.py
import pygame, sys, cmath, time, math
def get_mandlebrot(x, y):
num = complex(x, y)
curr_num = complex(0, 0)
max_iter = 100
for a in range(max_iter):
curr_num = (curr_num * curr_num) + num
r, phi = cmath.polar(curr_num)
if r > 2:
return a/max... | 3.21875 | 3 |
example-query.py | ericwhyne/http-ricochet | 19 | 35072 | <reponame>ericwhyne/http-ricochet<filename>example-query.py<gh_stars>10-100
#!/usr/bin/python
import urllib2
import random
# A list of places we've deployed ricochet
ricochet_servers = [
"http://127.0.0.1:8080/ricochet/ricochet?url=",
"http://127.0.0.1:8080/ricochet/ricochet?url="
]
# We're identifying ourselves to o... | 2.953125 | 3 |
Week-4/Prob4h.py | jabhij/MITx-6.00.1x-PYTHON | 2 | 35073 | def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: ... | 4.1875 | 4 |
annofabcli/filesystem/subcommand_filesystem.py | kurusugawa-computer/annofab-cli | 9 | 35074 | import argparse
from typing import Optional
import annofabcli
import annofabcli.common.cli
import annofabcli.filesystem.draw_annotation
import annofabcli.filesystem.filter_annotation
import annofabcli.filesystem.mask_user_info
import annofabcli.filesystem.merge_annotation
import annofabcli.filesystem.write_annotation_... | 2.390625 | 2 |
buildmsi.py | vivainio/pylauncher-import | 0 | 35075 | import getpass
import os
import sys
VER = '1.0.1.7'
VERSION = 'Version=%s' % VER
MANUFACTURER = 'Manufacturer=<NAME>'
X86 = 'Platform=x86'
X64 = 'Platform=x64'
TOWIN = 'ToWindows'
def main():
signpwd = getpass.getpass('Password for signing:')
import builddoc
builddoc.main()
os.environ['... | 2.109375 | 2 |
frameworks/Python/spyne/gen_benchmark_config.py | xsoheilalizadeh/FrameworkBenchmarks | 5,300 | 35076 | <filename>frameworks/Python/spyne/gen_benchmark_config.py
#!/usr/bin/env python
from __future__ import print_function
import json
from spyne import AnyUri, Unicode, ComplexModel, M, UnsignedInteger16, Array
from spyne.protocol.json import JsonDocument
from spyne.util.dictdoc import get_object_as_dict
class Benchma... | 2.140625 | 2 |
craedl/errors.py | AnotherGroupChat/craedl-sdk-python | 0 | 35077 | # Copyright 2019 The Johns Hopkins University
#
# 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 agree... | 2.484375 | 2 |
slack_bolt/response/__init__.py | korymath/bolt-python | 160 | 35078 | <filename>slack_bolt/response/__init__.py<gh_stars>100-1000
from .response import BoltResponse
| 1.15625 | 1 |
source/miscellaneous/test_get_sub_dir_dates.py | youdar/usesul_functions | 0 | 35079 | <reponame>youdar/usesul_functions
#!/usr/bin/env python
from __future__ import division
from get_sub_dir_dates import get_sub_dir_dates
from get_table_hdfs_location import get_table_hdfs_location
import unittest
import sys
__author__ = 'youval.dar'
class CollectDates(unittest.TestCase):
def test_get_sub_dir_dat... | 2.296875 | 2 |
torchreid/utils/tools.py | opencv/deep-person-reid | 1 | 35080 | <gh_stars>1-10
# Copyright (c) 2018-2021 <NAME>
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2018 davidtvs
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2018 Facebook
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
from __future__ import absol... | 1.921875 | 2 |
src/setup.py | Mr-Salme/CipheyCore | 0 | 35081 | from setuptools import setup, Extension
# Compile parts of `freq.cpp` into a shared library so we can call it from Python
setup(
#...
ext_modules=[Extension('gof_test', ['freq.cpp'],),],
)
| 1.359375 | 1 |
acousticsim/clustering/__init__.py | JoFrhwld/python-acoustic-similarity | 5 | 35082 | <filename>acousticsim/clustering/__init__.py
from .network import ClusterNetwork
| 1.140625 | 1 |
hangman/ps3_hangman.py | kriyaaseela/Hangman | 1 | 35083 | <filename>hangman/ps3_hangman.py
# Hangman game
import random
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
# inFile: fil... | 4.21875 | 4 |
src/utils/logger.py | hao-wang/Montage | 65 | 35084 | class Colors:
END = '\033[0m'
ERROR = '\033[91m[ERROR] '
INFO = '\033[94m[INFO] '
WARN = '\033[93m[WARN] '
def get_color(msg_type):
if msg_type == 'ERROR':
return Colors.ERROR
elif msg_type == 'INFO':
return Colors.INFO
elif msg_type == 'WARN':
return Colors.WARN
else:
return Colors.END... | 2.765625 | 3 |
lorawan/user_agent/bridge/agent_bridge.py | pablomodernell/lorawan_conformance_testing | 1 | 35085 | """
This Module defines the main the main component of the Agent service, a bridge that listens to
UDP messages from the LoRa gateway's Packet Forwarder and encapsulates and sends them using the AMQP
protocol to the Test Application Server (TAS).
"""
#####################################################################... | 1.765625 | 2 |
datamanager/interfaces/abstract_resource_resolver.py | alghimo/data-manager | 1 | 35086 | from abc import ABC, abstractmethod
from typing import TypeVar, Generic
T = TypeVar("T")
class AbstractResourceResolver(Generic[T], ABC):
"""
The resolver takes care of creating fully qualified names from resource keys.
For instance, when working with files this would be the file path, when working
w... | 3.15625 | 3 |
model_zoo/Star/__init__.py | RManLuo/MAMDR | 2 | 35087 | from .star import *
from .partitioned_norm import * | 1.054688 | 1 |
synergy/db/model/job.py | eggsandbeer/scheduler | 0 | 35088 | __author__ = '<NAME>'
from odm.document import BaseDocument
from odm.fields import StringField, ObjectIdField, ListField, IntegerField
MAX_NUMBER_OF_LOG_ENTRIES = 32
TIMEPERIOD = 'timeperiod'
PROCESS_NAME = 'process_name'
START_OBJ_ID = 'start_obj_id'
END_OBJ_ID = 'end_obj_id'
STATE = 'state'
RELATED_UNIT_OF_WORK = '... | 2.0625 | 2 |
text/code/exact-string-matching/naive-forward.py | pmikolajczyk41/string-algorithms | 1 | 35089 | def naive_string_matching(t, w, n, m):
for i in range(n - m + 1):
j = 0
while j < m and t[i + j + 1] == w[j + 1]:
j = j + 1
if j == m:
return True
return False | 3.171875 | 3 |
shop/tests.py | okcashpro/okshop | 3 | 35090 | <reponame>okcashpro/okshop
from django.test import TestCase, Client
from django.contrib.auth.models import User
from .models import *
from django.urls import reverse
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files.uploadedfile import InMemoryUploadedFile
from io import BytesIO
impor... | 2.203125 | 2 |
h2o-py/tests/testdir_algos/rulefit/pyunit_football_rulefit.py | vishalbelsare/h2o-3 | 1 | 35091 | <gh_stars>1-10
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.rulefit import H2ORuleFitEstimator
def football():
df = h2o.import_file("https://h2o-public-test-data.s3.amazonaws.com/mli-testing/manual-test/small-dataset/binomial/football_prediction.csv")
... | 2.9375 | 3 |
Day2/python-exercises-02-answers/preparing_dataset/category_dataset_debug.py | klimpie94/Python-training | 0 | 35092 | import pandas as pd
import os
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')
DATA_PATH = os.path.join(
os.fspath(Path(__file__).parents[1]),
"data")
IMDB_DATA_PATH = os.path.join(DATA_PATH, "imdb_category.csv")
EXPORT_PATH = os.path.join(DATA_PATH, "imdb_category_binary.csv")
ca... | 3.046875 | 3 |
imgtools/modules/segmentation.py | bhklab/med-imagetools | 9 | 35093 | from functools import wraps
import numpy as np
import SimpleITK as sitk
from ..utils import array_to_image, image_to_array
def accepts_segmentations(f):
@wraps(f)
def wrapper(img, *args, **kwargs):
result = f(img, *args, **kwargs)
if isinstance(img, Segmentation):
result = sit... | 2.671875 | 3 |
simtbx/diffBragg/attr_list.py | dperl-sol/cctbx_project | 155 | 35094 | from __future__ import division
"""
critical properties of diffBragg objects which should be logged for reproducibility
"""
# TODO : implement a savestate and getstate for these objects
# attrs of diffBragg() instances
DIFFBRAGG_ATTRS = [
'Amatrix',
'Bmatrix',
'Ncells_abc',
'Ncells_abc_aniso',
'Ncells_def',
'N... | 1.851563 | 2 |
tests/data/fields/field_test.py | MSLars/allennlp | 11,433 | 35095 | from allennlp.data.fields import Field
def test_eq_with_inheritance():
class SubField(Field):
__slots__ = ["a"]
def __init__(self, a):
self.a = a
class SubSubField(SubField):
__slots__ = ["b"]
def __init__(self, a, b):
super().__init__(a)
... | 2.953125 | 3 |
LMToolKit_Setup.py | Meadowlion/Float | 1 | 35096 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 10:19:44 2021
@author: sb069
"""
import os
import errno
from os.path import expanduser
os.system("sudo apt-get update")
os.system("sudo apt install nvidia-cuda-toolkit")
os.system("sudo apt install python3.8")
os.system("conda ins... | 1.78125 | 2 |
oxasl_ve/wrappers/veaslc.py | ibme-qubic/oxasl_ve | 1 | 35097 | """
Wrapper for epi_reg command
"""
import fsl.utils.assertions as asrt
from fsl.wrappers import wrapperutils as wutils
@wutils.fileOrImage('data', 'roi', outprefix='out')
@wutils.fileOrArray('veslocs', 'encdef', 'modmat')
@wutils.fileOrText(' ')
@wutils.fslwrapper
def veaslc(data, roi, veslocs, encdef, imlist, modm... | 2.140625 | 2 |
leo/modes/kivy.py | ATikhonov2/leo-editor | 1,550 | 35098 | <gh_stars>1000+
# Leo colorizer control file for kivy mode.
# This file is in the public domain.
# Properties for kivy mode.
properties = {
"ignoreWhitespace": "false",
"lineComment": "#",
}
# Attributes dict for kivy_main ruleset.
kivy_main_attributes_dict = {
"default": "null",
"digit_re... | 2.28125 | 2 |
src/predictor.py | prem2017/domain-adaptation-image | 1 | 35099 | <filename>src/predictor.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# ©Prem Prakash
# Predictor module
import os
import sys
import pdb
from copy import deepcopy
import argparse
import onnx
import onnxruntime as ort
import math
from matplotlib.pyplot import imshow
import numpy as np
import pandas as pd
import torch
i... | 2.140625 | 2 |