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 |
|---|---|---|---|---|---|---|
interprete/src/models/graphcodebert/model.py | serjtroshin/PLBART | 0 | 26100 | from pathlib import Path
from typing import List
import torch
from transformers import AutoModel, AutoTokenizer
from interprete.src.models.model import Model, ModelOutput
from interprete.src.models.utils import to_cpu
class GraphCodeBertModel(Model):
def __init__(self, args=[], type="GraphCodeBert"):
su... | 2.390625 | 2 |
app/verbose.py | erikosmond/knights_tour | 0 | 26101 | class Verbose(object):
Initialized = False
def __init__(self, verbosity, show_info=False):
assert type(verbosity) is int, "verbose takes an integer value of 0-1023"
self.verbose_int = verbosity
self.info = """
bit 0[-1](1) - max/min values
bit 1[-2](2) - r... | 3.546875 | 4 |
src/core/game.py | Swartz-42/Irale_Game_Py | 0 | 26102 | import pygame
from src.entities import Player
from src.utils import DialogBox
from src.map import MapManager
class Game:
def __init__(self):
super().__init__()
# creer la fenetre du jeu
self.screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("Irale - Le je... | 3 | 3 |
diagnnose/models/transformer_lm.py | Kalsir/diagNNose | 0 | 26103 | <filename>diagnnose/models/transformer_lm.py
from functools import reduce
from typing import List, Optional, Union
import torch
from torch import Tensor
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassificatio... | 1.890625 | 2 |
usbcan/somebus.py | laigui/usbcan | 0 | 26104 | <gh_stars>0
# -*- coding: utf-8 -*-
''' somebus.py: Somebus USBCAN-II adaptor driver class.
Copyright (C) 2019 <NAME> <<EMAIL>>'''
from ctypes import *
class VciInitConfig(Structure):
"""
INIT_CONFIG结构体定义了初始化CAN的配置
"""
_fields_ = [("AccCode", c_ulong), # 验收码,后面是数据类型
("AccMas... | 2.203125 | 2 |
PyFlow/Ui/StyleSheetEditor.py | pedroCabrera/PyFlow | 7 | 26105 | from Qt import QtWidgets
from Qt import QtCore
from widgets.pc_HueSlider import pc_HueSlider,pc_GradientSlider
if __name__ == '__main__':
import sys
sys.path.append("..")
import stylesheet
else:
from .. import stylesheet
from .. import resources
class StyleSheetEditor(QtWidgets.QWidget):
"""Style Sheet Editor... | 2.5625 | 3 |
test/win/compiler-flags/calling-convention.gyp | chlorm-forks/gyp | 2,151 | 26106 | <reponame>chlorm-forks/gyp
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_cdecl',
'type': 'loadable_module',
'msvs_settings': {
'VCCLCompiler... | 1.296875 | 1 |
integrationtest/vm/virtualrouter/volume/test_add_volume.py | sherry546/zstack-woodpecker | 2 | 26107 | <gh_stars>1-10
'''
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import os
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()
def test():
test_util.test_... | 1.859375 | 2 |
agents/base_agent.py | IanYHWu/msc_2021 | 0 | 26108 |
class BaseAgent(object):
"""
Class for the basic agent objects.
"""
def __init__(self,
env,
actor_critic,
storage,
device):
"""
env: (gym.Env) environment following the openAI Gym API
"""
self.env = en... | 2.84375 | 3 |
malpi/dkwm/gym_envs/__init__.py | Bleyddyn/malpi | 5 | 26109 | from gym.envs.registration import register
from malpi.dkwm.gym_envs.dkwm_env import DKWMEnv
register(
id='dkwm-v0',
entry_point='malpi.dkwm.gym_envs:DKWMEnv',
)
| 1.367188 | 1 |
ProjectEuler100/Problem_003.py | shiv-1998/EulerProject | 0 | 26110 | #!/bin/python3
import sys
import math
def isPrime(n):
if n==2 or n==3 or n==5 or n==7 or n==11 or n==13 or n==13 or n==17 or n==19:
return True
upperLimit = math.ceil(math.sqrt(n))+1
for i in range(2,upperLimit):
if n%i==0:
return False
return True
t = int(input().strip())... | 3.921875 | 4 |
opcua/__init__.py | minix1234/hacore_opcua | 4 | 26111 | """Support for OPCUA"""
import logging
import voluptuous as vol
from opcua import Client, ua
from homeassistant.const import (
ATTR_STATE,
CONF_URL,
CONF_NAME,
CONF_TIMEOUT,
CONF_USERNAME,
CONF_PASSWORD,
EVENT_HOMEASSISTANT_STOP,
EVENT_HOMEASSISTANT_START,
)
import homeassistant.hel... | 2.015625 | 2 |
pysnmp-with-texts/RBT-MIB.py | agustinhenze/mibs.snmplabs.com | 8 | 26112 | #
# PySNMP MIB module RBT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | 1.539063 | 2 |
fixture/take_datetime.py | dondemonz/audit_lite | 0 | 26113 | <reponame>dondemonz/audit_lite<gh_stars>0
import datetime as dt
from datetime import timedelta
def take_datetimes():
m = dt.datetime.now() + timedelta(seconds=1)
starttime = m.strftime("%Y-%m-%d %H:%M:%S")
m2 = dt.datetime.now() + timedelta(seconds=2)
starttime2 = m2.strftime("%Y-%m-%d %H:%M:%S")
m... | 2.796875 | 3 |
shelly-static-ip.py | asillye/shelly-static-ip | 0 | 26114 | import threading
import traceback
import logging
import requests
from json.decoder import JSONDecodeError
from ping3 import ping
logging.basicConfig(level=logging.INFO)
GATEWAY_IP = "192.168.100.1"
STATIC_IP_MIN = 200
STATIC_IP_MAX = 254
lastDot = GATEWAY_IP.rfind(".")
ipAddressBase = GATEWAY_IP[0:lastDot+1]
threadL... | 2.5625 | 3 |
src/problems/other/nearest_square.py | E1mir/PySandbox | 0 | 26115 | def solution(num):
if num < 0:
raise ValueError
if num == 1:
return 1
k = None
for k in range(num // 2 + 1):
if k ** 2 == num:
return k
elif k ** 2 > num:
return k - 1
return k
def best_solution(num):
if num < 0:
raise ValueEr... | 3.6875 | 4 |
src/tarski/fstrips/hybrid/differential_constraints.py | phoeft670/tarski | 29 | 26116 |
from ...syntax import BuiltinFunctionSymbol, CompoundTerm
from . import errors as err
class DifferentialConstraint:
""" A (possibly lifted) reaction """
def __init__(self, language, name, parameters, condition, variate, ode):
self.name = name
self.language = language
self.parameters ... | 2.671875 | 3 |
imix/models/encoder/lcgnencoder.py | linxi1158/iMIX | 23 | 26117 | <reponame>linxi1158/iMIX
import numpy as np
import torch.nn.functional as F
from torch import Tensor
from typing import Tuple
from ..builder import ENCODER
import torch.nn as nn
import torch
@ENCODER.register_module()
class LCGNEncoder(nn.Module):
def __init__(self, WRD_EMB_INIT_FILE: str, encInputDropout: float... | 2.421875 | 2 |
USB/python/test-usb2020.py | wjasper/Linix_Drivers | 100 | 26118 | #! /usr/bin/python3
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#... | 2.734375 | 3 |
archive/lym_project/treeano-master/benchmarks/fractional_max_pooling.py | peterdonnelly1/u24_lymphocyte | 45 | 26119 | <filename>archive/lym_project/treeano-master/benchmarks/fractional_max_pooling.py
import numpy as np
import theano
import theano.tensor as T
import treeano.nodes as tn
from treeano.sandbox.nodes import fmp
fX = theano.config.floatX
# TODO change me
node = "fmp2"
compute_grad = True
if node == "mp":
n = tn.MaxPool... | 2.15625 | 2 |
warranty.py | TannerFilip/dell-warranty | 0 | 26120 | #!/bin/python3
'''
USAGE:
$ python warranty.py list.txt
1. Set "apikey" to the API key obtained from Dell TechDirect.
2. Create file with serial numbers, one per line, no line endings
'''
import time
import requests
import fileinput
import sys
fileName = sys.argv[1]
api_url = 'https://sandbo... | 2.828125 | 3 |
tests/telemetry/decorators_test.py | trevorgrayson/telemetry | 3 | 26121 | <reponame>trevorgrayson/telemetry<filename>tests/telemetry/decorators_test.py<gh_stars>1-10
from pytest import raises
import telemetry
REPORT_NAME = 'some.key'
meter = telemetry.get_telemeter(__name__)
@meter.catch('some_report')
def exception_prone(ii):
return 1/ii
class TestsExcept:
def test_catch_pass... | 2.640625 | 3 |
SVGPs/kernels.py | vincentadam87/SVGPs | 3 | 26122 | <filename>SVGPs/kernels.py
# Copyright 2016 <NAME>, alexggmatthews
#
# 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 applic... | 2.40625 | 2 |
setup.py | schoenemeyer/pyheatmagic | 0 | 26123 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, "README.rst")) as f:
long_description = f.read()
setup(
... | 1.375 | 1 |
certificator/meetup/__init__.py | lamenezes/certificator | 19 | 26124 | <reponame>lamenezes/certificator<filename>certificator/meetup/__init__.py
from datetime import datetime as dt
from .client import MeetupClient
from ..certificator import BaseCertificator
from .models import Event
class MeetupCertificator(BaseCertificator):
def __init__(self, urlname, event_id, api_key, **kwargs)... | 2.3125 | 2 |
kolab/yk/yk2.py | KuramitsuLab/kolab | 0 | 26125 | <filename>kolab/yk/yk2.py
from os import read
import random
import sys
import pegtree as pg
import argparse
import csv
from pegtree.optimizer import optimize
peg = pg.grammar('yk.tpeg')
parse = pg.generate(peg)
parser = argparse.ArgumentParser(description='yk for Parameter Handling')
parser.add_argument('--notConv',... | 2.375 | 2 |
Lesson_6_Homework.py | verafes/python_training | 0 | 26126 | # Homework #6. Loops
print("--- Task #1. 10 monkeys")
# Task #1. Write a program that output the following string: "1 monkey 2 monkeys ... 10 monkeys".
for x in range(1, 11):
if x == 1:
monkey = f"{x} monkey "
else:
monkey = monkey + f"{x} monkeys "
print(monkey.strip())
print("\n--- Task #2. Countdow... | 4.46875 | 4 |
creel_portal/api/filters/FN125Tag_Filter.py | AdamCottrill/CreelPortal | 0 | 26127 | import django_filters
from .filter_utils import ValueInFilter
from ...models import FN125_Tag
from .FishAttr_Filter import FishAttrFilters
class FN125TagFilter(FishAttrFilters):
"""A filter set class for lamprey data. Inherits all of the filters in
FishAttrs and add some that are specific to Tag attribute... | 2.21875 | 2 |
testing/test_file_path.py | xapple/autopaths | 0 | 26128 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Some simple tests for the autopaths package.
You can run this file like this:
ipython -i -- ~/repos/autopaths/test/test_file_path.py
"""
# Built-in modules #
import os, inspect
# Get current directory (works always) #
file_name = os.path.abspath((inspect.stack()... | 2.34375 | 2 |
RecoEgamma/EgammaPhotonProducers/python/propOppoMomentumWithMaterialForElectrons_cfi.py | ckamtsikis/cmssw | 852 | 26129 | import FWCore.ParameterSet.Config as cms
import TrackingTools.MaterialEffects.OppositeMaterialPropagator_cfi
#PropagatorWithMaterialESProducer
oppositeToMomElePropagator = TrackingTools.MaterialEffects.OppositeMaterialPropagator_cfi.OppositeMaterialPropagator.clone(
Mass = 0.000511,
ComponentName = '... | 1.078125 | 1 |
test/__init__.py | gjhiggins/rdflib-sqlalchemy | 112 | 26130 | from rdflib import plugin
from rdflib import store
plugin.register(
"SQLAlchemy",
store.Store,
"rdflib_sqlalchemy.store",
"SQLAlchemy",
)
| 1.320313 | 1 |
Others/jsc/jsc2019-qual/b.py | KATO-Hiro/AtCoder | 2 | 26131 | # -*- coding: utf-8 -*-
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10 ** 9 + 7
ans = 0
# See:
# https://www.youtube.com/watch?v=JTH27weC38k
# https://atcoder.jp/contests/jsc2019-qual/submissions/7107452
# Key Insight
# 2つの... | 2.78125 | 3 |
Python-Programs/dicord.py-bot-suggest-commands/main.py | adityaverma121/Simple-Programs | 71 | 26132 | import difflib
import discord
from discord.ext import commands
from discord.ext.commands import CommandNotFound
intents = discord.Intents.all()
client = commands.Bot(command_prefix="+", intents=intents, help_command=None)
@client.event
async def on_ready():
print("Bot Online")
@client.event
async def on_comma... | 2.625 | 3 |
hummingbot/connector/exchange/bitfinex/bitfinex_api_user_stream_data_source.py | joedomino874/hummingbot | 37 | 26133 | import asyncio
import logging
import time
from typing import Optional, List
from hummingbot.core.data_type.user_stream_tracker_data_source import \
UserStreamTrackerDataSource
from hummingbot.logger import HummingbotLogger
from hummingbot.connector.exchange.bitfinex.bitfinex_order_book import BitfinexOrderBook
fro... | 1.898438 | 2 |
test_mersenne.py | Crulzor/algorithms-python-intro-ex | 0 | 26134 | <reponame>Crulzor/algorithms-python-intro-ex<filename>test_mersenne.py
from mersenne import generatePotentialMP, isPrime
def test_generatePotentialMP():
assert(generatePotentialMP(2) == 3)
assert(generatePotentialMP(1) ==1)
def test_isPrime():
assert(isPrime(7))
assert(isPrime(2))
assert(isPrime(3... | 2.734375 | 3 |
sim21/provider/base.py | kpatvt/sim21 | 7 | 26135 | <reponame>kpatvt/sim21<filename>sim21/provider/base.py
import math
import sys
import numpy as np
from numpy import ndarray
from sim21.data import chemsep
from sim21.data.chemsep_consts import GAS_CONSTANT
from numba import njit
from sim21.provider.generic import calc_ig_props
from sim21.provider.flash.basic import ba... | 1.765625 | 2 |
server/routers/auth.py | CraftyChimera/nittfest-site | 0 | 26136 | """
Auth route
"""
import requests
from fastapi import APIRouter, HTTPException
from fastapi.param_functions import Depends
from sqlalchemy.orm import Session
from config.database import get_database
from config.logger import logger
from config.settings import settings
from server.controllers.auth import get_departme... | 2.46875 | 2 |
isc_dhcp_leases/test_lease6.py | dholl/python-isc-dhcp-leases | 111 | 26137 | <gh_stars>100-1000
import datetime
from unittest import TestCase
from isc_dhcp_leases.iscdhcpleases import Lease6, utc
from freezegun import freeze_time
__author__ = '<NAME> <<EMAIL>>'
class TestLease6(TestCase):
def setUp(self):
self.lease_time = datetime.datetime(2015, 8, 18, 16, 55, 37, tzinfo=utc)
... | 2.40625 | 2 |
dril_pack/dril.py | RuohanW/il_baseline_fork | 0 | 26138 | <reponame>RuohanW/il_baseline_fork<filename>dril_pack/dril.py
import os
import numpy as np
import torch
import gym
import pandas as pd
from stable_baselines3.common.running_mean_std import RunningMeanStd
from collections import defaultdict
from torch.utils.data import DataLoader, TensorDataset
# This file creates t... | 2.234375 | 2 |
graphlearn/python/values.py | hansugu/graph-learn | 1 | 26139 | <gh_stars>1-10
# Copyright 2020 Alibaba Group Holding Limited. 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
#
# Unle... | 2.203125 | 2 |
.github/scripts/version_number_update.py | wattch/FreeRTOS | 0 | 26140 | import os
import re
import argparse
from collections import defaultdict
_AFR_COMPONENTS = [
'demos',
'freertos_kernel',
os.path.join('libraries','abstractions','ble_hal'),
os.path.join('libraries','abstractions','common_io'),
os.path.join('libraries','abstractions','pkcs11'),
os.path.join('lib... | 1.625 | 2 |
Medium/452.MinimumNumberofArrowstoBurstBalloons.py | YuriSpiridonov/LeetCode | 39 | 26141 | <filename>Medium/452.MinimumNumberofArrowstoBurstBalloons.py
"""
There are some spherical balloons spread in two-dimensional space. For each
balloon, provided input is the start and end coordinates of the horizontal
diameter. Since it's horizontal, y-coordinates don't matter, and hence the
x-coordina... | 3.84375 | 4 |
pl_extension/callbacks/speed.py | DuinoDu/pl-extension | 0 | 26142 | import logging
from pytorch_lightning.callbacks.base import Callback
__all__ = ["Speed"]
logger = logging.getLogger(__name__)
class Speed(Callback):
r"""
Training speed callback, require 'simple' or 'advanced' profiler.
"""
def on_train_batch_end(
self, trainer, pl_module, outputs, batch... | 2.53125 | 3 |
spectacles/validators/validator.py | felipefrancisco/spectacles | 150 | 26143 | <reponame>felipefrancisco/spectacles
from typing import Optional, List
from abc import ABC, abstractmethod
from spectacles.client import LookerClient
from spectacles.lookml import Project, Model, Dimension
from spectacles.select import is_selected
from spectacles.exceptions import LookMlNotFound
class Validator(ABC):... | 2.703125 | 3 |
python/periodic-web-scrapper/scraper/Scraper.py | MarioCodes/ProyectosClaseDAM | 0 | 26144 | '''
Created on Apr 18, 2018
@author: msanchez
'''
from scraper.RequestScraper import RequestScraper
from scraper.HTMLFilter import HTMLFilter
from scraper.NewsFilter import NewsFilter
from scraper.utilities.WebUtilities import WebUtilities
class Scraper(object):
''' Full scrap operation. Downloads the request wit... | 3.25 | 3 |
cabot_alert_pushover/models.py | dnelson/cabot-alert-pushover | 0 | 26145 | <reponame>dnelson/cabot-alert-pushover
from django.db import models
from django.conf import settings
from django.template import Context, Template
from cabot.cabotapp.alert import AlertPlugin, AlertPluginUserData
from os import environ as env
import requests
pushover_alert_url = "https://api.pushover.net/1/messages.... | 2.3125 | 2 |
mezzanine_faq/templatetags/faq_tags.py | fpytloun/mezzanine-faq | 0 | 26146 | # -*- coding: utf-8 -*-
from django import template
from mezzanine.conf import settings
from mezzanine_faq.models import FaqPage
register = template.Library()
@register.inclusion_tag('includes/faqlist.html')
def faq_list(**kwargs):
page = FaqPage.objects.get(**kwargs)
return {
'page': page,
... | 2.109375 | 2 |
easy/543-Diameter of Binary Tree.py | Davidxswang/leetcode | 2 | 26147 | <filename>easy/543-Diameter of Binary Tree.py<gh_stars>1-10
"""
https://leetcode.com/problems/diameter-of-binary-tree/
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may no... | 4.1875 | 4 |
hsf_website_helpers/bin/hsf_reformat_training_events.py | HSF/website-helpers | 0 | 26148 | #!/usr/bin/env python3
"""
Quick script to read all training schools from data file and write them out
again to e.g. update the formatting.
"""
import argparse
from hsf_website_helpers.events.event import EventDatabase
from hsf_website_helpers.util.cli import add_website_home_option
def get_parser() -> argparse.Ar... | 3.25 | 3 |
clothstream/styletags/urls.py | julienaubert/clothstream | 0 | 26149 | <gh_stars>0
from clothstream.lib.rest import SharedAPIRootRouter
from .views import ItemStyleTagCreate, StyleTagList
router = SharedAPIRootRouter()
router.register(r'styletag-item/create', ItemStyleTagCreate, base_name='itemstyletag-create')
router.register(r'styletags', StyleTagList)
| 1.617188 | 2 |
aws_automation/s3.py | VCCRI/Scavenger | 4 | 26150 | # a module that wraps some of the S3 commands
import boto3
from botocore.exceptions import ClientError
from boto3.s3.transfer import S3Transfer
import re
import os
# check for existance of bucket
def list_bucket(bucket_name, region):
s3 = boto3.resource('s3', region)
bucket = s3.Bucket(bucket_name)
object_... | 2.625 | 3 |
bot/exts/info/codeblock/_instructions.py | zwycl/bot | 1 | 26151 | <gh_stars>1-10
"""This module generates and formats instructional messages about fixing Markdown code blocks."""
import logging
from typing import Optional
from bot.exts.info.codeblock import _parsing
log = logging.getLogger(__name__)
_EXAMPLE_PY = "{lang}\nprint('Hello, world!')" # Make sure to escape any Markdow... | 3.046875 | 3 |
app/urls.py | julesc00/madmin | 0 | 26152 | from django.urls import path
from . import views
app_name = "app"
urlpatterns = [
path('', views.index, name="index"),
path('posts/', views.posts, name="posts"),
path('categories/', views.categories, name="categories"),
path('comments/', views.comments, name="comments"),
path('users/', views.user... | 1.875 | 2 |
lib/python/cellranger/analysis/pca.py | qiangli/cellranger | 1 | 26153 | #!/usr/bin/env python
#
# Copyright (c) 2017 10X Genomics, Inc. All rights reserved.
#
import cellranger.analysis.io as analysis_io
import cellranger.analysis.constants as analysis_constants
import cellranger.h5_constants as h5_constants
import cellranger.io as cr_io
import cellranger.analysis.stats as analysis_stats
... | 2.109375 | 2 |
src/atc/etl/__init__.py | atc-net/atc-dataplatform | 6 | 26154 | from .loader import Loader
from .extractor import Extractor
from .transformer import Transformer
from .orchestrator import Orchestrator
__all__ = [
"Loader",
"Extractor",
"Transformer",
"Orchestrator",
]
| 1.132813 | 1 |
a.py | Planecrayon/DAT120_Oblig_9 | 0 | 26155 | <filename>a.py<gh_stars>0
# Som del av et spørrespill skal du lage en klasse for flervalgspørsmål.
# Et flervalgspørsmål skal ha en spørsmålstekst, ei liste med svaralternativer
# (hvert svaralternativ er en tekststreng), og et tall som sier hvilket av
# svaralternativene som er korrekt.Klassen skal ha en __str__ metod... | 3.375 | 3 |
py/abd/abdcmd_instaweb.py | valhallasw/phabricator-tools | 0 | 26156 | <reponame>valhallasw/phabricator-tools
"""Start a local webserver to report the status of an arcyd instance."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdcmd_instaweb
#
# Public Function... | 2.34375 | 2 |
instana/span.py | tirkarthi/python-sensor | 2 | 26157 | <reponame>tirkarthi/python-sensor
# (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2017
"""
This module contains the classes that represents spans.
InstanaSpan - the OpenTracing based span used during tracing
When an InstanaSpan is finished, it is converted into either an SDKSpan
or RegisteredSpan dependi... | 2.15625 | 2 |
code/import_iworx.py | StolkArjen/human-interaction | 1 | 26158 | #!/usr/bin/env python
"""
--------------------------------------------------------
IMPORT_IWORX reads and converts various IWORX datafiles into a
FieldTrip-type data structure.
Use as
data, event = import_iworx(filename)
where the filename should point to a .mat or .txt datafile.
data has the followin... | 2.859375 | 3 |
ex/classifier.py | scw/conda-uc-2017 | 1 | 26159 | import arcpy
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
input_csv = arcpy.GetParameterAsText(0)
test_string = arcpy.GetParameterAsText(1)
df = pd.read_csv(input_csv)
target = df['is_there_an_emotion_directed_at_a_brand_or_product']
tex... | 3 | 3 |
test/test_gg_snippets.py | ooz/ggpy | 0 | 26160 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gg
from ggconfig import config
##############################################################################
# CONTENT SNIPPETS
##############################################################################
def test_logo_url():
assert gg.logo_url(config) == 'h... | 2.125 | 2 |
example/controller/tests/helper/security/web/csrf/verify/by_value.py | donghak-shin/dp-tornado | 18 | 26161 | # -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class ByValueController(Controller):
def get(self):
param_key = 'csrf'
if not self.helper.security.web.csrf.verify_token(controller=self, value=self.get_argument(param_key)):
return self.parent.finish_with_e... | 2.0625 | 2 |
dis_snek/api/http/route.py | BoredManCodes/Dis-Snek | 0 | 26162 | from typing import TYPE_CHECKING, Any, ClassVar, Optional
from urllib.parse import quote as _uriquote
if TYPE_CHECKING:
from dis_snek.models.discord.snowflake import Snowflake_Type
__all__ = ["Route"]
class Route:
BASE: ClassVar[str] = "https://discord.com/api/v9"
path: str
params: dict[str, str | ... | 2.4375 | 2 |
second/data/udi_dataset.py | muzi2045/second_TANET.pytorch | 6 | 26163 | # udi dataset process module
# modiflied from nuscenes_dataset.py
import json
import pickle
import time
import random
from copy import deepcopy
from functools import partial
from pathlib import Path
import subprocess
import fire
import numpy as np
import os
from second.core import box_np_ops
from second.core import... | 2.015625 | 2 |
storm_analysis/diagnostics/multicolor/configure.py | oxfordni/storm-analysis | 0 | 26164 | #!/usr/bin/env python
"""
Configure folder for Multicolor testing.
Hazen 01/18
"""
import argparse
import inspect
import numpy
import os
import pickle
import subprocess
import storm_analysis
import storm_analysis.sa_library.parameters as parameters
import storm_analysis.sa_library.sa_h5py as saH5Py
import storm_anal... | 2.03125 | 2 |
tests/views/test_application_views.py | snowdensb/domain-manager-api | 0 | 26165 | <filename>tests/views/test_application_views.py
"""Application View Tests."""
# Standard Python Libraries
import json
# cisagov Libraries
from tests.data.application_data import get_applications
def test_applications_get(client, mocker):
"""Test getting list of applications."""
mocker.patch("api.manager.Appl... | 2.1875 | 2 |
infratabapp/tasks.py | sheeshmohsin/infratabtask | 0 | 26166 | <filename>infratabapp/tasks.py
from __future__ import absolute_import
from infratabtask.celery import app
from celery import Task
from infratabapp.utils import send_email_notf, send_phone_notf
class SendNotf(Task):
def __init__(self, *args, **kwargs):
self.pk = kwargs.get('pk', None)
def run(self):... | 2.125 | 2 |
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/survey/admin.py | osoco/better-ways-of-thinking-about-software | 3 | 26167 | <filename>Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/survey/admin.py
"""
Provide accessors to these models via the Django Admin pages
"""
from django import forms
from django.contrib import admin
from lms.djangoapps.survey.models import SurveyForm
class SurveyFormAdmi... | 2.78125 | 3 |
resources/lib/guisettings.py | gade01/xbmcbackup | 86 | 26168 | <reponame>gade01/xbmcbackup
import json
import xbmc
from . import utils as utils
class GuiSettingsManager:
filename = 'kodi_settings.json'
systemSettings = None
def __init__(self):
# get all of the current Kodi settings
json_response = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id... | 2.46875 | 2 |
distopia/mapping/__init__.py | kevinguo344/distopia | 0 | 26169 | """
District Mapping
================
Defines the algorithms that perform the mapping from precincts to districts.
"""
| 1.625 | 2 |
pymilldb/context/Column.py | Toka-Taka/mill-db | 2 | 26170 | from .DataType import BaseType
class Column(object):
COLUMN_COMMON = 0
COLUMN_BLOOM = 1
COLUMN_INDEXED = 2
COLUMN_PRIMARY = 3
DEFAULT_FAIL_SHARE = 0.2
__NAME_TO_MOD = dict(
bloom=1,
indexed=2,
pk=3,
)
def __init__(self, name: str, kind: BaseType, mod: int, ta... | 2.96875 | 3 |
calico/etcddriver/test/test_hwm.py | ozdanborne/felix | 6 | 26171 | <filename>calico/etcddriver/test/test_hwm.py
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 Tigera, Inc. 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:/... | 2.171875 | 2 |
skdecide/hub/domain/gym/__init__.py | jeromerobert/scikit-decide | 0 | 26172 | # Copyright (c) AIRBUS 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.
from .gym import GymDomain, DeterministicInitializedGymDomain, GymWidthDomain, \
GymDiscreteActionDomain, DeterministicGymDomain, CostDeterministicG... | 1.117188 | 1 |
openwisp_network_topology/tests/test_admin.py | mafalaz/openwisp-network-topology | 1 | 26173 | from django.test import TestCase
from django.urls import reverse
from django_netjsongraph.tests import CreateGraphObjectsMixin
from django_netjsongraph.tests.base.test_admin import TestAdminMixin
from openwisp_users.tests.utils import TestOrganizationMixin
from openwisp_utils.tests.utils import TestMultitenantAdminMix... | 2.109375 | 2 |
FaceLandmarking.LearningProcess/readers/regressor_example_reader.py | TomaszRewak/FaceLandmarking | 78 | 26174 | import csv
def read_regressor_examples(num_of_features, num_of_decisions, file_path):
xs = []
ys = []
with open(file_path, mode='r', encoding='utf-8') as file:
reader = csv.reader(file, delimiter=' ')
for row in reader:
x = [float(value) for value in row[0 : num_of_features]]... | 3.046875 | 3 |
tests/test_models.py | jmichalicek/django-mail-viewer | 3 | 26175 | <reponame>jmichalicek/django-mail-viewer
from pathlib import Path
import shutil
from django.conf import settings
from django.core import cache, mail
from django.test import TestCase
from django_mail_viewer.backends.database.models import EmailMessage
class DatabaseBackendEmailMessageTest(TestCase):
connection_b... | 2.171875 | 2 |
utils.py | mfouilleul/Haddock | 0 | 26176 | '''
utils.py
General utility functions: unit conversions, great-circle
distances, CSV queries, platform-independent web browsing.
'''
import csv
import math
import webbrowser
# UNIT CONVERSIONS
MPS_TO_KTS = 1.944
class units:
def mps_to_kts(mps):
return mps*MPS_TO_KTS
def enforceTwoDigi... | 3.234375 | 3 |
frontend/front.py | streampizza/chirrup | 0 | 26177 | from flask import Flask
from flask import request, render_template, redirect
from datetime import datetime
from pymongo import MongoClient
import html
import random
import json
import ast
from flask.ext.pymongo import PyMongo
from flask import make_response, request, current_app
from functools import update_wrapper
app... | 2.5 | 2 |
resticweb/engine_configure.py | XXL6/resticweb | 1 | 26178 | <gh_stars>1-10
from resticweb.dictionary.resticweb_variables import Config
import resticweb.engine as local_engine
from resticweb.dictionary.resticweb_exceptions import NoEngineAvailable
import subprocess
import os.path as path
def configure_engine():
return_value = False
command = [Config.ENGINE_COMMAND, 'ver... | 2.21875 | 2 |
saas/aiops/api/anomalydetection/main/anomaly_detection.py | iuskye/SREWorks | 407 | 26179 | <filename>saas/aiops/api/anomalydetection/main/anomaly_detection.py
import pandas as pd
import json
import time
from bentoml import env, artifacts, api, BentoService
from bentoml.adapters import DataframeInput, JsonInput, StringInput
from bentoml.frameworks.sklearn import SklearnModelArtifact
@env(infer_pip_packages... | 2.703125 | 3 |
test cases/windows/10 vs module defs generated custom target/subdir/make_def.py | kira78/meson | 4,047 | 26180 | <reponame>kira78/meson
#!/usr/bin/env python3
import sys
with open(sys.argv[1], 'w') as f:
print('EXPORTS', file=f)
print(' somedllfunc', file=f)
| 1.851563 | 2 |
class-notes/fukushu/F-0728_graph.py | rhoenkelevra/python_simple_applications | 0 | 26181 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 28 13:31:06 2021
@author: user24
"""
'''
Suchi wo nyuryoku
only accepts integer
end shuryou
creates a graph as image
'''
import matplotlib.pyplot as plt
cnt = 0
Y = []
while True:
ans = input("数値を入力してください \n-->")
if ans == "end":
break
try:
... | 3.171875 | 3 |
flan/exports/awssqs.py | bretlowery/flan | 3 | 26182 | from flanexport import FlanExport, timeout_after
import os
import ast
try:
from boto.sqs import connection
from boto.sqs.message import Message
except:
pass
class AWSSQS(FlanExport):
def __init__(self, meta, config):
name = self.__class__.__name__
super().__init__(name, meta, config)... | 2.234375 | 2 |
setup.py | jongwon-jay-lee/ko_lm_dataformat | 22 | 26183 | <reponame>jongwon-jay-lee/ko_lm_dataformat
import os
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 6):
sys.exit("Sorry, Python >= 3.6 is required for ko_lm_dataformat")
with open("requirements.txt") as f:
require_packages = [line.strip() for line in f]
with open(os.path.joi... | 1.929688 | 2 |
tools/prepare_iata_airline_dump_file.py | mtrampont/opentraveldata | 208 | 26184 | <reponame>mtrampont/opentraveldata
#!/usr/bin/env python
import getopt, sys, io
import pandas as pd
#
# Usage
#
def usage (script_name):
"""
Display the usage.
"""
print ("")
print ("Usage: {} [options]".format(script_name))
print ("")
print ("That script transforms and filter a fix width... | 2.9375 | 3 |
sanalberto/views/polls.py | xJavii8/dafi-system | 7 | 26185 | <gh_stars>1-10
from collections import Counter
from typing import (
Any,
cast,
)
from django.contrib import messages
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin,
)
from django.db import transaction
from django.db.models import (
Count,
Q,
)
from django.forms... | 1.984375 | 2 |
face_morpher/facemorpher/warper.py | ivan-uskov/faces | 1 | 26186 | import numpy as np
import scipy.spatial as spatial
def bilinear_interpolate(img, coords):
""" Interpolates over every image channel
http://en.wikipedia.org/wiki/Bilinear_interpolation
:param img: max 3 channel image
:param coords: 2 x _m_ array. 1st row = xcoords, 2nd row = ycoords
:returns: array of interp... | 3.015625 | 3 |
paddlehub/serving/gunicorn.py | 18621579069/PaddleHub-yu | 4 | 26187 | <reponame>18621579069/PaddleHub-yu<filename>paddlehub/serving/gunicorn.py
#!/usr/bin/env python
# coding=utf-8
# coding: utf8
"""
configuration for gunicorn
"""
import multiprocessing
bind = '0.0.0.0:8888'
backlog = 2048
workers = multiprocessing.cpu_count() * 2 + 1
threads = 1
worker_class = 'sync'
worker_connections ... | 1.507813 | 2 |
Exercices/Secao04/exercicio46.py | Guilt-tech/PythonExercices | 0 | 26188 | <filename>Exercices/Secao04/exercicio46.py
print('Digite um número inteiro positivo de três dígitos (100 a 999), para gerar o número invertido')
num = int(input('Número: '))
num = str(num)
reverso = num[::-1]
print(f'O número ao contrário de: {num} é: {reverso}') | 4.15625 | 4 |
webapp/assessdb/scripts/import_csv_instruments.py | sspickle/assessdb | 0 | 26189 | <filename>webapp/assessdb/scripts/import_csv_instruments.py
import os
import sys
import transaction
import csv
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models.meta import Base
from ..models import (
get_engine,
get_session... | 2.0625 | 2 |
stock/experiment_compare_iterations_autions.py | dvirg/auctions | 1 | 26190 | <gh_stars>1-10
#!python3
"""
A utility for performing simulation experiments on auction mechanisms.
The experiment is similar to the one described by McAfee (1992), Table I (page 448).
In each experiment, we measure the actual vs. the optimal gain-from-trade.
This experiment using the real prices from Stock market. t... | 3.046875 | 3 |
categorias/iniciante/python/1095.py | carlos3g/URI-solutions | 1 | 26191 | # -*- coding: utf-8 -*-
i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3
| 3.609375 | 4 |
py_version/primary.py | the-phinisher/tic-tac-toe | 0 | 26192 | <gh_stars>0
from copy import deepcopy
from math import inf
import platform
from os import system
if platform.system() == 'Windows':
def clear():
system('cls')
else:
def clear():
system('clear')
board = [[0,0,0],
[0,0,0],
[0,0,0]]
player1 = 1
player2 = -1
null_move = [None... | 3.53125 | 4 |
set.py | git4satya/koleksyon | 0 | 26193 | from setuptools import setup, find_packages
from distutils.core import setup
from Cython.Build import cythonize
setup(name="mcmc", ext_modules=cythonize("./src/koleksyon/mcmc.pyx"))
| 1.101563 | 1 |
tests/test_functions/http_log_exception/main.py | KaylaNguyen/functions-framework-python | 479 | 26194 | <filename>tests/test_functions/http_log_exception/main.py
# Copyright 2020 Google LLC
#
# 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
#
# U... | 2.671875 | 3 |
tivol/tests/assets/migration_handlers.py | RoySegall/tivol | 2 | 26195 | <filename>tivol/tests/assets/migration_handlers.py
from tivol.base_classes.mappers import CsvMapper
from tivol.base_classes.migration_handler_base import MigrationHandlerBase
import os
class AnimalMigration(MigrationHandlerBase):
def init_metadata(self):
csv_mapper = CsvMapper()
path = os.path.jo... | 2.203125 | 2 |
2017/day25/day25.py | icemanblues/advent-of-code | 0 | 26196 | <reponame>icemanblues/advent-of-code<filename>2017/day25/day25.py
from typing import Set
day_num = "25"
day_title = "The Halting Problem"
def part1():
tape: Set[int] = set()
curr: int = 0
state: str = 'a'
for _ in range(12523873):
is_one = curr in tape
if state == 'a' and not is_one:... | 3.6875 | 4 |
Code.py | sad786/Python | 0 | 26197 | <reponame>sad786/Python<gh_stars>0
def process(N):
temp = str(N)
temp = temp.replace('4','2')
res1 = int(temp)
res2 = N-res1
return res1,res2
T = int(input())
for t in range(T):
N = int(input())
res1,res2 = process(N)
print('Case #{}: {} {}'.format(t+1,res1,res2)) | 2.78125 | 3 |
repos/insightface/deploy/test.py | batermj/DeepVideoAnalytics | 1 | 26198 | import face_embedding
import argparse
import cv2
import numpy as np
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.add_argument('--model', default='../models/model-r34-amf/model,0', help='path to load model.')
parser.add_... | 2.484375 | 2 |
apollon/io.py | bader28/apollon | 0 | 26199 | <filename>apollon/io.py<gh_stars>0
# Licensed under the terms of the BSD-3-Clause license.
# Copyright (C) 2019 <NAME>
# <EMAIL>
"""apollon/io.py -- General I/O functionallity.
Classes:
ArrayEncoder Serialize numpy array to JSON.
FileAccessControl Descriptor for file name attributes.
Functio... | 2.28125 | 2 |