max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
src/group_lasso/utils.py | sroet/group-lasso | 88 | 12771151 | <gh_stars>10-100
"""
"""
import numpy as np
def extract_ohe_groups(onehot_encoder):
"""Extract a vector with group indices from a scikit-learn OneHotEncoder
Arguments
---------
onehot_encoder : sklearn.preprocessing.OneHotEncoder
Returns
-------
np.ndarray
A group-vector that can... | 2.8125 | 3 |
024 Binary Search/Binary_Search.py | Iftakharpy/AlgoExpert-Questions | 3 | 12771152 | <gh_stars>1-10
# Best
# time O(log(n))
# space O(1)
def binarySearch(array, target):
low = 0
high = len(array)-1
while low<=high:
mid = (low+high)//2
if array[mid] == target:
return mid
if target > array[mid]:
low = mid + 1
else:
... | 3.484375 | 3 |
src/notesdir/cli.py | dendronhq/notesdir | 2 | 12771153 | <reponame>dendronhq/notesdir
"""Command-line interface for notesdir."""
import argparse
import dataclasses
from datetime import datetime
import json
from operator import itemgetter, attrgetter
import os.path
import sys
from terminaltables import AsciiTable
from notesdir.api import Notesdir
from notesdir.models import... | 2.53125 | 3 |
woollylib/utils/utils.py | woolly-of-cv/woolly-lib | 0 | 12771154 | <filename>woollylib/utils/utils.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torchsummary import summary
torch.manual_seed(1)
def get_device() -> tuple:
"""Get Device type
Returns:
tuple: Device type
"""
use_cuda = torch.cuda.is_available()
... | 2.46875 | 2 |
rx/operators/observable/blocking/last.py | yutiansut/RxPY | 1 | 12771155 | from typing import Any
def last(self) -> Any:
"""Blocks until the last element emits from a BlockingObservable.
If no item is emitted when on_completed() is called, an exception is thrown
Note: This will block even if the underlying Observable is
asynchronous.
Returns the last item to be emitte... | 3.53125 | 4 |
arch/arch_spade_flex.py | kimhyeongbok/SDGAN | 0 | 12771156 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 14:54:12 2018
@author: maximov
"""
import torch
import torch.nn as nn
import torch.utils.data
from torch.nn import functional as F
from arch.base_network import BaseNetwork
from arch.normalization import get_nonspade_norm_layer
from arch.archi... | 2.234375 | 2 |
lambda/src/compiler/handler.py | jack-e-tabaska/BayerCLAW | 7 | 12771157 | import logging
from pkg.compiler import compile_template
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event: dict, context: object) -> dict:
# event = {
# "requestId": "1234567890",
# "fragment": {...}
# }
ret = event.copy()
try:
ret["fragment"]... | 2.203125 | 2 |
shop/shop/context_processors.py | Anych/mila-iris | 0 | 12771158 | <filename>shop/shop/context_processors.py
from carts.utils import _cart_id
from category.models import Category
from carts.models import Cart, CartItem
def menu_links(request):
cloth_categories = Category.objects.get(slug='clothes').get_descendants(include_self=False)
shoe_categories = Category.objects.get(sl... | 2.125 | 2 |
loadtestmodel.py | The-bot-makers/FireFighterEngine | 1 | 12771159 | import tensorflow as tf
import numpy as np
import chess
#load the saved model
model=tf.keras.models.load_model('openlock_model')
#rest explained in nntest.py
probmodel=tf.keras.Sequential([
model,
tf.keras.layers.Softmax()
])
PieceNum={'p':'0','n':'1','b':'2','r':'3','q':'4','k':'5','.':'6'}
def numreprgen(re... | 2.40625 | 2 |
src/apim/apim_update.py | paul-mateos/azure-apim-deployment-utils | 14 | 12771160 | import sys
import apim_commands
if len(sys.argv) < 2:
print "Usage:"
print " python apim_update.py <config dir>"
sys.exit(1)
if not apim_commands.apim_update(sys.argv[1]):
sys.exit(1)
sys.exit(0)
| 2.4375 | 2 |
seahub/base/registration_urls.py | evrimguner/seahub | 1 | 12771161 | <gh_stars>1-10
from django.conf.urls.defaults import *
# from django.views.generic.simple import direct_to_template
from django.views.generic import TemplateView
from django.conf import settings
from registration.views import activate
from registration.views import register
from seahub.base.accounts import Registrati... | 1.835938 | 2 |
2021/1/1b.py | kristianwiklund/AOC2019 | 3 | 12771162 | <reponame>kristianwiklund/AOC2019
#!/usr/bin/python3
import fileinput
import rolling
l=list()
for line in fileinput.input():
l.append(int(line))
rl = list(rolling.Sum(l,3))
zl = list(zip(rl[:-1],rl[1:]))
def c(t):
return 1 if t[0]<t[1] else 0
print(sum(list(map(c,zl))))
| 3.234375 | 3 |
examples/flask/flask_sam.py | jpmn/sqlalchemy-media | 0 | 12771163 |
import json
import functools
from os import path, mkdir, getcwd
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import TypeDecorator, Unicode
from sqlalchemy_media import Image, ImageValidator, ImageProcessor, ImageAnalyzer, StoreManager, \
FileSystemStore
from sqlalchemy_... | 2.359375 | 2 |
portfolio/templatematching/tests/factories.py | Pompeiro/portfolio | 0 | 12771164 | <reponame>Pompeiro/portfolio
import factory
import factory.fuzzy
from django.core.files.base import ContentFile
from ..models import NEEDLE_CHOICES, UploadedImage
class UploadedImageFactory(factory.django.DjangoModelFactory):
image = factory.LazyAttribute(
lambda _: ContentFile(
factory.djang... | 2.25 | 2 |
src/gripper.py | srkiyengar/Gripper | 0 | 12771165 | <reponame>srkiyengar/Gripper<gh_stars>0
__author__ = 'srkiyengar'
import pygame
import logging
import logging.handlers
from datetime import datetime
import reflex
import screen_print as sp
import joystick as js
import threading
import time
POS_ERROR = 20
#logger
LOG_LEVEL = logging.DEBUG
LOG_FILENAME = 'Gripper' + d... | 2.765625 | 3 |
models/cifar_mobilenetv1.py | xhchrn/open_lth | 9 | 12771166 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch.nn as nn
import torch.nn.functional as F
from foundations import hparams
from lottery.desc import LotteryDesc
from models import ... | 2.28125 | 2 |
Hello World Programs/Hello World.py | chloee59/Contribute-to-HacktoberFest2020 | 0 | 12771167 | <filename>Hello World Programs/Hello World.py
print ("Hello world")
print ("Nice to meet you!")
name = input ("what is your name")
print ("I hope to code with you more" name "!")
| 3.25 | 3 |
kslurm/shell.py | pvandyken/kslurm | 1 | 12771168 | <reponame>pvandyken/kslurm
from __future__ import absolute_import, annotations
import importlib.resources as impr
import os
import subprocess as sp
from pathlib import Path
from shellingham import ShellDetectionFailure, detect_shell
class Shell:
"""
Represents the current shell.
"""
_shell = None
... | 1.90625 | 2 |
python/utils.py | SamoFMF/Slovenia---Settlements-Post-Offices | 0 | 12771169 | # Utilities
import pickle
from math import pi, cos, sin, asin, sqrt
def saveFile(filename, data):
with open(filename, "wb") as f:
pickle.dump(data, f)
def loadFile(filename):
with open(filename, "rb") as f:
return pickle.load(f)
def coordToDeg(coord):
return coord[0] + coord[1] / 60 + co... | 3.8125 | 4 |
navicatGA/test/test_real_application.py | lcmd-epfl/NaviCatGA | 1 | 12771170 | #!/usr/bin/env python3
from navicatGA.selfies_solver import SelfiesGenAlgSolver
from navicatGA.score_modifiers import score_modifier
from navicatGA.wrappers_selfies import (
sc2smiles,
sc2mol_structure,
mol_structure2depictions,
)
from navicatGA.quantum_wrappers_selfies import sc2gap
from navicatGA.wrapper... | 2.28125 | 2 |
Q02__/80_Wiggle_Sort/test.py | hsclinical/leetcode | 0 | 12771171 | <filename>Q02__/80_Wiggle_Sort/test.py<gh_stars>0
#!/usr/bin/python
from Solution import Solution
obj = Solution()
#A = [3,5,2,1,6,4]
A = [3,5,4,2,1,6,4]
out = obj.wiggleSort(A)
print(out)
| 3.109375 | 3 |
setup.py | dilwong/algorithms | 0 | 12771172 | <reponame>dilwong/algorithms
import setuptools
if __name__ == "__main__":
with open('requirements.txt', 'r') as f:
requirements = f.readlines()
requirements = [line.strip() for line in requirements if line.strip()]
setuptools.setup(name = 'algorithms',
version = '1.0.2',
author = '<NA... | 1.664063 | 2 |
atlas/workflow/scripts/convert_jgi2vamb_coverage.py | alienzj/atlas | 204 | 12771173 | <reponame>alienzj/atlas<filename>atlas/workflow/scripts/convert_jgi2vamb_coverage.py
#!/usr/bin/env python
import os
import sys
import re
def main(jgi_file):
# parsing input
header = {}
col2keep = ["contigName", "contigLen", "totalAvgDepth"]
with open(jgi_file) as inF:
for i, line in enumerate... | 2.65625 | 3 |
main.py | Adrian-at-CrimsonAuzre/madlib_generator | 0 | 12771174 | import madlib
for i in range(0, 100):
print(madlib.get_madlib())
| 2.203125 | 2 |
geostream/vector/serialize.py | karimbahgat/GeoStream | 0 | 12771175 | <reponame>karimbahgat/GeoStream
import sqlite3
from sqlite3 import Binary
from shapely.wkb import loads as wkb_loads
from shapely.geometry import shape
from shapely.geometry import Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon
def shapely_to_wkb(shp):
# shapely to wkb buffer
wkb = sh... | 2.5 | 2 |
karabo/simulation/station.py | i4Ds/Karabo-Pipeline | 0 | 12771176 | from karabo.simulation.coordinate_helper import east_north_to_long_lat
from karabo.simulation.east_north_coordinate import EastNorthCoordinate
class Station:
def __init__(self, position: EastNorthCoordinate,
parent_longitude: float = 0,
parent_latitude: float = 0,
... | 2.984375 | 3 |
src/insert.py | riggedCoinflip/danbooru_big_data | 0 | 12771177 | <reponame>riggedCoinflip/danbooru_big_data<filename>src/insert.py
import psycopg2
import time
from connect import connect
from load_dataset import yield_dataset
def main():
with connect() as conn:
datasets = yield_dataset()
for i, dataset in enumerate(datasets):
if i < 25000:
... | 2.421875 | 2 |
sorting_algorithms.py | edzelle/Projects | 0 | 12771178 | import numpy as np
import matplotlib.pyplot as plt
import timeit
import random
import math
def insertionSort(a):
for i in range(1,len(a)):
value = a[i]
pos = i
while (pos > 0 and value < a[pos-1]):
a[pos] = a[pos-1]
pos = pos-1
a[pos] = value
def countingSort(a,max):
m = max+1
co... | 3.84375 | 4 |
Barrier.py | yunfanz/ReionBub | 1 | 12771179 | <filename>Barrier.py
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
import numpy as np
from IO_utils import *
import matplotlib.pyplot as plt
import matplotlib, seaborn as sns
from scipy import ndimage, interpolate
from tocmfastpy import *
from skimage import measure, morphology, segmentation
from C... | 1.882813 | 2 |
shops/Shop.py | monoxacc/GPU_Crawler | 0 | 12771180 | from .Const import Const
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By... | 2.53125 | 3 |
openprocurement/auctions/tessel/tests/document.py | yevheniimoroziuk/openprocurement.auctions.tessel | 0 | 12771181 | # -*- coding: utf-8 -*-
import unittest
from openprocurement.auctions.tessel.tests.base import BaseTesselAuctionWebTest
from openprocurement.auctions.core.tests.base import snitch
from openprocurement.auctions.core.tests.document import (
AuctionDocumentResourceTestMixin,
AuctionDocumentWithDSResourceTestMixin... | 2.109375 | 2 |
algorithm/combinations.py | rishabhiitbhu/hackerrank | 0 | 12771182 | <reponame>rishabhiitbhu/hackerrank
l = [1,2,3,4]
def printCombo(l):
for j in range(1, len(l)+1):
for i in range(len(l)-1):
l[i],l[i+1]=l[i+1],l[i]
print(l)
for i in range(len(l)):
printCombo(l[i:])
| 3.75 | 4 |
python/astro_metadata_translator/translators/megaprime.py | lsst/astro_metadata_translator | 1 | 12771183 | # This file is part of astro_metadata_translator.
#
# Developed for the LSST Data Management System.
# This product includes software developed by the LSST Project
# (http://www.lsst.org).
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code... | 1.984375 | 2 |
list1/task1/main.py | ErykKrupa/metaheuristic-algorithms | 0 | 12771184 | <filename>list1/task1/main.py
from time import time
import numpy as np
def local_search(function, neighbour_function, max_execution_time):
end_time = time() + max_execution_time
best_solution = _get_naive_solution()
while time() < end_time:
result = function(best_solution)
neighbourhood = ... | 3.265625 | 3 |
apps/pretrained_protein/tape/data_process.py | Noisyntrain/PaddleHelix | 2 | 12771185 | <filename>apps/pretrained_protein/tape/data_process.py
# Copyright (c) 2020 PaddlePaddle Authors. 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.apa... | 2.46875 | 2 |
app/emotions/serializers.py | adiptdevtomar/emotions_backend | 0 | 12771186 | from rest_framework import serializers
from emotions import models
class EmotionsSerializer(serializers.ModelSerializer):
class Meta:
model = models.EmotionModel
fields = ['text'] | 2.0625 | 2 |
utils/HFUT/HFUTLog.py | Karry-ok/hfut-check-in | 7 | 12771187 | import logging
from rich.logging import RichHandler
from rich.traceback import install
install(max_frames=1)
FORMAT = '%(message)s'
logging.basicConfig(
level='INFO',
format=FORMAT,
datefmt='[%X]',
handlers=[RichHandler(rich_tracebacks=True)]
)
log = logging.getLogger('rich')
| 2.21875 | 2 |
temboardagent/plugins/monitoring/__init__.py | pierrehilbert/temboard-agent | 0 | 12771188 | <reponame>pierrehilbert/temboard-agent
import time
import os
import logging
import json
try:
from urllib2 import HTTPError
except ImportError:
from urllib.error import HTTPError
from temboardagent.toolkit import taskmanager
from temboardagent.routing import RouteSet
from temboardagent.toolkit.configuration imp... | 1.921875 | 2 |
update.py | forest-snow/clime-ui | 2 | 12771189 | <gh_stars>1-10
"""Update embeddings based on user feedback."""
from ast import literal_eval
import argparse
import csv
from itertools import islice
import json
import logging
import numpy as np
import os
import utils
import torch
import torch.optim as optim
from utils import save_embeds, load_embeds
def flatten(l)... | 2.1875 | 2 |
physio2go/exercises/urls.py | hamole/physio2go | 0 | 12771190 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.program_list,
name='program_list'
),
url(
regex=r'(?P<program_slug>[-\w]+)/$',
view=vi... | 1.953125 | 2 |
app/config.py | kowabunga314/LifeLoot | 0 | 12771191 | <gh_stars>0
from types import SimpleNamespace
# to get a string like this run:
# openssl rand -hex 32
SECRET_KEY = "<KEY>"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Tags for sorting requests in OpenAPI
TAGS = SimpleNamespace(
USER='Users',
GAME='Games',
AUTH='Authentication'
) | 2.453125 | 2 |
usher/tcp_server.py | lukecampbell/usher | 1 | 12771192 | <gh_stars>1-10
#!/usr/bin/env python
import gevent.monkey
gevent.monkey.patch_all()
from gevent.server import StreamServer
from usher.server import UsherServer
from usher.log import log, DEBUG
from struct import pack, unpack
'''
NOP Message
0x00
Acquire Message
'''
class MessageParser:
NOP_MESSAGE = 0x... | 2.3125 | 2 |
hard-gists/6094977/snippet.py | jjhenkel/dockerizeme | 21 | 12771193 | <reponame>jjhenkel/dockerizeme
import smbus
import getopt
import sys
from time import *
from time import gmtime, strftime
# TODO: Factor out all device_write calls to some PCF8574 specific module ...
# will be different with another io expander
# communication from expander to display: high nibble first, then ... | 2.59375 | 3 |
open_connect/connectmessages/tests/__init__.py | ofa/connect | 66 | 12771194 | """Custom TestCase and helpers for connectmessages tests."""
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory
from django.utils.timezone import ... | 2.265625 | 2 |
object_store_sdk/client.py | easyopsapis/easyops-api-python | 5 | 12771195 | <filename>object_store_sdk/client.py
# -*- coding: utf-8 -*-
import object_store_sdk.api.object_store.object_store_client
class Client(object):
def __init__(self, server_ip="", server_port=0, service_name=""):
self.object_store = object_store_sdk.api.object_store.object_store_client.ObjectStore... | 2.203125 | 2 |
tools/libs/utils.py | gurka/OldSchoolTibia | 3 | 12771196 | <reponame>gurka/OldSchoolTibia<gh_stars>1-10
def read_u8(f):
"""Reads an unsigned byte from the file object f.
"""
temp = f.read(1)
if not temp:
raise EOFError("EOF")
return int.from_bytes(temp, byteorder='little', signed=False)
def read_u16(f):
"""Reads a two byte unsigned value from... | 3.375 | 3 |
generator.py | kimvc7/DataSetGenerator | 0 | 12771197 | from random import randint
from matplotlib import pyplot as plt
import matplotlib
import argparse
import numpy as np
import scipy.ndimage
import json
import copy
import operator
VECTORS={0:(0,-1), 1:(1,-1),2:(1,0),3:(1,1),4:(0,1),5:(-1,1),6:(-1,0),7:(-1,-1)}
INV_VECTORS={(0,-1):0, (1,-1):1,(1,0):2,(1,1):3,(0,1):4,(-1... | 3.015625 | 3 |
python/2.OOP/2Inheritance/5.extends_any.py | dunitian/BaseCode | 25 | 12771198 | # 多继承引入
class Father(object):
def eat(self):
print("文雅的吃饭")
class Mom(object):
def run(self):
print("小碎步")
class Son(Father, Mom):
pass
def main():
son = Son()
son.eat()
son.run()
if __name__ == '__main__':
main()
| 3.734375 | 4 |
smc-monitoring/smc_monitoring/monitors/connections.py | kobaan/fp-NGFW-SMC-python | 17 | 12771199 | <filename>smc-monitoring/smc_monitoring/monitors/connections.py
"""
A connection query returns all currently connected sessions on the
given target.
Create a query to obtain all connections for a given engine::
query = ConnectionQuery('sg_vm')
Add a timezone to the query::
query.format.timezone('CST')
Add ... | 2.578125 | 3 |
netket/utils/types.py | pesvut/netket | 0 | 12771200 | <filename>netket/utils/types.py
# Copyright 2021 The NetKet Authors - 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
#
#... | 1.75 | 2 |
vang/bitbucket/tests/test_fork_repos.py | bjuvensjo/scripts | 6 | 12771201 | <reponame>bjuvensjo/scripts
from unittest.mock import call, patch
import pytest
from pytest import raises
from vang.bitbucket.fork_repos import fork_repo
from vang.bitbucket.fork_repos import fork_repos
from vang.bitbucket.fork_repos import main
from vang.bitbucket.fork_repos import parse_args
@patch('vang.bitbucke... | 2.265625 | 2 |
videos/urls.py | rupeshcode/youtube_scraper | 0 | 12771202 | from django.urls import include, path
from videos.views import manage_videos, manage_videos_search
app_name = 'videos'
urlpatterns = [
path('videos', manage_videos, name='manage_videos'),
path('videos/search', manage_videos_search, name='manage_videos_search')
]
| 1.84375 | 2 |
eodatasets/scripts/__init__.py | omad/eo-datasets | 0 | 12771203 | # coding=utf-8
from __future__ import absolute_import
import logging
def init_logging(debug):
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
if debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger('eodatasets').setLevel(logging.INFO)
| 2.078125 | 2 |
utils/utilities.py | INK-USC/procedural-extraction | 5 | 12771204 | <filename>utils/utilities.py
import re
def convert_int(alist):
"""
Convert all int-able string in list to int
"""
for i in range(len(alist)):
try:
alist[i] = int(alist[i])
except ValueError:
pass
return alist
prune_delimitor = re.compile("([\\s,.!?/\\'\"])")... | 3.9375 | 4 |
bubbleimg/obsobj/__init__.py | aileisun/bubblepy | 3 | 12771205 | <reponame>aileisun/bubblepy
# __init__.py
# ALS 2017/05/11
__all__ = ['obsobj', 'plainobj', 'sdss', 'hsc', 'objnaming', 'operator', 'imager']
from . import obsobj
from . import plainobj
from . import sdss
from . import hsc
from . import objnaming
from . import operator
from . import imager
from .obsobj import obsOb... | 1.09375 | 1 |
labml/monit.py | Asjidkalam/labml | 2 | 12771206 | from typing import Iterable, Sized, Collection, Callable, Tuple
from typing import Union, Optional, overload
from labml.internal.monitor import monitor_singleton as _internal
def clear():
_internal().clear()
def func(name, *,
is_silent: bool = False,
is_timed: bool = True,
is_partial... | 2.21875 | 2 |
tests/pipeline_runners/pipeline_runner_utils_test.py | elifesciences/sciencebeam | 272 | 12771207 | <gh_stars>100-1000
from unittest.mock import patch, MagicMock
import pytest
import sciencebeam.pipeline_runners.pipeline_runner_utils as pipeline_runner_utils_module
from sciencebeam.pipeline_runners.pipeline_runner_utils import (
get_remaining_file_list_for_args
)
BASE_TEST_PATH = '/tmp/test/conversion-pipelin... | 2.09375 | 2 |
test/remoting/webview-localfile/test.py | namaljayathunga/nw.js | 27 | 12771208 | <gh_stars>10-100
import time
import os
import urlparse, urllib
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *
def path2url(path):
return urlparse.urljoin(
'file:', urllib.pathname2url(path))
from selenium import webdriver
from se... | 2.921875 | 3 |
bleet/views.py | ntoll/facebaaak | 0 | 12771209 | import sys
from django.shortcuts import render, get_object_or_404
from bleet.models import Bleet
from users.models import Follow, Profile
from django.contrib.auth.models import User
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from django.contrib.aut... | 2.140625 | 2 |
2.With WebCam/rps.py | XiyuZhai97/Robotic-Hands-19 | 2 | 12771210 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
import numpy as np
import PIL.Image as Image
import time
import cv2
from pyfirmata import Ar... | 2.359375 | 2 |
test_number.py | bilaleluneis/LearningPython | 0 | 12771211 | from unittest import TestCase
from class_odd_and_prime_number import Number
class TestNumber(TestCase):
def test_number_init(self):
valid_number = Number(5)
self.assertEqual(valid_number.value, 5)
| 3.515625 | 4 |
tests/lists_tests/test_contains.py | lycantropos/cppbuiltins | 1 | 12771212 | <filename>tests/lists_tests/test_contains.py
from typing import Any
from hypothesis import given
from tests.utils import (AlternativeNativeListsPair,
equivalence)
from . import strategies
@given(strategies.lists_pairs, strategies.objects)
def test_basic(pair: AlternativeNativeListsPair, val... | 2.296875 | 2 |
tests/test_activities.py | KE-works/pykechain | 5 | 12771213 | <reponame>KE-works/pykechain
import os
import warnings
from datetime import datetime
from unittest import skip, skipIf
import pytest
import pytz
import requests
from pykechain.enums import (
ActivityType,
ActivityStatus,
ActivityClassification,
Category,
activity_root_name_by_classification,
A... | 1.953125 | 2 |
setup.py | asmiyusau/ShazamIO | 111 | 12771214 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="shazamio",
version="0.0.5",
author="dotX12",
description="Is a FREE asynchronous library from reverse engineered Shazam API written in Python 3.6+ with asyncio and aiohttp. I... | 1.679688 | 2 |
chrome/installer/mac/universalizer.py | zealoussnow/chromium | 14,668 | 12771215 | #!/usr/bin/env python
# coding: utf-8
# Copyright 2020 The Chromium 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 argparse
import errno
import filecmp
import os
import plistlib
import shutil
import stat
import subprocess
impo... | 2.484375 | 2 |
problem0751.py | kmarcini/Project-Euler-Python | 0 | 12771216 | <filename>problem0751.py
###########################
#
# #751 Concatenation Coincidence - Project Euler
# https://projecteuler.net/problem=751
#
# Code by <NAME>
#
###########################
| 1.609375 | 2 |
course_parallel_computer/Section_1_Python_Parallel_Programming_Solutions/Section2/using_with_statement.py | software-foundations/learning-distributed-systems | 0 | 12771217 | <filename>course_parallel_computer/Section_1_Python_Parallel_Programming_Solutions/Section2/using_with_statement.py
import threading
import logging
"""
Mostra que um lock pode ser adquirido usando with ao invés de usar lock.aquire()
Isso foi testado para lock, RLock, Semáforo, Condição e semáforo
"""
logging.ba... | 3.75 | 4 |
TEMpcPlot/tables/pt_tables.py | Prestipino/TEMpcPlot | 0 | 12771218 | <filename>TEMpcPlot/tables/pt_tables.py
#!usr/bin/python
# -*- coding: utf-8 -*-
# pt_table.py
"""set of funcion for atomic weight calculation
the modules contain some data
N_av constant avogadro number
Faraday constant Faraday constant (C/mol) n coulomb equal to a mole of e-
elements ... | 2.71875 | 3 |
test/test_navmesh.py | WGW101/habitat_sim2real | 0 | 12771219 | <filename>test/test_navmesh.py
import habitat_sim
from habitat_sim.agent import ActionSpec, ActuationSpec
sim_cfg = habitat_sim.SimulatorConfiguration()
sim_cfg.scene.id = "data/test/4d6ab9cc04f24c87aed802698f957b7a.glb"
sim_cfg.allow_sliding = False
ag_cfg = habitat_sim.agent.AgentConfiguration()
color_spec = habita... | 2.03125 | 2 |
simulator/opendc-experiments/opendc-experiments-allocateam/tools/plot/metrics/job_makespan.py | allocateam/opendc | 0 | 12771220 | from .metric import Metric, metric_path
import pandas as pd
import math
class JobMakespanMetric(Metric):
def __init__(self, plot, scenarios):
super().__init__(plot, scenarios)
self.name = "job_makespan"
self.x_axis_label = "Job makespan (seconds)"
def get_data(self, scenario):
... | 2.796875 | 3 |
src/monitors/optim_monitors.py | isaachenrion/jets | 9 | 12771221 | <filename>src/monitors/optim_monitors.py
import torch
from .meta import Collect
class GradNorm(Collect):
def __init__(self, **kwargs):
super().__init__('grad_norm', fn='last', **kwargs)
def call(self, grads=None, **kwargs):
#grads = [p.grad for p in model.parameters()]
#grads = torch.c... | 2.234375 | 2 |
tests/test_app.py | jackwardell/Flask-Model-Management | 2 | 12771222 | <filename>tests/test_app.py
import pytest
from flask import Flask
from flask_model_management.domain import CRUD_OPERATIONS
from flask_model_management.manager import ModelManager as ModelManagement
from tests.models import Address
from tests.models import db
from tests.models import populate
from tests.models import ... | 2.53125 | 3 |
model.py | rethinkdb/rethinkdb-example-webpy-blog | 16 | 12771223 | <gh_stars>10-100
# The [web.py](http://webpy.org/) (really basic) [blog example](http://webpy.org/src/blog/0.3)
# using **RethinkDB as the backend for web.py applications**.
#
# For details about the complete stack, installation, and running the app see
# the [README](https://github.com/rethinkdb/rethinkdb-example-web... | 2.75 | 3 |
demo/demo.py | chupati/stanfordgap | 0 | 12771224 | from sg.StanfordGap import StanfordGap
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import datasets
class StanfordGapDemo(object):
def run(self):
"""
Run the Stanford Gap Statistic Analysis on the iris data set presented in
http://sciki... | 3.078125 | 3 |
test/py/inters/test16.py | Ahdhn/lar-cc | 1 | 12771225 | <gh_stars>1-10
""" Generating the LAR of a set of non-intersecting cycles """
from larlib import *
sys.path.insert(0, 'test/py/inters/')
from test15 import *
cells = cellsFromCycles(latticeArray)
CV = AA(COMP([list,set,CAT]))(EVs)
EVdict = dict(zip(EV,range(len(EV))))
FE = [[EVdict[edge] for edge in cycle] for cycle ... | 2.3125 | 2 |
epson_projector/main.py | xWizard360/epson_projector | 0 | 12771226 | <reponame>xWizard360/epson_projector<filename>epson_projector/main.py
"""Main of Epson projector module."""
import logging
from .const import (BUSY, TIMEOUT_TIMES)
from .lock import Lock
_LOGGER = logging.getLogger(__name__)
class Projector:
"""
Epson projector class.
Control your projector with Pytho... | 2.78125 | 3 |
ds/beis_indicators/travel/make_travel_work.py | nestauk/beis-indicators | 4 | 12771227 | import logging
import numpy as np
import glob
from beis_indicators import project_dir
from beis_indicators.geo import NutsCoder, LepCoder
from beis_indicators.indicators import points_to_indicator, save_indicator
from beis_indicators.travel.travel_work_processing import get_travel_work_data
import pandas a... | 2.28125 | 2 |
snake4.py | JoaoBatistaJr/Pygame-SnakeGame | 0 | 12771228 | <gh_stars>0
import pygame, random
from pygame.locals import *
def on_grid_random():
x = random.randint(0,59)
y = random.randint(0,59)
return (x * 10, y * 10)
def collision(c1, c2):
return (c1[0] == c2[0]) and (c1[1] == c2[1])
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
#Definição das cores
BRANCO = pygame.Co... | 3.25 | 3 |
ddtrace/internal/module.py | ysk24ok/dd-trace-py | 0 | 12771229 | from collections import defaultdict
from os.path import abspath
from os.path import expanduser
from os.path import isdir
from os.path import isfile
from os.path import join
import sys
from types import ModuleType
from typing import Any
from typing import Callable
from typing import DefaultDict
from typing import Dict
f... | 1.929688 | 2 |
test/variational/test_batch_decoupled_variational_strategy.py | nzw0301/gpytorch | 0 | 12771230 | <gh_stars>0
#!/usr/bin/env python3
import unittest
import torch
import gpytorch
from gpytorch.test.variational_test_case import VariationalTestCase
def likelihood_cls():
return gpytorch.likelihoods.GaussianLikelihood()
def strategy_cls(model, inducing_points, variational_distribution, learn_inducing_location... | 2.265625 | 2 |
gpytorch/variational/ciq_variational_strategy.py | lrast/gpytorch | 2 | 12771231 | #!/usr/bin/env python3
from typing import Optional, Tuple
import torch
from .. import settings
from ..distributions import Delta, MultivariateNormal
from ..lazy import DiagLazyTensor, MatmulLazyTensor, SumLazyTensor, lazify
from ..module import Module
from ..utils import linear_cg
from ..utils.broadcasting import _m... | 2.25 | 2 |
core/migrations/0005_sitecontacted.py | andrsko/convabout-server-v1 | 0 | 12771232 | # Generated by Django 3.0.6 on 2020-06-26 09:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sessions', '0001_initial'),
('core', '0004_auto_20200603_1414'),
]
operations = [
migrations.Create... | 1.757813 | 2 |
test/test_teams.py | Galtozzy/basketball_reference_scraper | 191 | 12771233 | <filename>test/test_teams.py
import unittest
from basketball_reference_scraper.teams import get_roster, get_team_stats, get_opp_stats, get_roster_stats, get_team_misc
class TestTeams(unittest.TestCase):
def test_get_roster(self):
df = get_roster('GSW', 2019)
curry_df = df[df['PLAYER']=='<NAME>']
... | 3.046875 | 3 |
dtf/affiliates/views.py | WebPowerLabs/django-trainings | 0 | 12771234 | from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.contrib.auth.decorators import login_required
from utils.views import PermissionMixin
from .models import Partner, PartnerProduct
class PartnerListView(PermissionMixin, ListView):
model = Partner
de... | 2.015625 | 2 |
tests/task/nlp/test_masked_language_modeling.py | techthiyanes/lightning-transformers | 0 | 12771235 | <filename>tests/task/nlp/test_masked_language_modeling.py
import sys
from unittest.mock import MagicMock
import pytest
import pytorch_lightning as pl
from transformers import AutoTokenizer
from lightning_transformers.task.nlp.masked_language_modeling import (
MaskedLanguageModelingDataConfig,
MaskedLanguageMo... | 2.265625 | 2 |
math220/Homework06/ten-digit-problem.py | oniani/udmath | 0 | 12771236 | """
Author: <NAME>
Purpose: Homework (problem 8)
NOTE: I have not included the algorithm to check
that 6210001000 is indeed the only number that
meets the conditions. It needs a bit more explanation
for optimizations so I decided to take it out.
"""
def check(ten_digit_number):
"""
Function to check whether ... | 3.671875 | 4 |
model/m3d_model.py | SB-BISS/RLACOSarsaLambda | 7 | 12771237 | <reponame>SB-BISS/RLACOSarsaLambda
import numpy as np
import math
'''
@author <NAME>
This is a class whose only function is to provide the next_state for the mountain 3D car problem
basically, this is a model that the agent can use to query what will happen is an action is performed.
In order to be able... | 2.9375 | 3 |
project-euler/0018_maximum_path_sum.py | alenic/comprosol | 0 | 12771238 | s = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 3... | 2.71875 | 3 |
datamine/loaders/sofr.py | Saran33/datamine_python | 39 | 12771239 | from . import Loader
import pandas as pd
class SOFROISLoader(Loader):
dataset = 'SOFR'
fileglob = 'SOFR_OIS_*.csv'
columns = ['Trade Date', 'Exchange Code', 'Currency','Commodity Code',
'Short Description','Long Description', 'Curve Date', 'Offset',
'Discount Factor', 'Fo... | 3.078125 | 3 |
flak/cli.py | avdd/flak | 0 | 12771240 | <filename>flak/cli.py
# -*- coding: utf-8 -*-
import os
import sys
from threading import Lock, Thread
from functools import update_wrapper
import click
from ._compat import iteritems, reraise
class AppNotFound(click.UsageError):
pass
def find_best_app(module):
from .app import Flak
# search for the mos... | 2.0625 | 2 |
models/_resnet.py | yhlhit/dann | 0 | 12771241 | <filename>models/_resnet.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn.init as init
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... | 2.921875 | 3 |
python/isarnproject/sketches/spark/tdigest.py | SemanticBeeng/isarn-sketches-spark | 26 | 12771242 | <reponame>SemanticBeeng/isarn-sketches-spark
import sys
import random
import itertools as it
from bisect import bisect_left, bisect_right
from pyspark.sql.types import UserDefinedType, StructField, StructType, \
ArrayType, DoubleType, IntegerType
from pyspark.sql.column import Column, _to_java_column, _to_seq
from... | 2.375 | 2 |
myapps/jupyter/TensorFlow/Distributed/distributed_cnn.py | alonsoir/pipeline | 1 | 12771243 | <gh_stars>1-10
import tensorflow as tf
import numpy as np
# Modules required for file download and extraction
import os
import sys
import tarfile
from six.moves.urllib.request import urlretrieve
from scipy import ndimage
outdir = '/tmp/pipeline/datasets/notmist/'
def maybe_download(filename, url, force=False):
""... | 2.6875 | 3 |
src/design_patterns/solid/lsp/email_broadcaster_bad.py | schuna/design-patterns-python | 0 | 12771244 | from design_patterns.solid.lsp.common import User, SubscribedUser
class EmailBroadcaster:
def __init__(self):
print("Email Broadcaster")
def broadcast(self, event, user: User):
return f"Event: {event} to User: {user.name}"
class SubscriptionEmailBroadcaster(EmailBroadcaster):
def __init... | 2.609375 | 3 |
mathematics/number-theory/salary-blues.py | PingHuskar/hackerrank | 41 | 12771245 | <reponame>PingHuskar/hackerrank
# Mathematics > Number Theory > Salary Blues
# Help manager of HackerX company to normalize salaries.
#
# https://www.hackerrank.com/challenges/salary-blues/problem
# https://www.hackerrank.com/contests/infinitum-apr14/challenges/salary-blues
# challenge id: 1833
#
from math import gcd
... | 3.0625 | 3 |
GWP/QTGB/traj.py | binggu56/qmd | 0 | 12771246 | #!/usr/bin/python
import numpy as np
import pylab as plt
import seaborn as sns
sns.set_context("poster")
#with open("traj.dat") as f:
# data = f.read()
#
# data = data.split('\n')
#
# x = [row.split(' ')[0] for row in data]
# y = [row.split(' ')[1] for row in data]
#
# fig = plt.figure()
#
# ax1 = f... | 2.796875 | 3 |
examples/ble_hid_periph.py | nnja/Adafruit_CircuitPython_BLE | 0 | 12771247 | """
This example acts as a keyboard to peer devices.
"""
# import board
import sys
import time
import adafruit_ble
from adafruit_ble.advertising import Advertisement
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.standard.hid import HIDService
from adafruit_ble.s... | 3.078125 | 3 |
python/average_levels_of_binary_tree.py | anishLearnsToCode/leetcode-algorithms | 17 | 12771248 | <reponame>anishLearnsToCode/leetcode-algorithms<gh_stars>10-100
# Definition for a binary tree node.
from typing import List
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
... | 3.640625 | 4 |
lib/surface/asset/analyze_iam_policy.py | google-cloud-sdk-unofficial/google-cloud-sdk | 2 | 12771249 | <gh_stars>1-10
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | 1.734375 | 2 |
might_useful.py | lyclyc52/nerf_with_slot_attention | 1 | 12771250 | <reponame>lyclyc52/nerf_with_slot_attention<gh_stars>1-10
# For EM
# slots = slots.T
# position = position.T
# with torch.no_grad():
# for i in range(20):
# z = torch.matmul(f, slots) # NxK
# z_p = torch.matmul(f_p, position)
# z = z + w * z_p
# z = F.softmax(z, dim=-1) ... | 1.96875 | 2 |