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 |
|---|---|---|---|---|---|---|
bigdatacloudapi/client.py | robertreist/python-api-client | 6 | 12784951 | <gh_stars>1-10
import requests
import re
import json
class Client:
def __init__(
self,
apiKey,
nameSpace='data',
server='api.bigdatacloud.net'
):
self.apiKey=apiKey
self.nameSpace=nameSpace
self.server=server
def __getattr__(self,p):
def mm(params):
def conversion... | 2.765625 | 3 |
BoManifolds/pymanopt_addons/tools/autodiff/__init__.py | NoemieJaquier/GaBOtorch | 21 | 12784952 | from ._theano import TheanoBackend
from ._autograd import AutogradBackend
from ._tensorflow import TensorflowBackend
from ._pytorch import PytorchBackend
__all__ = ["AutogradBackend", "PytorchBackend",
"TensorflowBackend", "TheanoBackend"]
| 1.296875 | 1 |
pylps/plan.py | astraldawn/pylps | 1 | 12784953 | <gh_stars>1-10
import copy
from collections import deque
from ordered_set import OrderedSet
from pylps.config import CONFIG
from pylps.constants import *
from pylps.utils import *
class Proposed(object):
def __init__(self):
self._actions = OrderedSet()
self._fluents = OrderedSet()
def __re... | 2.671875 | 3 |
machine_learning/Preprocessing.py | jbofill10/House-Prices-Kaggle-Competition | 1 | 12784954 | <reponame>jbofill10/House-Prices-Kaggle-Competition<gh_stars>1-10
from sklearn.preprocessing import RobustScaler
import pandas as pd
def preprocess(train_test_df, train_df, test_df):
train_test_encoded = pd.get_dummies(train_test_df)
train_encoded = train_test_encoded.iloc[:len(train_df)]
test_encoded ... | 3.15625 | 3 |
saleor/product/urls.py | YunazGilang/saleor-custom | 2 | 12784955 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<slug>[a-z0-9-_]+?)-(?P<product_id>[0-9]+)/$',
views.product_details, name='details'),
url(r'^category/(?P<path>[a-z0-9-_/]+?)-(?P<category_id>[0-9]+)/$',
views.category_index, name='category'),
url(r'^brand/(?P... | 1.96875 | 2 |
distributed_social_network/posts/migrations/0005_auto_20190327_0252.py | leevtori/CMPUT404-project | 0 | 12784956 | <gh_stars>0
# Generated by Django 2.1.7 on 2019-03-27 02:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_auto_20190317_2154'),
]
operations = [
migrations.AlterField(
model_name='post',
name='cat... | 1.484375 | 1 |
python-news_aggregator/tests/libs/feed_utils_test.py | hanakhry/Crime_Admin | 0 | 12784957 | import unittest
from jarr.controllers.feed_builder import FeedBuilderController as FBC
from jarr.lib.enums import FeedType
class ConstructFeedFromTest(unittest.TestCase):
@property
def jdh_feed(self):
return {'icon_url': 'https://www.journalduhacker.net/assets/jdh-ico-31'
... | 2.46875 | 2 |
data_structures/tree.py | claudiogar/learningPython | 0 | 12784958 | class Tree:
def __init__(self, value):
self.rootValue = value
self.children = []
pass
def addChild(self, value):
node = Tree(value)
self.children.append(node)
return node
def removeChild(self, node):
for subChild in node.children:
... | 3.765625 | 4 |
mcse/libmpi/check.py | manny405/mcse | 5 | 12784959 | <reponame>manny405/mcse
# -*- coding: utf-8 -*-
import os,shutil
from mcse.io import read,write
from mcse.io import check_dir,check_struct_dir
from mcse.libmpi.base import _NaiveParallel
from mpi4py import MPI
def null_check_fn(struct_path):
"""
Checking Structure from input directory will always return Fa... | 2.453125 | 2 |
junospyez_ossh_server/__init__.py | jeremyschulman/junospyez-ossh-server | 3 | 12784960 | from .ossh_server import OutboundSSHServer | 1.03125 | 1 |
ssd_liverdet/data/data_custom_v2.py | L0SG/Liver_segmentation | 0 | 12784961 | <reponame>L0SG/Liver_segmentation
# NEW impl for 1904 dataset: things are getting too big, use online data loading from disk!
# for arbitrary image dataset
# courtesy of https://github.com/amdegroot/ssd.pytorch/issues/72
# # for debugging perf hotspot
# from line_profiler import LineProfiler
# from utils import augme... | 2.15625 | 2 |
data_collection/ts/indonesia_timeseries/download_indonesia_prices.py | f4bD3v/humanitas | 6 | 12784962 | #!/usr/bin/env python2
import urllib2
import shutil
import re
import sys
import datetime
from lxml import etree
usage_str = """
This scripts downloads daily food prices from http://m.pip.kementan.org/index.php (Indonesia).
Provide date in DD/MM/YYYY format.
Example:
./download_indonesia_prices.py 15/03/2013
""... | 3.390625 | 3 |
Seq2Seq/seq2seq_advanced.py | STHSF/DeepNaturallanguageprocessing | 15 | 12784963 | # coding=utf-8
import tensorflow as tf
import numpy as np
import helpers
tf.reset_default_graph()
sess = tf.InteractiveSession()
PAD = 0
EOS = 1
vocab_size = 10
input_embedding_size = 20
encoder_hidden_units = 512
decoder_hidden_units = encoder_hidden_units * 2
# define inputs
encoder_input = tf.placeholder(shape=(... | 2.34375 | 2 |
data/states/lobby/lobby_screen.py | iminurnamez/Python_Arcade_Collab | 2 | 12784964 | import math
import pygame as pg
from collections import OrderedDict
from data.core import tools, constants
from data.components.labels import Button, ButtonGroup
from data.components.special_buttons import GameButton, NeonButton
from data.components.animation import Animation
from data.components.state_machine import... | 2.671875 | 3 |
DIYgod/0006/a.py | saurabh896/python-1 | 3,976 | 12784965 | <gh_stars>1000+
f = open('a.txt', 'rb')
lines = f.readlines()
for line in lines:
pass
f.close()
f = open('a.txt', 'rb')
for line in f:
pass
f.close()
f = open('a.txt', 'rb')
while true:
line = f.readline()
if not line:
break
pass
f.close()
| 2.921875 | 3 |
torchpruner/torchpruner/pruner/opt_pruner.py | germanenik/CS231N-Pruning | 0 | 12784966 | <gh_stars>0
import torch
class OptimizerPruner:
@staticmethod
def prune(optimizer, param, axis, keep_indices, device):
if isinstance(optimizer, torch.optim.SGD):
return OptimizerPruner._prune_sgd(optimizer, param, axis, keep_indices, device)
elif isinstance(optimizer, torch.optim.... | 2.1875 | 2 |
jsk_rqt_plugins/src/jsk_rqt_plugins/label.py | ShunjiroOsada/jsk_visualization_package | 5 | 12784967 | <reponame>ShunjiroOsada/jsk_visualization_package<gh_stars>1-10
from rqt_gui_py.plugin import Plugin
import python_qt_binding.QtGui as QtGui
from python_qt_binding.QtGui import (QAction, QIcon, QMenu, QWidget,
QPainter, QColor, QFont, QBrush,
QP... | 1.921875 | 2 |
PythonExercicios/ex032.py | gabjohann/python_3 | 0 | 12784968 | <filename>PythonExercicios/ex032.py
# Faça um programa que leia um ano qualquer e mostre se ele é bissexto
# ----------------------------errado----------------------------
ano = int(input('Digite o ano que deseja saber se é bissexto: '))
bissexto = ano % 4
if bissexto == 0:
print('O ano {} é bissexto.'.format(ano)... | 4.125 | 4 |
mat/mat1.py | vhmercadoo/pytrail | 0 | 12784969 | <reponame>vhmercadoo/pytrail
var = 1
print (var)
| 0.964844 | 1 |
stitch.py | TheShrug/advanced_cartography | 2 | 12784970 | # Copyright (c) 2020 <NAME>
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from os import listdir, path
from time import sleep, strftime
from PIL import Image, ImageDraw
from threading import Thread
from math import floor
class pic:
def __init__(self, fpath, cropFactor... | 2.375 | 2 |
harvester/server/expiring_queue.py | Nisthar/CaptchaHarvester | 545 | 12784971 | <reponame>Nisthar/CaptchaHarvester
from queue import Empty, Queue, SimpleQueue
from threading import Timer
from typing import Any
class ExpiringQueue(Queue):
def __init__(self, timeout: int, maxsize=0):
super().__init__(maxsize)
self.timeout = timeout
self.timers: 'SimpleQueue[Timer]' = Si... | 2.84375 | 3 |
ExceptionHandling/getints.py | Vashesh08/Learn-Python-Programming-Masterclass | 0 | 12784972 | <gh_stars>0
import sys
def get_int(prompt):
while True:
try:
number = int(input(prompt))
return number
except EOFError:
sys.exit(1)
except: # Should be except ValueError:
print("Invalid Number Entered. Please Try Again:")
... | 3.6875 | 4 |
wikipediabase/resolvers/term.py | fakedrake/WikipediaBase | 1 | 12784973 | <reponame>fakedrake/WikipediaBase
# -*- coding: utf-8 -*-
import re
from wikipediabase.provider import provide
from wikipediabase.resolvers.base import BaseResolver
from wikipediabase.lispify import lispify
from wikipediabase.util import get_infoboxes, get_article, totext, markup_unlink
class TermResolver(BaseResol... | 2.609375 | 3 |
examples/TushareDataService/test3.py | gongkai90000/2010test | 0 | 12784974 | <reponame>gongkai90000/2010test
# encoding: UTF-8
import requests
import sys
import csv
import csv
import os
'''
future_code = 'M0'
url_str = ('http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine15m?symbol=' + future_code)
r = requests.get(url_str)
#http://stock2.finance.sina... | 2.921875 | 3 |
src/metrics.py | anastasiia-kornilova/mom-tools | 8 | 12784975 | # Copyright 2021 <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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | 1.726563 | 2 |
modules_tf/util.py | kibernetika-ai/first-order-model | 0 | 12784976 | import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.python.ops.gen_image_ops import resize_nearest_neighbor
@tf.function
def kp2gaussian(kp_value, spatial_size, kp_variance):
"""
Transform a keypoint into gaussian like representation
"""
mean = kp_value # B, 10, 2
coordin... | 2.71875 | 3 |
ut.py | michaelpdu/adversary_ml | 1 | 12784977 | import os, sys
import unittest
import tlsh
from logging import *
sys.path.append(os.path.join(os.path.dirname(__file__),'UT'))
# from ut_trendx_predictor import TrendXPredictorTestCase
from ut_dna_manager import DNAManagerTestCase
from ut_housecallx_report import HouseCallXReportTestCase
from ut_trendx_wrappe... | 1.945313 | 2 |
service/Speech.py | sola1993/inmoov | 1 | 12784978 | <filename>service/Speech.py
from time import sleep
from org.myrobotlab.service import Speech
from org.myrobotlab.service import Runtime
# sayThings.py
# example script for MRL showing various methods
# of the Speech Service
# http://myrobotlab.org/doc/org/myrobotlab/service/Speech.html
# The preferred method for cre... | 3.46875 | 3 |
lib/awx_cli/commands/BaseCommand.py | bennojoy/awx-cli | 2 | 12784979 | # Copyright 2013, AnsibleWorks Inc.
# <NAME> <<EMAIL>>
#
# 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... | 1.921875 | 2 |
hard-gists/2038329/snippet.py | jjhenkel/dockerizeme | 21 | 12784980 | <reponame>jjhenkel/dockerizeme
from bigfloat import *
N = 5
setcontext(precision(10**N))
def f(x):
return x + sin(x)
def g(n):
x = 3
for i in xrange(n):
x = f(x)
return x
import sympy
goodpi = str(sympy.pi.evalf(10**N))
def goodtill(n):
cand = g(n)
for i,(a,b) in enumerate(... | 2.609375 | 3 |
server.py | MeiRose/Datamanager | 0 | 12784981 | from flask import Flask, send_from_directory, jsonify
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
CLIENT_DIR = os.path.join(BASE_DIR, "client", "dist")
STATIC_DIR = os.path.join(BASE_DIR, "static")
app = Flask(__name__)
app.secret_key = "Developer Key"
@app.route('/')
def index():
return sen... | 2.515625 | 3 |
switch/controller/main_controller.py | fnrg-nfv/P4SFC-public | 2 | 12784982 | from flask import Flask, request
import argparse
import time
import threading
from p4_controller import P4Controller
from state_allocator import EntryManager
app = Flask(__name__)
p4_controller = None
entry_manager = None
@app.route('/test')
def test():
return "Hello from switch control plane controller~!"
@ap... | 2.359375 | 2 |
itemIndex.py | adamb70/CSGO-Market-Float-Finder | 73 | 12784983 | index = {
"ID0": "Vanilla",
"ID2": "Groundwater",
"ID3": "Candy Apple",
"ID5": "Forest DDPAT",
"ID6": "Arctic Camo",
"ID8": "Desert Storm",
"ID9": "Bengal Tiger",
"ID10": "Copperhead",
"ID11": "Skulls",
"ID12": "Crimson Web",
"ID13": "Blue Streak",
"ID14": "Red Laminate",... | 1.34375 | 1 |
pyimq/bin/utils/create_photo_test_set.py | bradday4/PyImageQualityRanking | 8 | 12784984 | <reponame>bradday4/PyImageQualityRanking
"""
<NAME> - 2015 - <EMAIL>
A small utility that generates Gaussian blurred images from a
series of base images. This utility was use to create an autofocus function test
dataset.
"""
import os
import sys
from scipy import ndimage, misc
import numpy
def main():
# Check ... | 2.859375 | 3 |
common/rtemsext.py | cillianodonnell/rtems-docs | 1 | 12784985 | from docutils import nodes
import sphinx.domains.std
# Borrowed from: http://stackoverflow.com/questions/13848328/sphinx-references-to-other-sections-containing-section-number-and-section-title
class CustomStandardDomain(sphinx.domains.std.StandardDomain):
def __init__(self, env):
env.settings['footnote_references... | 2.234375 | 2 |
ctc_fast/swbd-utils/score_frag_utts.py | SrikarSiddarth/stanford-ctc | 268 | 12784986 | <filename>ctc_fast/swbd-utils/score_frag_utts.py<gh_stars>100-1000
'''
Look at error rates only scoring utterances that contain frags
'''
FRAG_FILE = '/deep/u/zxie/ctc_clm_transcripts/frags.txt'
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('hyp')
pa... | 2.859375 | 3 |
leadgen.py | jsmiles/LeadGen | 0 | 12784987 | <gh_stars>0
import pandas as pd
input = pd.read_csv('input.txt',sep=',')
ref = pd.read_csv('reference.txt',sep=',')
def ref_lookup(company):
if company in ref.loc[:,'Company'].tolist():
dom = ref.loc[ref['Company']== f'{company}', 'Domain'].iloc[:]
pat = ref.loc[ref['Company']== f'{company... | 3.140625 | 3 |
data_loader/data_loaders.py | Neronjust2017/pytorch-classification-project | 0 | 12784988 | import torch
from torch.utils.data import TensorDataset
from torchvision import datasets, transforms
from base import BaseDataLoader, BaseDataLoader_2
from torch.utils.data import DataLoader
import numpy as np
import pandas as pd
from .utils import readmts_uci_har, transform_labels
class MnistDataLoader(BaseDataLoader... | 2.71875 | 3 |
sandbox/lhs_reduced.py | MiroK/fenics_ii | 10 | 12784989 | <filename>sandbox/lhs_reduced.py
from block import block_mat, block_vec, block_bc
from dolfin import *
from xii import *
import mshr
N = 10
EPS = 1E-3
R = 0.25
box_domain = mshr.Box(dolfin.Point(0, 0, 0), dolfin.Point(1, 1, 1))
_mesh = mshr.generate_mesh(box_domain, N)
stokes_subdomain = dolfin.CompiledSubDomain(
... | 1.921875 | 2 |
geoist/magmod/magnetic_model/model_composed.py | CHEN-Zhaohui/geoist | 53 | 12784990 | #-------------------------------------------------------------------------------
#
# Aggregated Magnetic Model
#
# Author: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2018 EOX IT Services GmbH
#
# Permission is hereby granted, free of charge, to a... | 1.21875 | 1 |
src/classification/experiment.py | rubencart/es-img-captioning | 0 | 12784991 | <filename>src/classification/experiment.py
import torchvision
from torchvision.transforms import transforms
from algorithm.tools.experiment import Experiment
from algorithm.tools.utils import Config
class MnistExperiment(Experiment):
"""
Subclass for MNIST experiment
"""
def __init__(self, exp, ... | 2.375 | 2 |
children/basic_logging.py | IgorIvkin/Children | 0 | 12784992 | """
Author: Igor
Date: 2020.06.07
"""
import logging
import sys
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
LOG_FORMATTING_STRING = logging.Formatter('%(asctime)s - %(module)s - %(filename)s - '
'%(lineno)d - %(levelname)s - %(message)... | 3.3125 | 3 |
test_myFunction.py | Guidofaassen/yolo-tyrion | 0 | 12784993 | <filename>test_myFunction.py
import myFunction
import numpy as np
class TestClass:
def test_answer(self):
assert myFunction.add_one(3) == 4
def test_answer2(self):
assert myFunction.add_one(4) == 5
def test_answer3(self):
assert myFunction.add_one(-2) == -1
# def test_similarity_conditional2(self... | 2.96875 | 3 |
Node_Classification/2.GraphSN_GIN/cora/models.py | wokas36/GraphSNN | 11 | 12784994 | <gh_stars>10-100
import math
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch.nn.parameter import Parameter
from torch.nn import Sequential, Linear, ReLU, Parameter, Sequential, BatchNorm1d, Dropout
class Graphsn_GIN(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout):
... | 2.515625 | 3 |
apps/fund/permissions.py | jfterpstra/onepercentclub-site | 7 | 12784995 | from rest_framework import permissions
class IsUser(permissions.BasePermission):
""" Read / write permissions are only allowed if the obj.user is the logged in user. """
def has_object_permission(self, request, view, obj):
return obj.user == request.user
| 2.71875 | 3 |
cli/decorators/count_calls.py | oleoneto/django-clite | 22 | 12784996 | <gh_stars>10-100
import functools
def count_calls(f):
@functools.wraps(f)
def wrapper_count_calls(*args, **kwargs):
wrapper_count_calls.num_calls += 1
print(f"Call {wrapper_count_calls.num_calls} of {f.__name__!r}")
return f(*args, **kwargs)
wrapper_count_calls.num_calls = 0
re... | 3.09375 | 3 |
coralinede/auto_detect_df/detect_datatype.py | coralinetech/coralinede | 0 | 12784997 | import operator
import sqlalchemy
import pandas as pd
import numpy as np
from math import ceil
DEFAULT_VARCHAR_LENGTH=100
def get_detected_column_types(df):
""" Get data type of each columns ('DATETIME', 'NUMERIC' or 'STRING')
Parameters:
df (df): pandas dataframe
Returns
df (df): datafr... | 3.296875 | 3 |
samples/python/40.timex-resolution/ambiguity.py | Aliacf21/BotBuilder-Samples | 1,998 | 12784998 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from recognizers_date_time import recognize_datetime, Culture
class Ambiguity:
"""
TIMEX expressions are designed to represent ambiguous rather than definite dates. For
example: "Monday" could be any Monday ever... | 3.4375 | 3 |
sensors/rg.py | caioluders/PII-Identifier | 14 | 12784999 | import re
def check(data) :
if not isinstance(data, list) :
data = [data]
maybe_rgs_parsed = [ re.sub("[^0-9]","",r) for r in data ]
true_rgs = []
for r in maybe_rgs_parsed :
r1 = list(map(int,list(r)))
r4 = r1[:8]
r2 = [ r4[rr]*(2+rr) for rr in range(len(r4)) ]
d1 = 11-(sum(r2)%11)
r4.append(d1)
... | 2.96875 | 3 |
kyu_7/remove_the_minimum/test_remove_the_minimum.py | pedrocodacyorg2/codewars | 1 | 12785000 | <filename>kyu_7/remove_the_minimum/test_remove_the_minimum.py<gh_stars>1-10
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# FUNDAMENTALS, LISTS, DATA STRUCTURES, ARRAYS
import unittest
import allure
from numpy.random import randint
from kyu_7.remove_... | 3.234375 | 3 |
day 4 .py | ShubhamSinghThakur2907/100daysofcode | 0 | 12785001 | <reponame>ShubhamSinghThakur2907/100daysofcode<filename>day 4 .py
Python 3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> ## there are basically 2 types of functions in python
>>> ##pre-defined user defi... | 3.4375 | 3 |
fetching_data.py | mosihere/selenium | 0 | 12785002 | <gh_stars>0
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# Install selenium driver in case that doesn't exist
driver = webdriver.Chrome(service=Service(ChromeDriverMa... | 3.046875 | 3 |
openprocurement/auctions/geb/tests/fixtures/active_tendering.py | oleksiyVeretiuk/openprocurement.auctions.geb | 0 | 12785003 | <reponame>oleksiyVeretiuk/openprocurement.auctions.geb
from copy import deepcopy
from openprocurement.auctions.core.utils import get_now
from openprocurement.auctions.geb.tests.fixtures.active_rectification import (
ACTIVE_RECTIFICATION_AUCTION_DEFAULT_FIXTURE
)
from openprocurement.auctions.geb.tests.fixtures.ques... | 2.015625 | 2 |
src/abstract_factory2.py | MrRezoo/design-patterns-python | 6 | 12785004 | """
Creational:
abstract factory
Car => Benz, Bmw => Suv, Coupe
benz suv => gla, glc
bmw suv => x1, x2
benz coupe => cls, E-class
bmw coupe => m2, m4
"""
from abc import ABC, abstractmethod
class Car(ABC):
@abstractmethod
def call_suv(self):
pass
@abstractmeth... | 4.15625 | 4 |
coinlib/wallet.py | santosmarco/coinlib | 3 | 12785005 | import coinlib
class Wallet():
def __init__(self, contents={}):
coins_by_symbol = coinlib.get_all_coins_by_symbol()
coins_by_name = coinlib.get_all_coins_by_name()
self.contents = {}
for coin in contents:
coin_lower = coin.lower().strip()
if (coin_lower not... | 3.34375 | 3 |
instagram/views.py | amiinegal/instagram | 0 | 12785006 | from django.shortcuts import render, redirect, get_object_or_404
from .models import Image,Profile,Location,tags
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.contrib.auth.models imp... | 2.15625 | 2 |
2021/day08/main.py | jonathonfletcher/adventofcode | 0 | 12785007 | <gh_stars>0
from collections import defaultdict
class P1(object):
def __init__(self):
self.counter = 0
self.length_mapping = {
2:1,
3:7,
4:4,
7:8
}
def add(self, inputs, outputs):
for o in outputs:
if len(o) in self.... | 2.59375 | 3 |
TriangleStrategy.py | cibobo/FCoin | 0 | 12785008 | <reponame>cibobo/FCoin<filename>TriangleStrategy.py
import FCoinRestLib
import time
import datetime
import json
import fcoin3
import math
class TriangleStrategy(object):
# minimum trading volumn for the reference coin
# BTC: 0.001; ETH: 0.01; USDT: 6.23
minNotional = 0.001
# standard volumn used for ... | 2.828125 | 3 |
airflow_run/__init__.py | TheWeatherCompany/airflow-run | 3 | 12785009 | <filename>airflow_run/__init__.py<gh_stars>1-10
from airflow_run.run import AirflowRun
| 1.15625 | 1 |
PoseEstimationModel.py | zabir-nabil/keras-human-pose | 10 | 12785010 | <gh_stars>1-10
import keras
from keras.models import Sequential
from keras.models import Model
from keras.layers import Input, Dense, Activation, Lambda
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.layers... | 2.640625 | 3 |
src/colors/colors.py | pmk456/Py-Colors | 1 | 12785011 | """
Author: <NAME>
Licence: Apache 2.0
Version: 0.1
"""
import os
import sys
_colors = ["RED", "BLUE", "CYAN", "YELLOW", "GREEN", "MAGENTA", "WHITE", "BLACK"]
backgrounds = ["BG_RED", "BG_BLUE", "BG_CYAN", "BG_YELLOW", "BG_GREEN", "BG_MAGENTA", "BG_WHITE", "BG_BLACK"]
styles = ['BOLD', 'REVERSE', 'UNDERLINE', 'RESET',... | 2.484375 | 2 |
sara_flexbe_behaviors/src/sara_flexbe_behaviors/leftorright_sm.py | WalkingMachine/sara_behaviors | 5 | 12785012 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside ... | 1.890625 | 2 |
tests/test_ipm.py | klauer/pcdsdevices | 1 | 12785013 | <reponame>klauer/pcdsdevices
import logging
import pytest
from ophyd.sim import make_fake_device
from unittest.mock import Mock
from pcdsdevices.inout import InOutRecordPositioner
from pcdsdevices.ipm import IPM
from conftest import HotfixFakeEpicsSignal
logger = logging.getLogger(__name__)
@pytest.fixture(scope=... | 2.15625 | 2 |
jowilder_utils.py | fielddaylab/OGDUtils | 0 | 12785014 | # google imports
# standard library imports
import sys
import copy
import pickle
import os
from collections import Counter
from io import BytesIO
from zipfile import ZipFile
import copy
import pickle
from math import ceil
import importlib
import urllib.request
# math imports
from matplotlib import pyplot as plt
impor... | 1.992188 | 2 |
mods/libvis_mods/project-templates/test-interactive.py | danlkv/pywebviz | 0 | 12785015 | from subprocess import Popen, PIPE
import sys
import os
from queue import Queue, Empty
import subprocess
import threading
import time
class LocalShell(object):
def __init__(self):
pass
def run(self, cmd):
env = os.environ.copy()
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=subproces... | 2.40625 | 2 |
python/testData/codeInsight/smartEnter/methodParameterStaticMethod_after.py | tgodzik/intellij-community | 2 | 12785016 | <reponame>tgodzik/intellij-community<filename>python/testData/codeInsight/smartEnter/methodParameterStaticMethod_after.py<gh_stars>1-10
class MyClass:
@staticmethod
def method():
<caret> | 1.617188 | 2 |
fancy/trainer/transforms/normalize_both_input_and_target.py | susautw/fancy-trainer | 0 | 12785017 | from typing import Optional, Callable
import torch
import numpy as np
from PIL.Image import Image
from ..transforms import TargetHandler
class NormalizeBothInputAndTarget:
transform: Callable[[Image], Image]
target_handler: TargetHandler
def __init__(
self,
transform: Callable[[... | 2.6875 | 3 |
version.py | TheNomet/blackbricks | 0 | 12785018 | <reponame>TheNomet/blackbricks<filename>version.py<gh_stars>0
import re
import os
def get_version():
"""Return the current version number from blackbricks/__init__.py"""
with open(os.path.join(os.path.dirname(__file__), "blackbricks/__init__.py")) as f:
match = re.search(r'__version__ = "([0-9\.]+)"'... | 2.46875 | 2 |
tests/snippets/decorators.py | gabhijit/RustPython | 1 | 12785019 | <gh_stars>1-10
def logged(f):
def wrapper(a, b):
print('Calling function', f)
return f(a, b + 1)
return wrapper
@logged
def add(a, b):
return a + b
c = add(10, 3)
assert c == 14
| 2.921875 | 3 |
assets/tinyurl.py | Code-Cecilia/BotMan.py | 4 | 12785020 | import aiohttp
async def get_tinyurl(link: str):
url = f"http://tinyurl.com/api-create.php?url={link}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response = (await response.content.read()).decode('utf-8')
return response
| 2.953125 | 3 |
YTPP001 Competition/ISGOODNM.py | 8Bit1Byte/Codechef-Solutions | 2 | 12785021 | '''
Problem Name: Good Number Or Not
Problem Code: ISGOODNM
Problem Link: https://www.codechef.com/problems/ISGOODNM
Solution Link: https://www.codechef.com/viewsolution/47005382
'''
def divisors(m):
from math import sqrt
l = set()
for i in range(1, int(sqrt(m)+1)):
if m%i == 0:
... | 3.71875 | 4 |
reproduction/coreference_resolution/data_load/cr_loader.py | KuNyaa/fastNLP | 1 | 12785022 | <filename>reproduction/coreference_resolution/data_load/cr_loader.py
from fastNLP.io.dataset_loader import JsonLoader,DataSet,Instance
from fastNLP.io.file_reader import _read_json
from fastNLP.core.vocabulary import Vocabulary
from fastNLP.io.base_loader import DataBundle
from reproduction.coreference_resolution.model... | 2.375 | 2 |
problems/problem25.py | phanghos/euler-solutions | 1 | 12785023 | <gh_stars>1-10
def digits(n):
c = 0
while n > 0:
c += 1
n //= 10
return c
fib1 = fib2 = 1
fib3 = fib1 + fib2
c = 3
while digits(fib3) != 1000:
fib1, fib2 = fib2, fib3
fib3 = fib1 + fib2
c += 1
print(c)
| 3.53125 | 4 |
reservationen_package/db_util.py | cyrilwelschen/reservationen_package | 0 | 12785024 | import sqlite3
import os
class DbUtil:
def __init__(self, db_file):
self.db_path = db_file
self.conn = self.create_connection()
self.c = self.create_cursor()
def create_connection(self):
try:
os.remove(self.db_path)
print("removing existing db file")
... | 3.109375 | 3 |
spectrespecs/core/models.py | Spacehug/loony-lovegood | 1 | 12785025 | <gh_stars>1-10
from django.utils import timezone
from django.db import models
class Profile(models.Model):
uid = models.BigIntegerField(
blank=False,
null=False,
help_text="Telegram user ID.",
verbose_name="User ID",
db_index=True,
)
gid = models.BigIntegerField(
... | 2.375 | 2 |
dl/keras-efficientnet-regression/efficient_net_keras_regression.py | showkeyjar/beauty | 1 | 12785026 | from typing import Iterator, List, Union, Tuple, Any
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from tensorflow import keras
import tensorflow_addons as tfa
from tensorflow.keras.preprocessing.image import... | 3 | 3 |
src/thirdparty/harfbuzz/src/check-includes.py | devbrain/neutrino | 0 | 12785027 | #!/usr/bin/env python3
import sys, os, re
os.chdir(os.getenv('srcdir', os.path.dirname(__file__)))
HBHEADERS = [os.path.basename(x) for x in os.getenv('HBHEADERS', '').split()] or \
[x for x in os.listdir('.') if x.startswith('hb') and x.endswith('.h')]
HBSOURCES = [os.path.basename(x) for x in os.getenv... | 2.796875 | 3 |
bit_manipulation/swapVariables.py | itsvinayak/cracking_the_codeing_interview | 4 | 12785028 | <gh_stars>1-10
# given two integer swap them without using any temporary variable
# link : https://www.youtube.com/watch?v=DtnH3V_Vjek&list=PLNmW52ef0uwvkul_e_wLD525jbTfMKLIJ&index=4
# x = x + y
# y = x - y
# x = x - y
def swapVariables(a, b):
a = a ^ b
b = a ^ b
a = a ^ b
return [a, b]
... | 3.78125 | 4 |
data_aug/analyze.py | carboncoo/UNITER | 0 | 12785029 | import os
import sys
import lmdb
import json
import torch
import pickle
import random
import msgpack
import numpy as np
import msgpack_numpy
# from transformers import AutoTokenizer
from lz4.frame import compress, decompress
from os.path import exists, abspath, dirname
from sklearn.metrics.pairwise import cosine_simila... | 1.742188 | 2 |
bs4ocr.py | JKamlah/BackgroundSubtractor4OCR | 5 | 12785030 | <filename>bs4ocr.py
#!/usr/bin/env python3
import argparse
import subprocess
import sys
from pathlib import Path
import cv2
import numpy as np
# Command line arguments.
arg_parser = argparse.ArgumentParser(description='Subtract background for better OCR results.')
arg_parser.add_argument("fname", type=lambda x: Path... | 2.953125 | 3 |
accounts/urls.py | imuno/Diploma | 3 | 12785031 | <gh_stars>1-10
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('/', views.login, name='login'),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| 1.585938 | 2 |
lifx.py | Noatz/lifx-api | 0 | 12785032 | import requests
from typing import Dict, List
class LIFX:
'''
docs: https://api.developer.lifx.com
selectors: https://api.developer.lifx.com/docs/selectors
'''
url = 'https://api.lifx.com'
def __init__(self, token):
self.headers = {
'Authorization': f'Bearer {token... | 2.84375 | 3 |
tests/test_gosubdag_relationships.py | flying-sheep/goatools | 477 | 12785033 | #!/usr/bin/env python
"""Plot both the standard 'is_a' field and the optional 'part_of' relationship."""
from __future__ import print_function
__copyright__ = "Copyright (C) 2016-2018, <NAME>, <NAME>, All rights reserved."
import os
import sys
import timeit
import datetime
from goatools.base import download_go_basic... | 2.40625 | 2 |
pystatreduce/optimize/OAS_Example1/pyopt_oas_problem.py | OptimalDesignLab/pyStatReduce | 0 | 12785034 | <filename>pystatreduce/optimize/OAS_Example1/pyopt_oas_problem.py
# pyopt_oas_problem.py
# The following file contains the optimization of the deterministic problem shown
# in the quick example within OpenAeroStruct tutorial, the difference being,
# pyOptSparse is called separately, whereas the Quick example uses a dri... | 2.609375 | 3 |
update.py | QuarkSources/quarksources.github.io | 34 | 12785035 | <gh_stars>10-100
from sourceUtil import AltSourceManager, AltSourceParser, GithubParser, Unc0verParser
sourcesData = [
{
"parser": AltSourceParser,
"kwargs": {"filepath": "https://altstore.oatmealdome.me"},
"ids": ["me.oatmealdome.dolphinios-njb", "me.oatmealdome.DolphiniOS-njb-patreon-beta... | 1.617188 | 2 |
logger.py | tommyvsfu1/ADL2019_ReinforcementLearning | 1 | 12785036 | import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
# Writer will output to ./runs/ directory by default
class TensorboardLogger(object):
def __init__(self, dir):
"""Create a summary writer logging to log_dir."""
self.writer... | 2.9375 | 3 |
app/utils/generator.py | hpi-studyu/analysis-project-generator | 1 | 12785037 | import json
import os
from dotenv import load_dotenv
from utils.copier import generate_files_from_template
from utils.gitlab_service import GitlabService
from utils.study_data import fetch_new_study_data
from utils.supabase_service import SupabaseService
load_dotenv()
def generate_repo(sbs: SupabaseService, gs: Gi... | 2.28125 | 2 |
nogi/endpoints.py | Cooomma/nogi-backup-blog | 0 | 12785038 | import requests
HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
}
# Bilibili Videos Backup
def get_channel_info(member_id: int):
return requests.get(
url='https://api.bilibili.com/x/space/acc/info',
params=... | 2.25 | 2 |
deep_utils/vision/face_detection/haarcascade/cv2/haarcascade_cv2_face_detection.py | dornasabet/deep_utils | 36 | 12785039 | from deep_utils.vision.face_detection.main import FaceDetector
from deep_utils.utils.lib_utils.lib_decorators import get_from_config, expand_input, get_elapsed_time, rgb2bgr
from deep_utils.utils.lib_utils.download_utils import download_decorator
from deep_utils.utils.box_utils.boxes import Box, Point
from .config impo... | 2.328125 | 2 |
test/test_vuelos_entrantes_aena_controller.py | SergioCMDev/Busines-Inteligence-applied-to-tourism | 0 | 12785040 | <reponame>SergioCMDev/Busines-Inteligence-applied-to-tourism
# coding: utf-8
from __future__ import absolute_import
from . import BaseTestCase
from six import BytesIO
from flask import json
class TestVuelosEntrantesAenaController(BaseTestCase):
""" VuelosEntrantesAenaController integration test stubs """
d... | 2.6875 | 3 |
sdk/python/tests/integration/online_store/test_universal_online.py | marsishandsome/feast | 1 | 12785041 | import random
import unittest
import pandas as pd
from tests.integration.feature_repos.test_repo_configuration import (
Environment,
parametrize_online_test,
)
@parametrize_online_test
def test_online_retrieval(environment: Environment):
fs = environment.feature_store
full_feature_names = environmen... | 2.453125 | 2 |
examples/04-rl-ray.py | nnaisense/pgpelib | 36 | 12785042 | # Solving reinforcement learning problems using pgpelib with parallelization
# and with observation normalization
# ==========================================================================
#
# This example demonstrates how to solve locomotion tasks.
# The following techniques are used:
#
# - dynamic population size
... | 2.9375 | 3 |
util/__init__.py | Ovakefali13/buerro | 2 | 12785043 | from .singleton import Singleton
from .to_html import link_to_html, list_to_html, dict_to_html, table_to_html
| 1.1875 | 1 |
logscanner.py | thiscodedbox/TerrariaPythonEmail | 0 | 12785044 | # ThisCodedBox Terraria notifier python script
# last modified 26-MAY-2017
# time for pauses
# smtplib for notifications
# random to add that random string
import time
import smtplib
import random, string
#setup the random, random, random maker
def randomword(length):
return ''.join(random.choice(string.lowercase... | 2.625 | 3 |
src/rosthrottle/tests/throttledListener.py | UTNuclearRoboticsPublic/rosthrottle | 3 | 12785045 | import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
def listener():
rospy.init_node('throttled_listener')
rospy.Subscriber('chatter_message_throttled', String, callback)
rospy.Subscriber('chatter_bandwidth_throttled', String,... | 2.25 | 2 |
tests/serializers/test_snippet.py | juliofelipe/snippets | 1 | 12785046 | <filename>tests/serializers/test_snippet.py
import json
import uuid
from src.domain.snippet import Snippet
from src.serializers.snippet import SnippetJsonEncoder
def test_serializers_domain_snippet():
code = uuid.uuid4()
snippet = Snippet(
code=code,
language="Python",
title="Replace... | 2.515625 | 3 |
MedString.py | soorajbhatia/bioinformatics | 0 | 12785047 | <reponame>soorajbhatia/bioinformatics
from itertools import permutations as p
import itertools
with open('data.txt', 'r') as file:
k = int(file.readline())
Dna = file.readlines()
#creates a list of all possible kmers
def HammingDistance(Text,Text2):
#defines variables to be used
n = len(Text)
k = 1
... | 3.75 | 4 |
misc/python/btn.py | Kolkir/orange-pi | 1 | 12785048 | <reponame>Kolkir/orange-pi<gh_stars>1-10
#!/usr/bin/env python
import os
import sys
import subprocess
if not os.getegid() == 0:
sys.exit('Script must be run as root')
from time import sleep
from subprocess import *
from pyA20.gpio import gpio
from pyA20.gpio import connector
from pyA20.gpio import port
button_... | 2.5 | 2 |
.archived/snakecode/other/dogfood.py | gearbird/calgo | 4 | 12785049 | <reponame>gearbird/calgo
def feedDog(sp: list[str], k: int) -> int:
feedCount = 0
nextDog = 0
for i, v in enumerate(sp):
if v != 'F': continue
while nextDog < min(i+k+1, len(sp)):
if sp[nextDog] != 'D':
nextDog += 1
continue
if abs(next... | 2.875 | 3 |
cme/enum/wmiquery.py | padfoot999/CrackMapExec | 2 | 12785050 | #!/usr/bin/python
# Copyright (c) 2003-2015 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description: [MS-WMI] example. It allows to issue WQL queries and
# ge... | 2.265625 | 2 |