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 |
|---|---|---|---|---|---|---|
blueprints/finance/views.py | shuxiang/MT-WMS | 1 | 23700 | <reponame>shuxiang/MT-WMS<gh_stars>1-10
#coding=utf8
import json
from sqlalchemy import func, or_
from pprint import pprint
from datetime import datetime, timedelta
from random import randint
from flask import Blueprint, g, request, jsonify
from flask_login import LoginManager, login_user, logout_user, login_required,... | 1.773438 | 2 |
layers/modules/fast_mask_iou.py | sebastian-ruiz/yolact | 1 | 23701 | <reponame>sebastian-ruiz/yolact
import torch
from torch import nn
import torch.nn.functional as F
#locals
from data.config import Config
from utils.functions import make_net
from utils.script_module_wrapper import ScriptModuleWrapper, script_method_wrapper
class FastMaskIoUNet(ScriptModuleWrapper):
def __init__(... | 2.125 | 2 |
audio_pouring/utils/network.py | lianghongzhuo/MultimodalPouring | 5 | 23702 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : <NAME>
# E-mail : <EMAIL>
# Description:
# Date : 15/10/2019: 22:13
# File Name : network
import argparse
import numpy as np
import torch
def worker_init_fn(pid):
np.random.seed(torch.initial_seed() % (2 ** 31 - 1))
def my_collate(batch):... | 2.234375 | 2 |
FederatedSDNSecurity/main.py | Beaconproj/CrossCloudVNFSimulation | 1 | 23703 |
'''
Created on 12 janv. 2016
@author: phm
'''
import FederatedSDN
import FederatedSDNSecurity
import FederatedSecurityAgent
import VNFManager
import CloudManager
import ssl, socket
inputMessage="Press enter to continue"
federationCloudManagers=[]
cloudFederationMembers=[
["cloud_man_1","vnf_manager_1"... | 2.484375 | 2 |
WCET_stats.py | FTOD/ZExp | 0 | 23704 | import parsetools
from benchDesc import benchsDesc
import matplotlib.pyplot as plt
import matplotlib
import getopt, sys
try:
opts, args = getopt.getopt(sys.argv[1:], "h", ["arch="])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
file_postfix = ""
for o,a in opts:
if o == "--arch":
if... | 2.15625 | 2 |
schoolport/app_core/migrations/0024_auto_20210513_1020.py | yotink522/schoolport | 0 | 23705 | <reponame>yotink522/schoolport
# Generated by Django 3.1.7 on 2021-05-13 02:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_core', '0023_auto_20210513_1004'),
]
operations = [
migrations.AlterField(
model_name='tb_cou... | 1.648438 | 2 |
galaxy_kickstart/binary_datatypes_to_be_added_in_galaxy.py | pajanne/galaxy-kickstart | 2 | 23706 | <gh_stars>1-10
class CompressedFastq( CompressedArchive ):
"""
Class describing an compressed fastq file
This class can be sublass'ed to implement archive filetypes that will not be unpacked by upload.py.
"""
file_ext = "fq.gz"
def set_peek( self, dataset, is_multi_byte=False ):
... | 2.625 | 3 |
timesketch/lib/cypher/insertable_string.py | Marwolf/timesketch | 0 | 23707 | # Copyright 2017 Google 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | 3.828125 | 4 |
networks/rnn.py | uchikun2493/nn_modules | 0 | 23708 | <filename>networks/rnn.py
# pytorch
import torch
import torch.nn as nn
import torch.nn.functional as F
# **********************************************
# rnn class
# **********************************************
class BasicRNNCell(nn.Module):
def __init__(self, inputs, hidden, outputs):
super(BasicRNNCell... | 3.40625 | 3 |
config/settings/production.py | rimphyd/Django-OPAC | 1 | 23709 | import django_heroku
from config.settings.base import *
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asc... | 1.820313 | 2 |
fabrikApi/views/assembly/list.py | demokratiefabrik/fabrikApi | 0 | 23710 | """ Assemblies List View. """
import logging
from datetime import datetime
from cornice.service import Service
from fabrikApi.models.assembly import DBAssembly
from fabrikApi.models.mixins import arrow
# from fabrikApi.util.cors import CORS_LOCATION, CORS_MAX_AGE
logger = logging.getLogger(__name__)
# SERVICES
as... | 2.078125 | 2 |
layers/layers.py | yangzonglin1994/yangzl-deep-text-matching | 2 | 23711 | <reponame>yangzonglin1994/yangzl-deep-text-matching
import tensorflow as tf
from keras import backend as K
from keras.engine.topology import Layer
from keras.initializers import Ones, Zeros
from layers import transformer
class LayerNormalization(Layer):
def __init__(self, eps=1e-6, **kwargs):
super(Layer... | 2.625 | 3 |
tests/TestMetrics.py | gr33ndata/irlib | 80 | 23712 | <reponame>gr33ndata/irlib
from unittest import TestCase
from irlib.metrics import Metrics
class TestMetrics(TestCase):
def setUp(self):
self.m = Metrics()
def test_jaccard_same_len(self):
with self.assertRaises(ValueError):
self.m.jaccard_vectors(
[0, 1],
... | 2.640625 | 3 |
cottonformation/res/lookoutmetrics.py | gitter-badger/cottonformation-project | 0 | 23713 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
This module
"""
import attr
import typing
from ..core.model import (
Property, Resource, Tag, GetAtt, TypeHint, TypeCheck,
)
from ..core.constant import AttrMeta
#--- Property declaration ---
@attr.s
class AnomalyDetectorCsvFormatDescriptor(Property):
"""
AWS Obj... | 2 | 2 |
mlcomp/db/core/options.py | sUeharaE4/mlcomp | 166 | 23714 | class PaginatorOptions:
def __init__(
self,
page_number: int,
page_size: int,
sort_column: str = None,
sort_descending: bool = None
):
self.sort_column = sort_column
self.sort_descending = sort_descending
self.page_number = page_number
self... | 2.734375 | 3 |
pbxproj/pbxsections/PBXResourcesBuildPhase.py | JoliChen/mod-pbxproj | 1 | 23715 | from pbxproj.pbxsections.PBXGenericBuildPhase import *
class PBXResourcesBuildPhase(PBXGenericBuildPhase):
def _get_comment(self):
return 'Resources'
| 1.414063 | 1 |
Week-4/points_and_segments.py | AbhiSaphire/Algorithmic-Toolbox | 3 | 23716 | <gh_stars>1-10
import sys
from itertools import chain
def fast_count_segments(starts, ends, points):
cnt = [0] * len(points)
start_points = zip(starts, ['l'] * len(starts), range(len(starts)))
end_points = zip(ends, ['r'] * len(ends), range(len(ends)))
point_points = zip(points, ['p'] * len(points), ra... | 3.203125 | 3 |
main.py | anurendra/Web_IE | 0 | 23717 | import argparse
import numpy as np
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from datasets import custom_collate_fn, load_data, WebDataset
from models import WebObjExtractionNet
from train import train_model, evaluate_model
from utils... | 1.992188 | 2 |
rclpy/actions/minimal_action_client/examples_rclpy_minimal_action_client/client_cancel.py | emersonknapp/examples | 1 | 23718 | <filename>rclpy/actions/minimal_action_client/examples_rclpy_minimal_action_client/client_cancel.py<gh_stars>1-10
# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# 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... | 2.453125 | 2 |
buffers/introspective_buffer.py | GittiHab/mbrl-thesis-code | 0 | 23719 | import numpy as np
from typing import Union, Optional, List, Dict, Any
from buffers.chunk_buffer import ChunkReplayBuffer
class IntrospectiveChunkReplayBuffer(ChunkReplayBuffer):
def __init__(self, buffer_size: int, *args, **kwargs):
super().__init__(buffer_size, *args, **kwargs)
self.sam... | 2.34375 | 2 |
esp8266/boot.py | AlexGolovko/UltrasonicDeeper | 3 | 23720 | # This file is executed on every boot (including wake-boot from deepsleep)
import esp
import gc
import machine
import network
esp.osdebug(None)
# machine.freq(160000000)
def do_connect(wifi_name, wifi_pass):
ssid = 'microsonar'
password = '<PASSWORD>'
ap_if = network.WLAN(network.AP_IF)
ap_if.activ... | 2.6875 | 3 |
bin/check_ysim.py | ACTCollaboration/tilec | 1 | 23721 | <gh_stars>1-10
from __future__ import print_function
from orphics import maps,io,cosmology,stats
from pixell import enmap
import numpy as np
import os,sys
from tilec import utils as tutils
region = 'deep56'
#region = 'boss'
solution = 'comptony'
tdir = "/scratch/r/rbond/msyriac/data/depot/tilec/v1.2.0_20200324"
dcomb ... | 1.796875 | 2 |
tests/schema_mapping/expected/generated_example3.py | loyada/typed-py | 14 | 23722 | from typedpy import *
class Person(Structure):
first_name = String()
last_name = String()
age = Integer(minimum=1)
_required = ['first_name', 'last_name']
class Groups(Structure):
groups = Array(items=Person)
_required = ['groups']
# ********************
class Example1(Structure):
p... | 3.203125 | 3 |
rpesk/morse_code.py | LukeJVinton/pi-projects | 0 | 23723 |
# 02_blink_twice.py
# From the code for the Electronics Starter Kit for the Raspberry Pi by MonkMakes.com
import RPi.GPIO as GPIO
import time
def word_separation(pin):
sleep_time = 7
GPIO.output(pin, False) # True means that LED turns on
time.sleep(sleep_time)
def pulse(pin, length = "dot"):
... | 3.609375 | 4 |
lljs.py | Peter9192/wind_analytics | 0 | 23724 | """ Identify low-level jets in wind profile data.
<NAME>
December 2020
"""
import numpy as np
import xarray as xr
def detect_llj(x, axis=None, falloff=0, output='strength', inverse=False):
""" Identify maxima in wind profiles.
args:
- x : ndarray with wind profile data
- axis ... | 3.421875 | 3 |
rollon_erpnext/hooks_property_setter.py | santoshbb/rhplrepo | 0 | 23725 | property_setter = {
"dt": "Property Setter",
"filters": [
["name", "in", [
'Purchase Order-read_only_onload',
'Purchase Order-default_print_format',
'Purchase Invoice-naming_series-options',
'Purchase Invoice-naming_series-default',
'Delivery Note-naming_series-options',
'Delivery Note-naming_seri... | 1.117188 | 1 |
api/client/src/pcluster_client/sigv4_auth.py | maclema/aws-parallelcluster | 415 | 23726 | """Sigv4 Signing Support"""
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy
# of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or i... | 2.0625 | 2 |
django/contrib/sessions/tests.py | rawwell/django | 1 | 23727 | r"""
>>> from django.conf import settings
>>> from django.contrib.sessions.backends.db import SessionStore as DatabaseSession
>>> from django.contrib.sessions.backends.cache import SessionStore as CacheSession
>>> from django.contrib.sessions.backends.file import SessionStore as FileSession
>>> from django.contrib.ses... | 2.359375 | 2 |
gopage/web_helper.py | wavegu/gopage | 1 | 23728 | <gh_stars>1-10
# encoding: utf-8
import urllib2
from proxy_helper import ProxyHelper
proxyHelper = ProxyHelper()
class WebHelper:
def __init__(self):
pass
@classmethod
def get_page_content_from_url(cls, page_url):
"""
get html content from web page with given url
:param... | 3.03125 | 3 |
tests/test_skipping.py | pytask-dev/pytask | 41 | 23729 | import textwrap
from contextlib import ExitStack as does_not_raise # noqa: N813
import pytest
from _pytask.mark import Mark
from _pytask.outcomes import Skipped
from _pytask.outcomes import SkippedAncestorFailed
from _pytask.outcomes import SkippedUnchanged
from _pytask.skipping import pytask_execute_task_setup
from ... | 2.1875 | 2 |
basic/server.py | spinico/django-projects-boilerplates | 0 | 23730 | <filename>basic/server.py
from waitress import serve
from conf.wsgi import application
if __name__ == '__main__':
serve(application, listen='0.0.0.0:8000', url_scheme='https')
| 1.703125 | 2 |
src/django_version_checks/apps.py | adamchainz/django-version-checks | 33 | 23731 | from django.apps import AppConfig
from django.core.checks import Tags, register
from django_version_checks import checks
class DjangoVersionChecksAppConfig(AppConfig):
name = "django_version_checks"
verbose_name = "django-version-checks"
def ready(self) -> None:
register(Tags.compatibility)(chec... | 1.6875 | 2 |
app/ocr.py | noahnisbet/human-rights-first-asylum-ds-noahnisbet | 1 | 23732 | <reponame>noahnisbet/human-rights-first-asylum-ds-noahnisbet<gh_stars>1-10
import os
os.environ["OMP_NUM_THREADS"]= '1'
os.environ["OMP_THREAD_LIMIT"] = '1'
os.environ["MKL_NUM_THREADS"] = '1'
os.environ["NUMEXPR_NUM_THREADS"] = '1'
os.environ["OMP_NUM_THREADS"] = '1'
os.environ["PAPERLESS_AVX2_AVAILABLE"]="false"
os.... | 2.59375 | 3 |
lp_local_search.py | cddoyle/div-k-median | 0 | 23733 | import time
import sys
import numpy as np
from local_search import kmedian_local_search
import feasibility
from kmedkpm import k_median_k_partitions_LS
import psutil
from sklearn.datasets import make_blobs
import generator
import random
test = False
def lp_ls_complete(data, color_mat, rvec, k, logfile):
#########... | 2.234375 | 2 |
dms/v2/meal/__init__.py | moreal/DMS-api | 0 | 23734 | <gh_stars>0
import datetime
import requests
import json
from dms.v2.config import DMS_URL
class Meal():
@staticmethod
def get(date: datetime.date or str=datetime.date.today()):
if not isinstance(date, str):
date = str(date)
resp = requests.get(f"http://{DMS_URL}/v2/meal/{date}")
... | 2.6875 | 3 |
mayan/apps/dependencies/permissions.py | CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons | 2 | 23735 | from django.utils.translation import ugettext_lazy as _
from mayan.apps.permissions import PermissionNamespace
namespace = PermissionNamespace(label=_('Dependencies'), name='dependencies')
permission_dependencies_view = namespace.add_permission(
label=_('View dependencies'), name='dependencies_view'
)
| 1.429688 | 1 |
src/about.py | jukeboxroundtable/JukeboxRoundtable | 1 | 23736 | <filename>src/about.py
from flask import Blueprint, render_template
about_blueprint = Blueprint('about', __name__)
@about_blueprint.route('/about')
def about():
"""Show the about page."""
return render_template('about.html')
| 2.734375 | 3 |
src/lib/template.py | emil-jacero/powerdns-auth-docker | 0 | 23737 | import os
import jinja2
import logging
from lib.config import Config
class Template:
def __init__(self, env_search_term="ENV"):
self.log_name = f'{Config.logger_name}.{self.__class__.__name__}'
self.log = logging.getLogger(self.log_name)
self.path = None
self.name = None
s... | 2.765625 | 3 |
backend/fief/schemas/workspace.py | fief-dev/fief | 1 | 23738 | from typing import Optional
from pydantic import BaseModel, root_validator, validator
from fief.crypto.encryption import decrypt
from fief.db.types import DatabaseType
from fief.errors import APIErrorCode
from fief.schemas.generics import UUIDSchema
from fief.settings import settings
def validate_all_database_setti... | 2.359375 | 2 |
art/migrations/0007_alter_artimage_project.py | rrozander/Art-Website | 0 | 23739 | # Generated by Django 3.2.12 on 2022-03-01 23:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('art', '0006_auto_20220301_1452'),
]
operations = [
migrations.AlterField(
model_name='artimage... | 1.414063 | 1 |
blog/tasks.py | iloveyougit/ylink2 | 0 | 23740 | <reponame>iloveyougit/ylink2
from __future__ import absolute_import, unicode_literals
import string
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from celery import shared_task, current_task
@shared_task
def create_random_user_accounts(total_user):
for i in r... | 2.3125 | 2 |
fehler_auth/migrations/0003_auto_20220416_1626.py | dhavall13/fehler_core | 0 | 23741 | # Generated by Django 2.2.27 on 2022-04-16 16:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fehler_auth', '0002_auto_20211002_1511'),
]
operations = [
migrations.AlterField(
model_name='invite',
name='email'... | 1.515625 | 2 |
models/gene.py | rogamba/neuropy | 0 | 23742 | <reponame>rogamba/neuropy
from random import choice, gauss, random
class Gene(object):
def __init__(self, config, key):
self.config = config
self.key = key
def __str__(self):
attrib = ['key'] + [a for a in self.__gene_attributes__]
attrib = ['{0}={1}'.format(a, getattr(self, a... | 2.859375 | 3 |
tapis_cli/commands/taccapis/v2/apps/mixins.py | bpachev/tapis-cli | 8 | 23743 | <gh_stars>1-10
from tapis_cli.clients.services.mixins import ServiceIdentifier
__all__ = ['AppIdentifier']
class AppIdentifier(ServiceIdentifier):
service_id_type = 'App'
dest = 'app_id'
def validate_identifier(self, identifier, permissive=False):
try:
self.tapis_client.apps.get(appI... | 2.484375 | 2 |
agents/antifa.py | fan-weiwei/mercury-unicorn | 0 | 23744 | from agents.agent import Agent
from random import randint
class Antifa(Agent):
def __init__(self):
super().__init__()
self.is_spy = False
def __str__(self):
return 'Basic Antifa'
def assign_mission(self, board):
number_to_assign = board.number_to_assign()
board.... | 3.21875 | 3 |
faketranslate/metadata.py | HeywoodKing/faketranslate | 0 | 23745 | <filename>faketranslate/metadata.py
# -*- encoding: utf-8 -*-
"""
@File : metadata.py
@Time : 2020/1/1
@Author : flack
@Email : <EMAIL>
@ide : PyCharm
@project : faketranslate
@description : 描述
""" | 0.957031 | 1 |
Scaffold_Code/test scripts/test10_vm.py | tzortzispanagiotis/nbc-blockchain-python | 0 | 23746 | <gh_stars>0
import requests, json, time
from multiprocessing.dummy import Pool
pool = Pool(100)
transactions0 = []
transactions1 = []
transactions2 = []
transactions3 = []
transactions4 = []
transactions5 = []
transactions6 = []
transactions7 = []
transactions8 = []
transactions9 = []
nodeid = {
'id0': 0,
'... | 2.21875 | 2 |
api/standup/utils/email.py | adoval4/standup | 0 | 23747 | <gh_stars>0
# django
from django.core.mail import EmailMessage
from django.conf import settings
from django.template.loader import render_to_string
# utiltities
import threading
class EmailThread(threading.Thread):
"""
Class uses a thread to send email
"""
def __init__(self, subject, content, recipient_list, is_... | 2.734375 | 3 |
app/main/controller/sample_controller.py | Eliotdoesprogramming/python.flask.sqlalchemy.Rest_Api_Template | 0 | 23748 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from service.api_service import Service
class SampleController(object):
def __init__(self,app:Flask,db:SQLAlchemy,service:Service) -> None:
self.app=app
self.db=db
self.service=service
self.add_routes(app)
def add_ro... | 2.6875 | 3 |
supervised/preprocessing/datetime_transformer.py | sourcery-ai-bot/mljar-supervised | 0 | 23749 | import numpy as np
import pandas as pd
import datetime
import json
class DateTimeTransformer(object):
def __init__(self):
self._new_columns = []
self._old_column = None
self._min_datetime = None
self._transforms = []
def fit(self, X, column):
self._old_column = column
... | 3.125 | 3 |
tac/gui/dashboards/controller.py | fetchai/agents-tac | 29 | 23750 | <reponame>fetchai/agents-tac<gh_stars>10-100
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with ... | 1.960938 | 2 |
timecat/apps/users/views.py | LinXueyuanStdio/memp | 0 | 23751 | import json
from django.urls import reverse
from django.shortcuts import render
from django.db.models import Q
from django.views.generic.base import View
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
... | 1.90625 | 2 |
SWSIdentity/Controllers/__init__.py | vanzhiganov/identity | 1 | 23752 | <reponame>vanzhiganov/identity
__all__ = [
'Users'
] | 1.085938 | 1 |
gui/Ui_sales_transaction.py | kim-song/kimsong-apriori | 2 | 23753 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'd:\MITE12\ksapriori\gui\sales_transaction.ui'
#
# Created by: PyQt5 UI code generator 5.12.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_FormSalesTransaction(ob... | 1.703125 | 2 |
setup.py | dboddie/Beeware-Hello-VOC | 35 | 23754 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='{{ cookiecutter.app_name }}',
version='0.0.1',
description='{{ cookiecutter.description }}',
author='{{ cookiecutter.author }}',
author_email='{{ cookiecutter.author_email }}',
license='{{ cookiecutter.license }}',
... | 1.289063 | 1 |
src/app.py | chunyuyuan/NEWS_2019_network-master | 0 | 23755 | from flask import Flask, request, render_template, send_file, Response
import io
import base64
import csv
import json
import time
from collections import OrderedDict
import numpy
import pandas as pd
from numpy import genfromtxt
from flask import jsonify
from flask_cors import CORS
from LoadingNetwork import... | 2.578125 | 3 |
src/oca/models/__init__.py | goubertbrent/oca-backend | 0 | 23756 | # coding: utf-8
# flake8: noqa
"""
Our City App
Our City App internal apis # noqa: E501
The version of the OpenAPI document: 0.0.1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
# import models into model package
from oca.models.home_screen import HomeScre... | 1.046875 | 1 |
calibrate.py | jamesbowman/k40-python | 2 | 23757 | import svgwrite
def cross(dwg, x, y, r = 5):
dwg.add(dwg.line((x - r, y), (x + r, y), stroke='red', stroke_width=.1))
dwg.add(dwg.line((x, y - r), (x, y + r), stroke='red', stroke_width=.1))
if __name__ == '__main__':
dwg = svgwrite.Drawing('test.svg', size=('150mm', '150mm'), viewBox=('0 0 150 150'))
... | 2.90625 | 3 |
Pokemon Identifier/app.py | sethuiyer/mlhub | 22 | 23758 | from poketype import PokemonTypeIdentifier
from flask import Flask, request, make_response,jsonify
import os
id = PokemonTypeIdentifier()
app = Flask(__name__,static_url_path='/static')
@app.route('/findtype',methods=['GET'])
def classify():
poke_name=request.args.get('pokename')
results = id.predict_type(poke... | 2.375 | 2 |
SViTE/backup/sparselearning/snip.py | VITA-Group/SViTE | 50 | 23759 | <reponame>VITA-Group/SViTE
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import math
import copy
import types
def fgsm_attack(image, epsilon, data_grad):
print('Attacking...')
# Collect the element-wise sign of the data gradient
sign_data_grad = data_... | 2.375 | 2 |
digin/leads/views.py | yhung119/cs411-digin | 0 | 23760 | from django.shortcuts import render
from leads.models import Lead
from leads.serializers import LeadSerializer
from rest_framework import generics
# Create your views here.
class LeadListCreate(generics.ListCreateAPIView):
queryset = Lead.objects.all()
serializer_class = LeadSerializer
| 1.664063 | 2 |
Module01/OOP/FirstClassDef.py | fenglihanxiao/Python | 0 | 23761 | """ First class definition"""
class Cat:
pass
class RaceCar:
pass
cat1 = Cat()
cat2 = Cat()
cat3 = Cat() | 2.453125 | 2 |
ddtrace/contrib/aiobotocore/__init__.py | tophatmonocle/dd-trace-py | 0 | 23762 | """
The aiobotocore integration will trace all AWS calls made with the ``aiobotocore``
library. This integration isn't enabled when applying the default patching.
To enable it, you must run ``patch_all(botocore=True)``
::
import aiobotocore.session
from ddtrace import patch
# If not patched yet, you can ... | 1.757813 | 2 |
luna/__init__.py | ktemkin/luna | 4 | 23763 | #
# This file is part of LUNA.
#
import shutil
import tempfile
import argparse
from nmigen import Elaboratable
from .gateware.platform import get_appropriate_platform
def top_level_cli(fragment, *pos_args, **kwargs):
""" Runs a default CLI that assists in building and running gateware.
If the user's opt... | 2.5625 | 3 |
htdocs/geojson/hsearch.py | akrherz/depbackend | 0 | 23764 | <reponame>akrherz/depbackend
"""search for HUC12 by name."""
import json
from paste.request import parse_formvars
from pyiem.util import get_dbconn
def search(q):
"""Search for q"""
pgconn = get_dbconn("idep")
cursor = pgconn.cursor()
d = dict(results=[])
cursor.execute(
"""SELECT huc_12,... | 2.75 | 3 |
setup.py | Peque/mmsim | 0 | 23765 | """
Setup module.
"""
from setuptools import setup
from mmsim import __version__
setup(
name='mmsim',
version=__version__,
description='A simple Micromouse Maze Simulator server',
long_description="""The server can load different mazes and any client
can connect to it to ask for the current po... | 1.554688 | 2 |
fastinference.py | wkcw/VariousDiscriminator-CycleGan | 0 | 23766 | <filename>fastinference.py
"""
A fast version of the original inference.
Constructing one graph to infer all the samples.
Originaly one graph for each sample.
"""
import tensorflow as tf
import os
from model import CycleGAN
import utils
import scipy.misc
import numpy as np
try:
from os import scandir
except ImportE... | 2.03125 | 2 |
donatello/utils.py | adrianchifor/donatello | 7 | 23767 | <reponame>adrianchifor/donatello
import http.client
def getFunctionPublicIP():
conn = http.client.HTTPSConnection('api.ipify.org', 443)
conn.request('GET', '/?format=json')
ip = conn.getresponse().read()
print(ip)
conn.close()
return str(ip)
def non_zero_balance(balance):
"""
Return ... | 2.9375 | 3 |
omop_cdm/utility_programs/load_concept_files_into_db.py | jhajagos/CommonDataModelMapper | 1 | 23768 | import argparse
import json
import sys
import os
try:
from utility_functions import load_csv_files_into_db, generate_vocabulary_load
except(ImportError):
sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], os.path.pardir, os.path.pardir, "src")))
from utility_functions import load_... | 2.65625 | 3 |
triplinker/tests/test_views/test_non_dynamic_urls/test_accounts_views/tests.py | GonnaFlyMethod/triplinker | 0 | 23769 | <reponame>GonnaFlyMethod/triplinker
# Python modules.
import pytest
# Django modules.
from django.urls import reverse
from django.test import TestCase
# !Triplinker modules:
from tests.helpers.create_user import new_user
@pytest.mark.django_db
def test_signup_view(client):
url = reverse('accounts:s... | 2.203125 | 2 |
DNN_Experiments/MaskRCNN/convert.py | wmjpillow/FlameDetectionAPP | 2 | 23770 | #!/usr/bin/env python
# convert jpg tp png
from glob import glob
import cv2
pngs = glob('./*.jpg')
for j in pngs:
img = cv2.imread(j)
cv2.imwrite(j[:-3] + 'png', img)
# delete jpg files
import glob
import os
dir = "/Users/wangmeijie/ALLImportantProjects/FlameDetectionAPP/Models/MaskRCNN/02_26_2020/Mask_RCNN... | 3.046875 | 3 |
src/title2Id_redirect_parser.py | mjstrobl/WEXEA | 10 | 23771 | import xml.sax
import re
import os
import json
import time
current_milli_time = lambda: int(round(time.time() * 1000))
RE_LINKS = re.compile(r'\[{2}(.*?)\]{2}', re.DOTALL | re.UNICODE)
IGNORED_NAMESPACES = [
'wikipedia', 'category', 'file', 'portal', 'template',
'mediaWiki', 'user', 'help', 'book', 'draft', ... | 2.59375 | 3 |
rules/starlark_configurations/cc_test/defs.bzl | CyberFlameGO/examples | 572 | 23772 | # We can transition on native options using this
# //command_line_option:<option-name> syntax
_BUILD_SETTING = "//command_line_option:test_arg"
def _test_arg_transition_impl(settings, attr):
_ignore = (settings, attr)
return {_BUILD_SETTING: ["new arg"]}
_test_arg_transition = transition(
implementation ... | 1.921875 | 2 |
test_cases/apache_avro_adapter.py | QratorLabs/ritfest2016 | 0 | 23773 | import io
import avro.io
try:
from avro.schema import parse
except ImportError:
from avro.schema import Parse as parse
class ApacheAvroAdapter(object):
NAME = 'avro'
def __init__(self):
with open('specs/str.avsc', 'r') as f:
schema = parse(f.read())
self.str_reader = a... | 2.4375 | 2 |
tests/test_vec/__init__.py | karin0018/EduNLP | 18 | 23774 | <filename>tests/test_vec/__init__.py
# coding: utf-8
# 2021/5/30 @ tongshiwei
| 0.984375 | 1 |
tests/test_nameko_prometheus.py | alfaro28/nameko-prometheus | 0 | 23775 | <filename>tests/test_nameko_prometheus.py<gh_stars>0
import pytest
from nameko.events import EventDispatcher, event_handler
from nameko.rpc import rpc
from nameko.testing.services import entrypoint_hook, entrypoint_waiter
from nameko.web.handlers import http
from prometheus_client import REGISTRY, Counter
from nameko_... | 2.03125 | 2 |
testing/forms/products.py | Miki761000/storage_podari_s_luibov | 0 | 23776 | from django import forms
from warehouse.models import Product, ProductAdditionalInformation
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
field_order = [
'product_name',
'product_code',
'product_quantity',
... | 2.03125 | 2 |
src/amuse/community/sei/test_sei.py | joshuawall/amuse | 1 | 23777 | <filename>src/amuse/community/sei/test_sei.py<gh_stars>1-10
from amuse.test.amusetest import TestWithMPI
from amuse.units import nbody_system
from amuse.units import units
import os
import sys
import numpy
import math
from amuse.community.sei.interface import SeiInterface
from amuse.community.sei.interface import Sei
... | 2.234375 | 2 |
datetimeparser/enums.py | aridevelopment-de/datetimeparser | 12 | 23778 | from datetime import datetime, timedelta
from enum import Enum, auto
from dateutil.relativedelta import relativedelta
from .baseclasses import Constant, MethodEnum
from .formulars import days_feb, eastern_calc, thanksgiving_calc, year_start
class ConstantOption(Enum):
TIME_VARIABLE = auto()
DATE_VARIABLE = ... | 2.421875 | 2 |
ontospy/extras/hacks/server.py | michaelyryi/Ontospy | 0 | 23779 | <reponame>michaelyryi/Ontospy
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
UTILITY TO START A LOCAL SERVER
Copyright (c) 2015 __<NAME>__ <http://www.michelepasin.org>. All rights reserved.
Shows local repo within a server
"""
MODULE_VERSION = 0.1
USAGE = "@todo"
import time, optparse, os, rdflib, sys, web... | 2.328125 | 2 |
python/dolfinx_contact/unbiased/nitsche_unbiased.py | jorgensd/asimov-contact | 0 | 23780 | # Copyright (C) 2021 <NAME>
#
# SPDX-License-Identifier: MIT
from typing import Callable, Tuple, Union
import dolfinx.common as _common
import dolfinx.fem as _fem
import dolfinx.log as _log
import dolfinx.mesh as _mesh
import dolfinx_cuas
import numpy as np
import ufl
from dolfinx.cpp.graph import AdjacencyList_in... | 1.71875 | 2 |
scratch/movielens-mongodb.py | crcsmnky/movielens-data-exports | 1 | 23781 | <filename>scratch/movielens-mongodb.py<gh_stars>1-10
"""
usage: python movielens-mongodb.py [movies] [ratings] [links]
"""
import sys
import re
import csv
import os
# import tmdbsimple as tmdb
from pymongo import MongoClient
from pymongo import ASCENDING, DESCENDING
from datetime import datetime
from time import sl... | 2.828125 | 3 |
coretabs ATM py/withdraw.py | attia7/Test | 0 | 23782 | <gh_stars>0
balance = 700
papers=[100, 50, 10, 5,4,3,2,1]
def withdraw(balance, request):
if balance < request :
print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance))
else:
print ('your balance >>', balance)
orgnal_request = request
whil... | 3.375 | 3 |
dynamicform/widgets.py | cdgagne/django-dynamicform | 0 | 23783 | <reponame>cdgagne/django-dynamicform
from django import forms
from django.forms.utils import flatatt
from django.utils import formats
from django.utils.encoding import force_text
from django.utils.html import format_html
class AjaxValidatingTextInput(forms.TextInput):
def __init__(self, *args, **kwargs):
... | 2.171875 | 2 |
ocdskingfisherprocess/maindatabase/migrations/versions/8e3f80979dc9_change_unique_constraint_on_collection.py | matiasSanabria/kingfisher-process | 1 | 23784 | """Change unique constraint on collection
Revision ID: 8e3f80979dc9
Revises: 3d5fae27a215
Create Date: 2019-12-18 13:14:56.466907
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '3d5fae27a215'
branch_labels = None
depends_on = None
def ... | 1.609375 | 2 |
tests/stdlib_test.py | misantroop/jsonpickle | 0 | 23785 | <reponame>misantroop/jsonpickle
# -*- coding: utf-8 -*-
"""Test miscellaneous objects from the standard library"""
import uuid
import unittest
import jsonpickle
class UUIDTestCase(unittest.TestCase):
def test_random_uuid(self):
u = uuid.uuid4()
encoded = jsonpickle.encode(u)
decoded = j... | 2.65625 | 3 |
app/core.py | JoonyoungYi/lol-recommend | 0 | 23786 | <gh_stars>0
import os
import time
import tensorflow as tf
import numpy as np
import pandas as pd
from .configs import *
from .models import init_models
EPOCH_NUMBER = 10000
EARLY_STOP = True
EARLY_STOP_MAX_ITER = 40
def _train(session, saver, models, train_data, valid_data):
model_file_path = _init_model_file_... | 2.234375 | 2 |
aito/client/requests/query_api_request.py | AitoDotAI/aito-python-tools | 6 | 23787 | <gh_stars>1-10
"""Aito `Query API <https://aito.ai/docs/api/#query-api>`__ Request Class"""
import re
from abc import ABC
from typing import Dict, Optional, Union, List
from .aito_request import AitoRequest, _PatternEndpoint, _PostRequest
from ..responses import SearchResponse, PredictResponse, RecommendResponse, Eva... | 2.375 | 2 |
tests/test_domain.py | shyams2/pychebfun | 72 | 23788 | <reponame>shyams2/pychebfun
#!/usr/bin/env python
# coding: UTF-8
from __future__ import division
from pychebfun import Chebfun
import operator
import unittest
import pytest
from . import tools
import numpy as np
import numpy.testing as npt
#----------------------------------------------------------------------------... | 2.59375 | 3 |
glance/rpc/common.py | Quinton/glance | 5 | 23789 | #!/usr/bin/env python
#encode=utf-8
#vim: tabstop=4 shiftwidth=4 softtabstop=4
#Created on 2013-8-17
#Copyright 2013 <NAME>
import copy
import logging
import traceback
class RPCException(Exception):
message = "An Unknown RPC related exception occurred"
def __init__(self, message = None, **... | 2.0625 | 2 |
tests/test_simple.py | ImportTaste/WebRequest | 8 | 23790 | <filename>tests/test_simple.py<gh_stars>1-10
import unittest
import socket
import json
import base64
import zlib
import gzip
import bs4
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import WebRequest
from . import testing_server
class TestPlainCreation(unittest.TestCase):
d... | 2.671875 | 3 |
cplcom/moa/device/mcdaq.py | matham/cplcom | 0 | 23791 | '''Barst Measurement Computing DAQ Wrapper
==========================================
'''
from functools import partial
from pybarst.mcdaq import MCDAQChannel
from kivy.properties import NumericProperty, ObjectProperty
from moa.threads import ScheduledEventLoop
from moa.device.digital import ButtonViewPort
from cplco... | 2.1875 | 2 |
train_utils.py | BatyrM/QL-Net | 0 | 23792 | <reponame>BatyrM/QL-Net
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, T... | 2.625 | 3 |
Bronze/Bronze_V/17496.py | masterTyper/baekjoon_solved_ac | 0 | 23793 | N, T, C, P = map(int, input().split())
print(((N - 1) // T) * C * P) | 2.390625 | 2 |
sapy_script/SAP.py | fkfouri/sapy_script | 3 | 23794 | from multiprocessing import Pool, Manager
from time import sleep
from wmi import WMI
from win32com.client import GetObject
from subprocess import Popen
from collections import Iterable
from tqdm import tqdm
from os import getpid
from sapy_script.Session import Session
session_process = None
all_processes_id = []
de... | 2.4375 | 2 |
shepherd/blueprints/editor/__init__.py | Systemetric/shepherd | 0 | 23795 | import json
import os
import os.path as path
import re
from flask import Blueprint, request
blueprint = Blueprint("editor", __name__)
robotsrc_path = path.join(os.getcwd(), "robotsrc")
if not path.exists(robotsrc_path):
os.mkdir(robotsrc_path)
main_path = path.join(robotsrc_path, 'main.py')
main_file = open(main... | 2.6875 | 3 |
hai_tests/test_event_emitter.py | valohai/hai | 2 | 23796 | <filename>hai_tests/test_event_emitter.py
import pytest
from hai.event_emitter import EventEmitter
class Thing(EventEmitter):
event_types = {'one', 'two'}
@pytest.mark.parametrize('omni', (False, True))
def test_event_emitter(omni):
t = Thing()
events = []
def handle(sender, **args):
asser... | 2.234375 | 2 |
dit/divergences/tests/test_jensen_shannon_divergence.py | chebee7i/dit | 0 | 23797 | """
Tests for dit.divergences.jensen_shannon_divergence.
"""
from nose.tools import assert_almost_equal, assert_raises
from dit import Distribution
from dit.exceptions import ditException
from dit.divergences.jensen_shannon_divergence import (
jensen_shannon_divergence as JSD,
jensen_shannon_divergence_pmf as... | 2.46875 | 2 |
demo/test_scans.py | zhanwj/multi-task-pytorch | 2 | 23798 | <filename>demo/test_scans.py
import torch
maxdisp = 10
disp_scans = torch.arange(maxdisp).view(1,maxdisp,1,1)
zeros_scans = torch.arange(maxdisp).view(1,maxdisp,1,1)
semseg = torch.arange(16).view(4,4)
zeros_scans = torch.cat([zeros_scans.repeat(1, repeat,1, 1) for i in range(1)],dim=0)
| 2.265625 | 2 |
models.py | collingreen/yaib_plugin_leavemessage | 0 | 23799 | <filename>models.py
from sqlalchemy import Table, Column, String, DateTime, Text
from modules.persistence import Base, getModelBase
CustomBase = getModelBase('leavemessage')
class Message(Base, CustomBase):
user = Column(String(200))
nick = Column(String(100))
message_time = Column(DateTime)
to_nick... | 2.84375 | 3 |