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 |
|---|---|---|---|---|---|---|
Truck.py | GLayton-TX/Delivery_application | 0 | 12776751 | # class for the truck object
# max of 16 packages
# travel at 18mph
# 3 trucks but only 2 drivers
# 8am earliest departure from hub
import Location
import Utility
import Package
# the truck object, initializes with parameters set in the assessment
# time_space complexity of O(1)
class Truck:
de... | 3.921875 | 4 |
tests/core/tests_category.py | caputomarcos/django-bmf | 0 | 12776752 | #!/usr/bin/python
# ex:set fileencoding=utf-8:
# flake8: noqa
from __future__ import unicode_literals
from django.test import TestCase
from django.utils.translation import ugettext_lazy as _
from djangobmf.core.category import Category
from collections import OrderedDict
class ClassTests(TestCase):
pass
# ... | 2.390625 | 2 |
vega/core/trainer/callbacks/model_checkpoint.py | qixiuai/vega | 0 | 12776753 | # -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | 2.171875 | 2 |
kernel/type.py | zhouwenfan/temp | 0 | 12776754 | # Author: <NAME>
from collections import OrderedDict
class TypeMatchException(Exception):
pass
class HOLType():
"""Represents a type in higher-order logic.
Types in HOL are formed by two kinds of constructors: TVar and Type.
TVar(name) represents a type variable with the given name. Type(f, arg... | 3.953125 | 4 |
test/fake_combo_dataset_generation.py | EdwardDixon/facenet | 3 | 12776755 | <gh_stars>1-10
import json
import numpy as np
from itertools import combinations
from sklearn.externals import joblib
def compare(x,y):
dist = np.sqrt(np.sum(np.square(np.subtract(x, y))))
return (dist)
def get_sim(vecs):
n=len(vecs)
if(n<=1):
return 1,0,0,n
combe12=list(combinations(rang... | 2.921875 | 3 |
Stat_Calculator/Median.py | cy275/Statistics_Calculator | 0 | 12776756 | def median(a):
a = sorted(a)
list_length = len(a)
num = list_length//2
if list_length % 2 == 0:
median_num = (a[num] + a[num + 1])/2
else:
median_num = a[num]
return median_num
| 3.734375 | 4 |
tests/test_sample.py | harshkothari410/refocus-python | 0 | 12776757 | <reponame>harshkothari410/refocus-python<gh_stars>0
import sys, os
sys.path.insert(0, os.path.abspath('..'))
from refocus import Refocus
r = Refocus()
def test_post_success_sample():
data = {
'name' : 'test_subject',
'isPublished' : True
}
subject = r.subject.post(data)
subjectId = subject['id']
name = 'exa... | 2.421875 | 2 |
examples/readdir.py | jorge-imperial/mongo_ftdc | 2 | 12776758 | import pyftdc
import datetime
p = pyftdc.FTDCParser()
start = datetime.datetime.now()
p.parse_dir('/home/jorge/diagnostic.data', lazy=False)
end = datetime.datetime.now()
t = end - start
print(t)
| 2.4375 | 2 |
python/lambda-dlq-destinations/dlq/core_lambda.py | chejef/aws-cdk-examples-proserve | 0 | 12776759 | from constructs import Construct
from aws_cdk import (
Duration,
aws_sqs as sqs,
aws_sns as sns,
aws_lambda as _lambda,
aws_lambda_event_sources as events,
)
lambda_timeout = Duration.seconds(15)
visibility_timeout = lambda_timeout.plus(Duration.seconds(5))
retention_period = Duration.minutes(60)
... | 2.34375 | 2 |
alex/applications/PublicTransportInfoCS/slu/dailogregclassifier/download_models.py | oplatek/alex | 184 | 12776760 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
import autopath
from alex.utils.config import online_update
if __name__ == '__main__':
online_update("applications/PublicTransportInfoCS/slu/dailogregclassifier/dailogreg.nbl.model.all")
| 1.140625 | 1 |
MA/__main__.py | highvelcty/MediaArchivist | 0 | 12776761 | <filename>MA/__main__.py
# === Imports ======================================================================================
# Standard library
# Local library
from .gui import root
# === Main =========================================================================================
gui = root.MediaArchivistGUI()
gui... | 1.609375 | 2 |
tron/Nubs/deprecated/rawin.py | sdss/tron | 0 | 12776762 | <reponame>sdss/tron<filename>tron/Nubs/deprecated/rawin.py<gh_stars>0
from tron import g, hub
name = 'rawin'
listenPort = 6090
def acceptStdin(in_f, out_f, addr=None):
""" Create a command source with the given fds as input and output. """
d = Hub.RawCmdDecoder('gcam', EOL='\r\n', debug=9)
e = Hub.RawR... | 2.34375 | 2 |
Merida/model.py | rahulmadanraju/Semantic-Search-Engine | 2 | 12776763 | from sentence_transformers import SentenceTransformer
from process import processing_combined
import pickle as pkl
# Corpus with example sentences
def model_transformer(query_data):
df_sentences_list, df = processing_combined(query_data)
embedder = SentenceTransformer('bert-base-nli-mean-tokens')
corpus =... | 2.5625 | 3 |
Amelie/views.py | HuMingqi/Amelie_S | 0 | 12776764 | from django.http import HttpResponse
from django.shortcuts import render_to_response
import json
from . import feature_vector
from . import dist
from . import top_k
import re
import codecs
#import sys
#import imp
# imp.reload(sys)
# sys.setdefaultencoding('utf-8') #python3 don't has this method,the default on Pyth... | 2.171875 | 2 |
day4.py | Camology/AdventOfCode2020 | 0 | 12776765 | import re
input = open("inputs/day4.txt", "r")
#credit to themanush on r/adventofcode I was very confused how to nicely read this in
lines = [line.replace("\n", " ") for line in input.read().split("\n\n")]
#part1
requiredItems = ["byr","iyr","eyr","hgt","hcl","ecl","pid"]
acceptedPP = 0
for line in lines:
if all(... | 3.78125 | 4 |
src/abaqus/StepOutput/OutputModel.py | Haiiliin/PyAbaqus | 7 | 12776766 | <filename>src/abaqus/StepOutput/OutputModel.py
import typing
from abaqusConstants import *
from .FieldOutputRequest import FieldOutputRequest
from .HistoryOutputRequest import HistoryOutputRequest
from .IntegratedOutputSection import IntegratedOutputSection
from .TimePoint import TimePoint
from ..Model.ModelBase impor... | 2.359375 | 2 |
sac/sac.py | iarhbahsir/rl-algorithms | 0 | 12776767 | import random
import numpy as np
import matplotlib.pyplot as plt
from torch import tensor
from torch import cat
from torch import clamp
from torch.distributions import normal
from torch import nn
import torch.nn.functional as F
from torch import optim
from torch.utils.tensorboard import SummaryWriter
import torch
imp... | 2.46875 | 2 |
manage.py | dgkilolo/Blog | 0 | 12776768 | <gh_stars>0
from app import create_app,db
from flask_script import Manager,Server
from app.models import Quotes, Writer, Posts, Comments
from flask_migrate import Migrate, MigrateCommand
# Creating app instance
app = create_app('production')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('serve... | 2.4375 | 2 |
src/devicegroup.py | nlitz88/ipmifan | 0 | 12776769 |
class DeviceGroup:
def __init__(self, name):
self.name = name
self.devices = []
def addDevice(self, newDevice):
self.devices.append(newDevice)
# Just thinking through how I want the program to work.
# A diskgroup should be initialized once every time the service is started. ... | 3.53125 | 4 |
tests/test_repo/test_estacionamento_crud_repo/base.py | BoaVaga/boavaga_server | 0 | 12776770 | <reponame>BoaVaga/boavaga_server
import pathlib
import unittest
from unittest.mock import Mock
from src.container import create_container
from src.enums import UploadStatus
from src.classes import MemoryFileStream
from src.models import AdminSistema, AdminEstacio, Estacionamento, Veiculo, Upload
from src.repo import E... | 2.03125 | 2 |
youtube_dl/downloader/external.py | builder07/ytdl | 5 | 12776771 | <gh_stars>1-10
from __future__ import unicode_literals
import os.path
import subprocess
from .common import FileDownloader
from ..utils import (
cli_option,
cli_valueless_option,
cli_bool_option,
cli_configuration_args,
encodeFilename,
encodeArgument,
)
class ExternalFD(FileDownloader):
... | 2.34375 | 2 |
ormar/queryset/__init__.py | smorokin/ormar | 0 | 12776772 | from ormar.queryset.filter_query import FilterQuery
from ormar.queryset.limit_query import LimitQuery
from ormar.queryset.offset_query import OffsetQuery
from ormar.queryset.order_query import OrderQuery
from ormar.queryset.queryset import QuerySet
__all__ = ["QuerySet", "FilterQuery", "LimitQuery", "OffsetQuery", "Or... | 1.34375 | 1 |
unimport/statement.py | abdulniyaspm/unimport | 1 | 12776773 | import operator
from typing import List, NamedTuple, Union
class Import(NamedTuple):
lineno: int
column: int
name: str
package: str
def __len__(self) -> int:
return operator.length_hint(self.name.split("."))
class ImportFrom(NamedTuple):
lineno: int
column: int
name: str
... | 3.125 | 3 |
examples/other/export_x3d.py | evanphilip/vedo | 0 | 12776774 | """Embed a 3D scene
in a webpage with x3d"""
from vedo import dataurl, Plotter, Volume, Text3D
plt = Plotter(size=(800,600), bg='GhostWhite')
embryo = Volume(dataurl+'embryo.tif').isosurface().decimate(0.5)
coords = embryo.points()
embryo.cmap('PRGn', coords[:,1]) # add dummy colors along y
txt = Text3D(__doc__, fon... | 2.984375 | 3 |
project/apps/keller/inlines.py | barberscore/archive-api | 0 | 12776775 | <reponame>barberscore/archive-api<gh_stars>0
# Django
from django.contrib import admin
# Local
from .models import Flat
class FlatInline(admin.TabularInline):
model = Flat
fields = [
'selection',
'complete',
'score',
]
extra = 0
show_change_link = True
classes = [
... | 1.625 | 2 |
cluster_2.py | plrlhb12/my_scanpy_modules | 0 | 12776776 | import h5py
import os
import argparse
import numpy as np
import pandas as pd
import scanpy as sc
def cluster(args):
"""
Clustering cells after computing pca and neiborhood distances.
"""
input = args.input
out = args.out
dpi = args.dpi
figsize = args.figsize
figure_type = args.figure_ty... | 2.75 | 3 |
autoclass/autoargs_.py | erocarrera/python-autoclass | 33 | 12776777 | import sys
from collections import OrderedDict
from makefun import wraps
try: # python 3+
from inspect import signature, Signature
except ImportError:
from funcsigs import signature, Signature
try: # python 3.5+
from typing import Tuple, Callable, Union, Iterable
except ImportError:
pass
from deco... | 2.96875 | 3 |
tornadoes_plot/plot_single_tornado.py | Shom770/data-science-projects | 0 | 12776778 | from operator import itemgetter
from shapefile import Reader
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.img_tiles as cimgt
import matplotlib.pyplot as plt
from metpy.plots import USCOUNTIES
from statsmodels.nonparametric.smoothers_lowess import lowess
# Constants
EF_COLORS = {
... | 2.203125 | 2 |
Core/Block_C/RC500_Factory.py | BernardoB95/Extrator_SPEDFiscal | 1 | 12776779 | <filename>Core/Block_C/RC500_Factory.py
from Core.IFactory import IFactory
from Regs.Block_C import RC500
class RC500Factory(IFactory):
def create_block_object(self, line):
self.rc500 = _rc500 = RC500()
_rc500.reg_list = line
return _rc500
| 2.21875 | 2 |
notebooks/cognitive-services/textanalytics-sentiment.py | kawo123/azure-databricks | 0 | 12776780 | # Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC # Spark integration with Azure Cognitive Services
# MAGIC
# MAGIC At Spark + AI Summit 2019, Microsoft announced a new set of models in the SparkML ecosystem that make it easy to leverage the Azure Cognitive Services at terabyte scales. With only a few lines of... | 2.453125 | 2 |
tasks/dataflow/dataset/create.py | drakesvoboda/ProGraML | 71 | 12776781 | <gh_stars>10-100
# Copyright 2019-2020 the ProGraML authors.
#
# Contact <NAME> <<EMAIL>>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | 1.6875 | 2 |
betdaq/endpoints/betting.py | jackrhunt13/betdaq | 13 | 12776782 | <filename>betdaq/endpoints/betting.py<gh_stars>10-100
import datetime
from betdaq.enums import Boolean
from betdaq.utils import clean_locals, listy_mc_list
from betdaq.endpoints.baseendpoint import BaseEndpoint
from betdaq.errorparsers.betting import err_cancel_market, err_suspend_orders
from betdaq.resources.betting... | 2.453125 | 2 |
analysis/paper_plots.py | Achilleas/aqua-py-analysis | 0 | 12776783 | import h5py
import os, sys, glob
import numpy as np
import plotly.offline as offline
from preprocessing import analysis_pp
from analysis.general_utils import aqua_utils, saving_utils, plotly_utils, general_utils, compare_astro_utils, correlation_utils, stat_utils
from scipy.stats.stats import power_divergence
from scip... | 2.046875 | 2 |
src/chat/train.py | lingeen/lingeen-Ying | 0 | 12776784 | # -*- coding: utf-8 -*-
# @Time : 2020/12/24 3:48 PM
# @Author : Kevin
from src.chat import dataset
from src.chat.seq2seq import ChatSeq2Seq
from torch.optim import Adam
import torch.nn.functional as F
import torch
from src import config
from tqdm import tqdm
from src.lib import device,chat_answer_word_sequence_mod... | 2.40625 | 2 |
gammapy/spectrum/tests/test_cosmic_ray.py | grburgess/gammapy | 3 | 12776785 | <reponame>grburgess/gammapy<gh_stars>1-10
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from astropy.units import Quantity
from astropy.tests.helper import assert_quantity_allclose
from ...spectrum import cosmic_ray_flu... | 2 | 2 |
2. Programming Fundamentals With Python (May 2021)/18. Mid Exam Preparation/More Exercises/02_muOnline.py | kzborisov/SoftUni | 1 | 12776786 | <filename>2. Programming Fundamentals With Python (May 2021)/18. Mid Exam Preparation/More Exercises/02_muOnline.py
"""
You have initial health 100 and initial bitcoins 0.
You will be given a string, representing the dungeons rooms.
Each room is separated with '|' (vertical bar): "room1|room2|room3…"
Each room contains... | 4.3125 | 4 |
source/yorm/mixins.py | faraazkhan/aws-control-tower-customizations | 20 | 12776787 | <gh_stars>10-100
import warnings
from yorm import utilities
class ModelMixin:
"""Adds ORM methods to a mapped class."""
@classmethod
def create(cls, *args, **kwargs):
return utilities.create(cls, *args, **kwargs)
@classmethod
def new(cls, *args, **kwargs):
msg = "ModelMixin.new(... | 2.328125 | 2 |
AD18-flask-admin-image-demo/app/extensions.py | AngelLiang/Flask-Demos | 3 | 12776788 | from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
db = SQLAlchemy()
admin = Admin(template_mode='bootstrap3')
def register_extensions(app):
db.init_app(app)
admin.init_app(app)
from app.admin_ import register_modelviews
register_modelviews(admin, app)
| 1.71875 | 2 |
utils/graphUtils/graphML.py | VishnuDuttSharma/gnn_pathplanning | 86 | 12776789 | # 2018/11/01~2018/07/12
# <NAME>, <EMAIL>.
"""
graphML.py Module for basic GSP and graph machine learning functions.
Functionals
LSIGF: Applies a linear shift-invariant graph filter
spectralGF: Applies a linear shift-invariant graph filter in spectral form
NVGF: Applies a node-variant graph filter
EVGF: Applies an ed... | 2.609375 | 3 |
winter/core/utils/__init__.py | DmitryKhursevich/winter | 9 | 12776790 | <reponame>DmitryKhursevich/winter<gh_stars>1-10
from .beautify_string import camel_to_human
from .cached_property import cached_property
from .nested_types import TypeWrapper
from .nested_types import has_nested_type
from .positive_integer import PositiveInteger
| 1.3125 | 1 |
ml/train/evaluation/model_scoring.py | ishaanjain/video-annotation-tool | 12 | 12776791 | <filename>ml/train/evaluation/model_scoring.py<gh_stars>10-100
import keras
import numpy as np
import os
from keras_retinanet.utils.eval import _get_detections
from keras_retinanet.utils.eval import _get_annotations
from keras_retinanet.utils.anchors import compute_overlap
""" Evaluate a given dataset using a given m... | 2.671875 | 3 |
sshr/_compat.py | zhengxiaowai/sshm | 0 | 12776792 | <filename>sshr/_compat.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import six
if six.PY3:
from io import IOBase
file = (IOBase, six.StringIO)
else:
file = (file, six.StringIO)
| 2.03125 | 2 |
Modules/mystuff.py | Keerti-Gautam/PythonLearning | 0 | 12776793 | def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
def addition():
x = int(raw_input("Please enter the first number to be added: "))
y = int(raw_input("Please enter the second number to be added: "))
#return x+y
z = x+y
return z
| 3.84375 | 4 |
lucene/build_index.py | lavizhao/keyword | 3 | 12776794 | #coding: utf-8
import lucene
import csv
print "预处理"
INDEX_DIR = '../index'
lucene.initVM()
directory = lucene.SimpleFSDirectory(lucene.File(INDEX_DIR))
analyzer = lucene.StandardAnalyzer(lucene.Version.LUCENE_CURRENT)
def get_data():
"""
"""
f = open("../data/new_train.csv")
reader = csv.reader(f)
... | 2.859375 | 3 |
chuong_3.py | ngcngmnh/lt_he_thong_dien | 1 | 12776795 | import array
import math
import chuong_1
import chuong_2
def bien_ap_t1():
s_max=abs(chuong_2.s_a)
s_dm_B=s_max/1.4
d_p_n=260
d_p_0=100
u_n=14
i_0=0.045
r_b1=d_p_n*110**2/20000**2*10**3
z_b1=u_n*110**2/20000*10
x_b1=math.sqrt(z_b1**2-r_b1**2)
d_q_FE=i_0*20000/100
print('S_ptm... | 2.46875 | 2 |
labs/ex04/template/ex04.py | kcyu1993/ML_course_kyu | 0 | 12776796 | # Useful starting lines
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# %load_ext autoreload
# %autoreload 2
from sklearn import linear_model
# from __future__ import absolute_import
from labs.ex03.template import helpers
from labs.ex04.template.costs import compute_rmse, compute_mse
from la... | 2.578125 | 3 |
virtualmother_app/module/database.py | guralin/virtual_mother | 0 | 12776797 | <reponame>guralin/virtual_mother
#!/bin/env python
# coding: utf-8
from virtualmother_app import db
from virtualmother_app.models import Table,TodoTable
from flask_sqlalchemy import SQLAlchemy
import datetime
# views.py (/register)
class SendData(Table):
# カラムに値を代入
def __init__(self, user_id, get_up_time):
... | 2.578125 | 3 |
GUI.py | Kr0nox/LaunchpadTool | 1 | 12776798 | <reponame>Kr0nox/LaunchpadTool
import tkinter as tk
import webbrowser
from LaunchpadListener import LaunchpadListener
import time
import threading
import math
from typing import List
from KeyProfile import KeyProfile
import Actions
launchpad = None
profiles: List[KeyProfile] = []
UI = None
UNCLICKED = "... | 2.390625 | 2 |
lecture_04/302_ros_hello_world_listener.py | farzanehesk/COMPAS-II-FS2022 | 11 | 12776799 | import time
from roslibpy import Topic
from compas_fab.backends import RosClient
def receive_message(message):
print("Received: " + message["data"])
with RosClient("localhost") as client:
print("Waiting for messages...")
listener = Topic(client, "/messages", "std_msgs/String")
listener.subscribe(r... | 2.5 | 2 |
tests/show_text_input.py | royqh1979/easygui_qt | 53 | 12776800 | import os
import sys
sys.path.insert(0, os.getcwd())
try:
from easygui_qt import easygui_qt
except ImportError:
print("problem with import")
name = easygui_qt.text_input(message="What is your name?",
title="Mine is Reeborg.")
print(name, end='')
| 2.390625 | 2 |
studies/handwriting-all-digits/NPQC/JOB_SPECIFICATION.py | chris-n-self/large-scale-qml | 6 | 12776801 | <reponame>chris-n-self/large-scale-qml<filename>studies/handwriting-all-digits/NPQC/JOB_SPECIFICATION.py
"""
"""
import numpy as np
#
# Set all run arguments
#
BACKEND_NAME = 'aer_simulator'
N_QUBITS = 8
DEPTH = 8
TYPE_CIRCUIT = 1
TYPE_DATASET = 4
APPLY_STRATIFY = True
RESCALE_FACTOR = 1.
N_PCA_FEATURES = 36
N_BOOTS... | 1.84375 | 2 |
layers/__init__.py | MSU-MLSys-Lab/CATE | 15 | 12776802 | from .graphEncoder import PairWiseLearning
from .graphEncoder import GraphEncoder
from .loss import KLDivLoss
__all__ = ["PairWiseLearning", "KLDivLoss", "GraphEncoder"] | 1.046875 | 1 |
open_relation/hex/hex_setup.py | sx14/hierarchical-relationship | 1 | 12776803 | def hed_setup(E_h, E_e):
"""
使用理解矩阵构建HEX图
:param E_h: H-edge-mat
:param E_e: E-edge-mat
:return: G
"""
| 2.015625 | 2 |
imagr_users/forms.py | cewing/cfpydev-imagr | 0 | 12776804 | from django import forms
from imagr_users.models import ImagrUser
from registration.forms import RegistrationForm
class ImagrUserRegistrationForm(RegistrationForm):
def clean_username(self):
"""Validate that the username is alphanumeric and is not already in use.
"""
existing = ImagrUser.o... | 2.5625 | 3 |
chatclient.py | charchitdahal/Chat-Server | 0 | 12776805 | #!/usr/bin/env python
import socket
import os
import sys
import thread
import time
import json
server_ip = sys.argv[1]
server_port = 1134
username = sys.argv[2]
sock = socket.socket( socket.AF_INET,socket.SOCK_DGRAM )
def get_messages():
global sock, username
while True:
data = None
try:
... | 3.125 | 3 |
init_db.py | zhy0216-collection/Gather | 0 | 12776806 | <gh_stars>0
# coding=utf-8
import settings
import pymongo
db = pymongo.Connection(host=settings.mongodb_host,
port=settings.mongodb_port)[settings.database_name]
db.members.create_index([('created', -1)])
db.topics.create_index([('last_reply_time', -1), ('node', 1)])
db.replies.create_index([(... | 2.25 | 2 |
sdk/python/generated/azuremarketplace/saas/models/subscription_summary_py3.py | Ercenk/AMPSaaSSpecs | 0 | 12776807 | <filename>sdk/python/generated/azuremarketplace/saas/models/subscription_summary_py3.py
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenera... | 1.929688 | 2 |
main/edit-distance-hr/edit-distance-hr.py | EliahKagan/old-practice-snapshot | 0 | 12776808 | #!/usr/bin/env python3
def read_text():
"""Reads a line of text, stripping whitespace."""
return input().strip()
def distance(s, t):
"""Wagner-Fischer algorithm"""
if len(s) < len(t):
s, t = t, s
pre = [None] * (len(t) + 1)
cur = list(range(len(pre)))
for i, sc in enumerate(s, ... | 3.875 | 4 |
library/__init__.py | DanielLevy0705/algosec-ansible-role | 13 | 12776809 | <reponame>DanielLevy0705/algosec-ansible-role
__author__ = '<NAME> (@AlmogCohen)'
__version__ = '0.0.1'
| 0.726563 | 1 |
tareas/4/JimenezRodrigo/Tarea4.py | EnriqueAlbores03/sistop-2022-1 | 6 | 12776810 | <reponame>EnriqueAlbores03/sistop-2022-1<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 27 21:06:27 2021
@author: RGJG
"""
global A
global posicion
A=[]
posicion=0
def modos(archivo,identificador,modo,A,posicion):
A.append([archivo,identificador,modo,posicion,False])
return A
print("""dir → Mues... | 2.421875 | 2 |
engine/test/unit/app/test_app_api.py | pcanto-hopeit/hopeit.engine | 15 | 12776811 | from typing import Optional
import pytest
import hopeit.app.api as api
from hopeit.app.config import EventType
from hopeit.server.api import APIError
from mock_app import mock_app_api_get, MockData, mock_app_api_post, mock_app_api_get_list
from mock_app import mock_api_app_config, mock_api_spec # noqa: F401
def te... | 1.828125 | 2 |
tests/test_client/test_init.py | Flickswitch/phx_events | 0 | 12776812 | import asyncio
from urllib.parse import urlencode
import pytest
from phx_events.client import PHXChannelsClient
pytestmark = pytest.mark.asyncio
class TestPHXChannelsClientInit:
def setup(self):
self.socket_url = 'ws://test.socket/url/'
self.channel_auth_token = '<PASSWORD>'
self.phx_... | 2.109375 | 2 |
apps/stats/urls.py | puertoricanDev/horas | 10 | 12776813 | from django.urls import re_path
from .views import StatsView
urlpatterns = [re_path("^$", StatsView.as_view(), name="stats")]
| 1.507813 | 2 |
newbeginning/network/test-analysis/distributionplots.py | arnavkapoor/fsmresults | 0 | 12776814 | <gh_stars>0
# import plotly.plotly as py
# import plotly.graph_objs as go
# import plotly.figure_factory as FF
import math
import numpy as np
import pandas as pd
import matplotlib as mplt
import itertools
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
neededfiles = ['aim.fsm','battlef... | 2.3125 | 2 |
vice/toolkit/hydrodisk/data/download.py | rcooke-ast/VICE | 22 | 12776815 | <reponame>rcooke-ast/VICE
import urllib.request
import sys
import os
PATH = os.path.dirname(os.path.abspath(__file__))
NSUBS = int(30) # hard coded into VICE
def download(verbose = True):
r"""
Downloads the h277 supplementary data from VICE's source tree on GitHub
"""
if not os.path.exists("%s/h277" % (PATH)): o... | 2.765625 | 3 |
xroms0/depth.py | bjornaa/xroms0 | 0 | 12776816 | """Vertical structure functions for ROMS
:func:`sdepth`
Depth of s-levels
:func:`zslice`
Slice a 3D field in s-coordinates to fixed depth
:func:`multi_zslice`
Slice a 3D field to several depth levels
:func:`z_average`
Vertical average of a 3D field
:func:`s_stretch`
Compute vertical stretching arrays Cs_r or... | 2.75 | 3 |
tests/test_table_input.py | abcnishant007/sklearn-evaluation | 351 | 12776817 | <filename>tests/test_table_input.py
from unittest import TestCase
from sklearn_evaluation import table
class TestMissingInput(TestCase):
def test_feature_importances(self):
with self.assertRaisesRegex(ValueError, "needed to tabulate"):
table.feature_importances(None)
| 2.640625 | 3 |
src/api.py | edgartan/slack_movie_app | 0 | 12776818 | import sys
sys.path.insert(1, "lib/")
# This going against PEP-8 will refactor once we have a build pipeline
import os
import json
import logging
import requests
import cachetools.func
class MovieApis:
api_key = os.environ.get("API_KEY")
# instance method
@cachetools.func.ttl_cache(maxsize=20, ttl=300)
... | 2.4375 | 2 |
src/checker/httpstatusmonitor.py | red-lever-solutions/system-checker | 1 | 12776819 | <filename>src/checker/httpstatusmonitor.py
from .mylog import log
import requests
def monitor(url, method="GET", data=None, headers=None, verify_ssl=True):
log.debug("Checking http status code of %s", url)
try:
if method.lower() == "get":
response = requests.get(url, data=data, headers=hea... | 2.8125 | 3 |
update_data.py | claire9501/d3-group-project | 0 | 12776820 | # Dependencies
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
# Go to existing database with automap_base
from sqlalchemy.ext.automap import automap_base
# Work through mapper to use python code
from sqlalchemy.orm import Session, relationship
# Inspect with python
from sqlalchemy import create_eng... | 2.96875 | 3 |
CDSB_series/cumul/main.py | WFDetector/WFDetection | 0 | 12776821 | import numpy as np
import sys
#for calculate the loss
from sklearn.metrics import log_loss
from sklearn.metrics import make_scorer
#import three machine learning models
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
#for stan... | 2.09375 | 2 |
text_analysis_tools/api/sentiment/sentiment.py | yu3peng/text_analysis_tools | 149 | 12776822 | # -*- coding: utf-8 -*-
import os
import json
import jieba.analyse
import jieba
CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
sentiment_path = os.path.join(CURRENT_PATH, 'data', 'sentimentDict.json')
stopwords_path = os.path.join(CURRENT_PATH, 'data', 'stopwords.txt.json')
degree_path = os.path.join(CUR... | 2.921875 | 3 |
infra_macros/macro_lib/convert/sphinx.py | martarozek/buckit | 0 | 12776823 | #!/usr/bin/env python2
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""... | 1.804688 | 2 |
Factorial.py | holtjma/pyku | 0 | 12776824 | '''
Factorial int
Recurse Implementation
Auth.: holtjma
'''
def dec(Input):
'''
Pyku for decrement:
y equals input
y equals y minus two
return y plus one
'''
y = Input
y = y-2
return y+1
def fac(x):
'''
Pyku for factorial:
if x and not false
return x times fac dec x... | 3.6875 | 4 |
tintest.py | SaxonWang99/CMPE273-WeWin | 0 | 12776825 | import requests
import json
print("register node 5000, 5001, 5002, 5003, 5004, 5005")
m_node = {
"nodes" : ["http://127.0.0.1:5000","http://127.0.0.1:5001",
"http://127.0.0.1:5002","http://127.0.0.1:5003","http://127.0.0.1:5004","http://127.0.0.1:5005"]
}
r = requests.post('http://127.0.0.1:5000/nodes/regis... | 2.78125 | 3 |
scripts/NoIp/noIp.py | tatan8425/hal-9000-webserver | 0 | 12776826 | <gh_stars>0
import requests, socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close... | 2.96875 | 3 |
python/hijack/sacrifice.py | mum-chen/funny | 1 | 12776827 | <gh_stars>1-10
from kidnapper import Kidnapper, Human
@Kidnapper.ransom
class Sacrifice(Human):
def say_name(self):
print("I'm Sacrifice")
| 2.640625 | 3 |
src/keras_exp/distrib/cluster_parsers/slurm.py | avolkov1/keras_experiments | 92 | 12776828 | # Taken from: https://github.com/jhollowayj/tensorflow_slurm_manager
# ref:
# https://github.com/jhollowayj/tensorflow_slurm_manager/blob/master/slurm_manager.py
# @IgnorePep8
'''
'''
from __future__ import print_function
import os
import re
# import socket
# depends on hostlist: pip install python-hostlist
import ho... | 2.265625 | 2 |
solutions/python3/problem665.py | tjyiiuan/LeetCode | 0 | 12776829 | # -*- coding: utf-8 -*-
"""
665. Non-decreasing Array
Given an array nums with n integers, your task is to check if it could become non-decreasing
by modifying at most 1 element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Constraints:
1 <=... | 3.671875 | 4 |
Backend/src/flask_app.py | BSAkash/ChatBot | 0 | 12776830 | from flask import Flask, render_template, request, jsonify
import conversation
# import traceback
app = Flask(__name__)
app.config["DEBUG"] = True
conversation.initBrain()
@app.route('/')
def index():
return render_template('main_page.html')
@app.route('/api/', methods=["GET","POST"])
def api():
try:
... | 2.515625 | 3 |
tools/w3af/w3af/core/controllers/core_helpers/consumers/tests/test_base_consumer.py | sravani-m/Web-Application-Security-Framework | 3 | 12776831 | """
test_base_consumer.py
Copyright 2011 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that ... | 1.78125 | 2 |
11/11.py | pemcconnell/euler | 0 | 12776832 | <reponame>pemcconnell/euler<gh_stars>0
import re
SIZE = 4
GREATESTPRODUCT = 0
def find_biggest(cells):
global GREATESTPRODUCT
gp = 0
l = len(cells)
for i,num in enumerate(cells):
if i > (l - SIZE):
break
x = SIZE-1
p = 1
while x >= 0:
p *= int(cells[i+x])
x -= 1
if p > gp:
gp = p
if gp > GR... | 2.953125 | 3 |
utils.py | Air-Fighter/KnowledgeEnhancedTE | 1 | 12776833 | <gh_stars>1-10
"""
Utility functions.
"""
import argparse
# list comprehension operator
# COMP = require("pl.comprehension").new()
def printerr(msg):
print '\033[1;31;40m',
print msg,
print '\033[0m'
def get_args():
parser = argparse.ArgumentParser(description='Structured Attention PyTorch ... | 2.6875 | 3 |
data/hr/csv2json.py | rbt-lang/rbt-proto | 9 | 12776834 |
import sys
import csv
import json
icsv = csv.DictReader(sys.stdin)
ojson = { "departments": [] }
dept_data = ojson["departments"]
dept_name_idx = {}
for line in icsv:
dept_name = line["dept_name"]
dept = dept_name_idx.get(dept_name)
if dept is None:
dept = dept_name_idx[dept_name] = { "name": dep... | 3.078125 | 3 |
src/cobald/daemon/runners/base_runner.py | thoto/cobald | 7 | 12776835 | import logging
import threading
from typing import Any
from cobald.daemon.debug import NameRepr
class BaseRunner(object):
flavour = None # type: Any
def __init__(self):
self._logger = logging.getLogger(
"cobald.runtime.runner.%s" % NameRepr(self.flavour)
)
self._payloads... | 2.171875 | 2 |
discrete_pole.py | yashpatel5400/ot_experiments | 0 | 12776836 | <filename>discrete_pole.py
import gym
import math
import numpy as np
import sklearn
from sklearn.linear_model import SGDRegressor
from sklearn.pipeline import Pipeline
from sklearn.kernel_approximation import RBFSampler
import matplotlib.pyplot as plt
env = gym.make('CartPole-v0')
env.reset()
episodes = 1000
gamma = ... | 2.40625 | 2 |
app/modules/assets/controllers.py | systemaker/Flask-Easy-Template | 11 | 12776837 | <reponame>systemaker/Flask-Easy-Template
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ------- IMPORT DEPENDENCIES -------
import datetime
import sendgrid
import os
import json
from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMultiDict
from flask import request, render_template, fl... | 2.09375 | 2 |
complexity_normalized.py | DReichLab/adna-workflow | 9 | 12776838 | import argparse
import subprocess
from pathlib import Path
from multiprocessing import Pool
picard_jar = None
def normalized_unique_reads(number_of_reads, bam):
try:
downsampled_library = downsample(number_of_reads, bam)
unique_bam = remove_duplicates(downsampled_library)
unique_reads = count_bam_reads(unique_... | 2.578125 | 3 |
src/main.py | wene37/WeConnect-SolarManager | 2 | 12776839 | #!/usr/bin/python
import logging
import logging.handlers
import configparser
from time import sleep
from SolarManager import SolarManager
def log_setup():
formatter = logging.Formatter("%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s")
logLevel = logging.INFO
log_handler = logging.handlers.... | 2.5625 | 3 |
mundo_1/desafios/desafio_027.py | lvfds/Curso_Python3 | 0 | 12776840 | <gh_stars>0
"""
Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.
Ex: <NAME>
primeiro = Ana
último = Sousa
"""
valor_digitado = input('Digite seu nome completo: ')
transformar_valor_digitado_em_lista = valor_digitado.split()
primei... | 3.640625 | 4 |
persister/observations/management/commands/initialize_data.py | City-of-Helsinki/hel-data-pipe | 1 | 12776841 | from django.core.management.base import BaseCommand
from observations.models import Datasourcetype
class Command(BaseCommand):
def handle(self, *args, **options):
Datasourcetype.objects.get_or_create(
name="Digital Matter Sensornode LoRaWAN",
defaults={
"descriptio... | 1.90625 | 2 |
ezancestry/process.py | arvkevi/ezancestry | 26 | 12776842 | <gh_stars>10-100
import warnings
from pathlib import Path
import joblib
import pandas as pd
from cyvcf2 import VCF
from loguru import logger
from sklearn.preprocessing import OneHotEncoder
from snps import SNPs
from ezancestry.config import aisnps_directory as _aisnps_directory
from ezancestry.config import aisnps_se... | 2.265625 | 2 |
chapter03/battle_scene.py | gothedistance/python-book | 17 | 12776843 | <reponame>gothedistance/python-book<filename>chapter03/battle_scene.py
import random
# 自分のヒットポイント
my_hit_point = 15
# スライムのヒットポイント
slime_hit_point = 8
# こうげきの順番
# ここでは自分から攻撃するものとする
index = 0
# どちらかのヒットポイントがあるまで戦う
# ヒットポイントが0以下になると繰り返しが終わる
while slime_hit_point > 0 and my_hit_point > 0:
# ランダムに与えるダメージを決定
attack... | 3.265625 | 3 |
cctbx/sgtbx/direct_space_asu/plane_group_reference_table.py | dperl-sol/cctbx_project | 155 | 12776844 | <filename>cctbx/sgtbx/direct_space_asu/plane_group_reference_table.py
from __future__ import absolute_import, division, print_function
from cctbx.sgtbx.direct_space_asu import direct_space_asu
from cctbx.sgtbx.direct_space_asu.short_cuts import *
from six.moves import range
def asu_01(): # p_1 (s.g. 1)
return (direc... | 1.945313 | 2 |
python/fixrgraph/db/scripts/querydb.py | LesleyLai/biggroum | 7 | 12776845 | <reponame>LesleyLai/biggroum
""" Test script used to query the db programmatically
"""
import sys
import os
import optparse
import logging
import string
import collections
from fixrgraph.db.isodb import IsoDb
import sqlalchemy
if (len(sys.argv) != 2):
print "Not enough param"
db_path=sys.argv[1]
if (not os.p... | 2.59375 | 3 |
login_register/apps/userAuth/urls/v1/urls.py | Mr-IT007/django-vue | 1 | 12776846 | from django.urls import path
from rest_framework.routers import SimpleRouter
from apps.userAuth.views.v1.views import SendCodeView, UserViewSet
router = SimpleRouter(trailing_slash=False)
router.register('user', UserViewSet, base_name='user')
urlpatterns = [
path('sendcode', SendCodeView.as_view(), name='sendco... | 1.828125 | 2 |
src/replys/serializers.py | banfstory/REST-API-DJANGO | 0 | 12776847 | from rest_framework import serializers
from .models import Reply
from users.models import Profile
from comments.models import Comment
class ReplySerializer(serializers.HyperlinkedModelSerializer):
user = serializers.PrimaryKeyRelatedField(queryset=Profile.objects.all())
comment = serializers.PrimaryKeyRelatedField... | 2.1875 | 2 |
src/ipyannotations/__init__.py | tabaspki/ipyannotations | 0 | 12776848 | """Annotate data in jupyter notebooks."""
__version__ = "0.2.0"
from .images import PolygonAnnotator, PointAnnotator, BoxAnnotator
__all__ = ["PolygonAnnotator", "PointAnnotator", "BoxAnnotator"]
| 1.632813 | 2 |
hpc/collect.py | samvonderdunk/artistoo | 0 | 12776849 | #!/usr/bin/env python
#
# collect.py renames files from subdirectories
#
# Copyright <NAME>, 2007--2018
"""
Synopsis:
Rename files or folders following a pattern containing an integer index,
as in 'image0001.png'. The file will be moved in the current directory
The number in the file name is inc... | 3.875 | 4 |
models/codegnngru.py | AntonPrazdnichnykh/CodeGNN-pytorch | 0 | 12776850 | <reponame>AntonPrazdnichnykh/CodeGNN-pytorch<gh_stars>0
from typing import Tuple, List, Dict, Union
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from pytorch_lightning import LightningModule
from omegaco... | 2.015625 | 2 |