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 |
|---|---|---|---|---|---|---|
cse4305-compilers/Exceptions.py | mqt0029/univ-courses | 0 | 12770751 | <reponame>mqt0029/univ-courses
# <NAME>
# mqt0029
# 1001540029
# 2019-05-13
#---------#---------#---------#---------#---------#--------#
class InternalError( Exception ) : pass
class LexicalError( Exception ) : pass
class SemanticError( Exception ) : pass
class SyntacticError( Exception ) : pass
#---------#-------... | 1.570313 | 2 |
pegasus/dados/insertion/insert_into_all_SINASC.py | SecexSaudeTCU/PegaSUS | 0 | 12770752 | <reponame>SecexSaudeTCU/PegaSUS
###########################################################################################################################
# SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC SINASC #
######################################... | 1.632813 | 2 |
Navigation.py | jvalderr239/DeepQNetwork | 0 | 12770753 | #!/usr/bin/env python
# coding: utf-8
# # Navigation
#
# ---
#
# You are welcome to use this coding environment to train your agent for the project. Follow the instructions below to get started!
#
# ### 1. Start the Environment
#
# Run the next code cell to install a few packages. This line will take a few minut... | 3.015625 | 3 |
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/fortinet/fortimanager/plugins/modules/fmgr_widsprofile.py | Stienvdh/statrick | 0 | 12770754 | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
# Copyright 2019-2020 Fortinet, Inc.
#
# This program 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, either version 3 of the ... | 1.375 | 1 |
curd/connections/utils/sql.py | jdxin0/curd | 8 | 12770755 | from datetime import datetime, timezone
class BaseClause(object):
def __init__(self, field, value):
self._field = field
self._value = value
@property
def field(self):
return '.'.join(
['`{}`'.format(i) for i in self._field.replace('`', '').split('.')])
... | 2.90625 | 3 |
solutions/2121.py | pacokwon/leetcode | 2 | 12770756 | # Intervals Between Identical Elements
from typing import List
from collections import defaultdict
class Solution:
def getDistances(self, arr: List[int]) -> List[int]:
indices = defaultdict(list)
for index, n in enumerate(arr):
indices[n].append(index)
ans = [0] * len(arr)
... | 3.421875 | 3 |
boto/kinesis/layer1.py | Grindizer/boto | 6 | 12770757 | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights ... | 1.625 | 2 |
src/hierarchy/stationary.py | drvinceknight/HierarchicalPromotion | 0 | 12770758 | import numpy as np
import hierarchy as hrcy
def get_stationary_distribution(capacities, r, lmbda, mu):
assert capacities[-1] == 1
matrix = hrcy.transitions.get_transition_matrix(
capacities=capacities, r=r, lmbda=lmbda, mu=mu
)
dimension = matrix.shape[0]
M = np.vstack((matrix.transpose(... | 2.484375 | 2 |
Day_14_Web_Automation/using_soup.py | ValRCS/Python_TietoEvry_Sep2021 | 0 | 12770759 | import requests
from bs4 import BeautifulSoup as bs
url = "https://mdn.github.io/beginner-html-site/"
response = requests.get(url) # this is like going to our browser and going to the url
print(response.status_code) # 200 would be good 404 would be bad
print(response.text[:500]) # first 500 characters
# i could ... | 3.703125 | 4 |
regtests/test-all.py | ahakingdom/Rusthon | 622 | 12770760 | <filename>regtests/test-all.py
import os, subprocess
os.chdir( os.path.split(__file__)[0] )
subprocess.check_call(['python', 'test-c++.py'])
subprocess.check_call(['python', 'test-go.py'])
subprocess.check_call(['python', 'test-javascript.py'])
subprocess.check_call(['python', 'test-markdowns.py'])
| 2.109375 | 2 |
Trabalhos/Python/MiniEP/coordenada.py | phelipes2000/Ola-Mundo | 0 | 12770761 | <gh_stars>0
def coord(x,y):
if x > 0 and y > 0:
i = "I"
elif x > 0 and y < 0:
i = "IV"
elif x < 0 and y < 0:
i = "III"
elif x < 0 and y > 0:
i = "II"
print(f"O ponto ({x:.0f}, {y:.0f}) pertence ao quadrante: {i}")
print(" ")
def main():
a = float(input("Digit... | 3.8125 | 4 |
scripts/searcher.py | lmdu/PanMicrosatDB | 0 | 12770762 | <gh_stars>0
import os
import sys
import csv
import gzip
import time
import json
import numpy
import queue
import signal
import shutil
import sqlite3
import traceback
import itertools
import collections
import multiprocessing
from ..thirds import kseq, ncls, tandem
from ..thirds.motifs import MotifStandard
from ..confi... | 2.203125 | 2 |
WEEKS/CD_Sata-Structures/_RESOURCES/python-prac/mini-scripts/python_NumPy_Summations_2.txt.py | webdevhub42/Lambda | 5 | 12770763 | import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])
newarr = np.sum([arr1, arr2])
print(newarr)
| 3.234375 | 3 |
nobos_commons/tools/skeleton_converters/skeleton_converter_openpose_to_stickman.py | noboevbo/nobos_commons | 2 | 12770764 | <reponame>noboevbo/nobos_commons
from nobos_commons.data_structures.skeletons.joint_2d import Joint2D
from nobos_commons.data_structures.skeletons.skeleton_openpose import SkeletonOpenPose
from nobos_commons.data_structures.skeletons.skeleton_stickman import SkeletonStickman
from nobos_commons.tools.skeleton_converters... | 2.1875 | 2 |
mots_vides/tests/shortcut.py | Fantomas42/mots-vides | 13 | 12770765 | <reponame>Fantomas42/mots-vides<filename>mots_vides/tests/shortcut.py
"""
Tests for shortcuts
"""
from unittest import TestCase
from mots_vides import stop_words
from mots_vides.stop_words import StopWord
from mots_vides.exceptions import StopWordError
class StopWordShortcutTestCase(TestCase):
def test_stop_wor... | 2.359375 | 2 |
rastervision_core/rastervision/core/utils/misc.py | theoway/raster-vision | 1,577 | 12770766 | <reponame>theoway/raster-vision
import io
from pydantic import confloat
from PIL import Image
import numpy as np
import imageio
import logging
Proportion = confloat(ge=0, le=1)
log = logging.getLogger(__name__)
def save_img(im_array, output_path):
imageio.imwrite(output_path, im_array)
def numpy_to_png(array... | 2.8125 | 3 |
python-sdk/experimental/deploy-triton/src/score_densenet.py | 0mza987/azureml-examples | 331 | 12770767 | <gh_stars>100-1000
import io
import numpy as np
import os
from azureml.core import Model
from azureml.contrib.services.aml_request import rawhttp
from azureml.contrib.services.aml_response import AMLResponse
from PIL import Image
from onnxruntimetriton import InferenceSession
def preprocess(img, scaling): # , dtype... | 2.28125 | 2 |
visualize_predictions_graph.py | jmhessel/multi-retrieval | 28 | 12770768 | '''
for i in predictions/test/*; do python visualize_predictions.py $i\/doc.json $i/pred_weights.npy prediction_dir/$i ; done;
'''
import argparse
import numpy as np
import bipartite_utils
import json
import os
import subprocess
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
def parse_args(... | 2.28125 | 2 |
app.py | EmmanuelleAD/api_livres_categories_iai | 0 | 12770769 | <filename>app.py
import os
from flask import Flask,abort,jsonify,request
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
username=os.getenv('user')
mdp=os.getenv('pswd')
host=os.getenv('host')
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='p... | 2.5 | 2 |
code/radix_sort.py | mrtryhard/SortingsBenchmarkPython | 0 | 12770770 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import math
# Tri par base (RadixSort)
# lst : liste à trier
# max_len : longueur max d'un nombre (int: 10)
def tri_par_base(lst, max_len = 10):
# un nombre n'aura pas plus que 10 digit.
NB_BUCKETS = 10
for x in range(max_len):
... | 3.828125 | 4 |
structural/facade.py | zhengxiaowai/python-javascript-design-patterns | 6 | 12770771 | <reponame>zhengxiaowai/python-javascript-design-patterns
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class HardWare(object):
def power_on(self):
print('上电')
def bootloader(self):
print('bootloader 启动')
def power_off(self):
print('断电')
class OperatingSystem(object):
def l... | 3.171875 | 3 |
bin/get_tractor_images.py | UnofficialJuliaMirrorSnapshots/SloanDigitalSkySurvey.jl-d2185075-3040-5c42-a634-a12f38dbd79b | 0 | 12770772 | #!/usr/bin/python
#
# Load a processed image from the tractor. Note that as of writing,
# the masking was incorrect.
# https://github.com/dstndstn/tractor
from tractor.sdss import *
import argparse
import numpy
import copy
parser = argparse.ArgumentParser()
parser.add_argument('--run', type=int, help='The run numbe... | 2.484375 | 2 |
simulation.py | thiagogvasc/CPU_Scheduler_Simulator | 1 | 12770773 | from process import Process
from process import State
class Simulation:
def __init__(self, data, cpu, scheduling):
self.data = data
self.cpu = cpu
self.scheduling = scheduling
self.processes = []
### Initiate all processes at the same time since they all arrive at t = 0
... | 3.3125 | 3 |
lungs_ml/lungs_ml/visualization_service/__init__.py | dumaevrinat/lung_diseases | 3 | 12770774 | <reponame>dumaevrinat/lung_diseases<gh_stars>1-10
from .visualization_service import VisualizationService
| 1.03125 | 1 |
concat/tests/level1/test_execute.py | jmanuel1/concat | 5 | 12770775 | import concat.level1.execute
import unittest
import ast
from typing import Dict
class TestExecute(unittest.TestCase):
names = ['to_int', 'to_bool', 'to_complex', 'len', 'getitem', 'to_float',
'decode_bytes', 'to_tuple', 'to_bytes', 'to_list', 'to_bytearray',
'to_set', 'add_to_set', 'to_f... | 2.53125 | 3 |
src/bo4e/com/tarifpreispositionproort.py | bo4e/BO4E-python | 1 | 12770776 | """
Contains TarifpreispositionProOrt class
and corresponding marshmallow schema for de-/serialization
"""
from typing import List
import attr
from marshmallow import fields
from bo4e.com.com import COM, COMSchema
from bo4e.com.tarifpreisstaffelproort import TarifpreisstaffelProOrt, TarifpreisstaffelProOrtSchema
fro... | 1.929688 | 2 |
src/python/src/grpc/framework/foundation/later.py | iMilind/grpc | 2 | 12770777 | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | 1.375 | 1 |
pycrunch_trace/client/networking/client_trace_introspection.py | yswtrue/pycrunch-trace | 90 | 12770778 | import collections
from collections import defaultdict
from typing import List, Dict
from pycrunch_trace.tracing.file_map import FileMap
class ClientTraceIntrospection:
total_events: int
def __init__(self):
self.total_events = 0
self.stats = defaultdict(int)
# file id -> hit count
... | 2.765625 | 3 |
week4_ml/aiDB.py | ohmink/relay_02 | 1 | 12770779 | import sqlite3
class AI_DB(object):
def __init__(self, db_file_name):
self.conn = sqlite3.connect(db_file_name)
self.cur = self.conn.cursor()
def read_1_data(self, user_id):
query = "SELECT * FROM user WHERE user_id="+str(user_id)
self.cur.execute(query)
row = self.cur.f... | 3.28125 | 3 |
FormManagement/migrations/0001_initial.py | SajedeNick1999/Payslip-Management- | 1 | 12770780 | # Generated by Django 3.0.8 on 2020-08-05 20:30
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('CompanyManagement', '0001_initial'),
]
operat... | 1.828125 | 2 |
a10/build/lib/a10/asvr/db/__init__.py | THS-on/AttestationEngine | 7 | 12770781 | <reponame>THS-on/AttestationEngine<gh_stars>1-10
# Copyright 2021 Nokia
# Licensed under the BSD 3-Clause Clear License.
# SPDX-License-Identifier: BSD-3-Clear
| 0.949219 | 1 |
yardstick/tests/unit/benchmark/scenarios/networking/test_vsperf_dpdk.py | mythwm/yardstick | 0 | 12770782 | <reponame>mythwm/yardstick
# Copyright 2017 Nokia
#
# 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 agr... | 1.78125 | 2 |
pro1/interviews/urls.py | BhanuPrakashNani/StudentPortal | 0 | 12770783 | <filename>pro1/interviews/urls.py<gh_stars>0
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.home, name='interview-home'),
]
| 1.75 | 2 |
src/versions/Iter4/helpapp-seproject/api/update_user.py | chenbachar/MitzvahApp | 0 | 12770784 | import webapp2
import json
from models.user import User
class UpdateUserHandler(webapp2.RequestHandler):
def get(self):
user = User.checkUser()
if not user:
return
update_name = self.request.get('name')
update_car = self.request.get('car')
needCar = False
if update_car == 'true':
ne... | 2.46875 | 2 |
next/boot/fe/parser.py | 27Saumya/next | 2 | 12770785 | <reponame>27Saumya/next
# Copyright 2022 VincentRPS
#
# 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 agr... | 2.34375 | 2 |
jobapplications/migrations/0005_auto_20200204_1927.py | MattYu/ConcordiaAce | 1 | 12770786 | <gh_stars>1-10
# Generated by Django 3.0 on 2020-02-05 00:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobapplications', '0004_auto_20200204_0004'),
]
operations = [
migrations.RemoveField(
model_name='ranking',
... | 1.757813 | 2 |
irisProblem.py | wriggs12/Machine-Learning-Practice | 1 | 12770787 | <filename>irisProblem.py<gh_stars>1-10
import numpy as np
from scipy.spatial import distance
import matplotlib.pyplot as plt
def euc(a, b):
return distance.euclidean(a, b)
class personalKNN():
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def p... | 2.609375 | 3 |
script_remote.py | ArthurSStrong/actions-bot | 0 | 12770788 | <gh_stars>0
"""
Connects to the Reddit API to get rising submissions details and posts
them to a Discord webhook.
"""
import os
import requests
import random
WEBHOOK_URL = os.environ["WEBHOOK"]
def main():
"""Start the script."""
list_reddit = ['doodles','DigitalPainting','drawing','Illustration','concepta... | 3.703125 | 4 |
libtool/util/regex.py | matan-h/libtool | 0 | 12770789 | <reponame>matan-h/libtool<filename>libtool/util/regex.py
import re
def get_val(val, string):
sec = """{}(\s|)+=(\s|)+(["'])(.*)(["'])""".format(val)
return re.findall(sec, string)[0][3]
| 2.875 | 3 |
mysite/asd.py | iml1111/django-study | 0 | 12770790 | <reponame>iml1111/django-study
from django_jwt_extended.decorators import jwt_required
@jwt_required()
def asdasdasd():
return "sad"
asdasdasd() | 1.976563 | 2 |
core/filters.py | ankit94/ShoppingWebsiteDjango | 0 | 12770791 | <gh_stars>0
import django_filters
from django_filters import CharFilter
from .models import Item
class ItemFilter(django_filters.FilterSet):
title = CharFilter(field_name='title', lookup_expr='icontains')
class Meta:
model = Item
fields = ['title']
| 1.789063 | 2 |
scripts/plot_Figure5.py | pabloitu/pycsep_esrl-1 | 0 | 12770792 | <reponame>pabloitu/pycsep_esrl-1
# Python imports
import os
import json
import time
# 3rd party impoorts
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
# pycsep imports
from csep import load_catalog_forecast, load_catalog, load_json, load_evaluation_result
from csep.models import Event,... | 1.789063 | 2 |
resource_tracker/migrations/0005_auto_20211015_1015.py | LaudateCorpus1/squest | 112 | 12770793 | # Generated by Django 3.2.7 on 2021-10-15 08:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resource_tracker', '0004_alter_resourcepoolattributedefinition_resource_pool'),
]
operations = [
migrations.RenameField(
model_name='res... | 1.679688 | 2 |
api/core/migrations/0001_initial.py | JRMurr/rps | 1 | 12770794 | <filename>api/core/migrations/0001_initial.py<gh_stars>1-10
# Generated by Django 2.2.5 on 2019-09-19 23:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
... | 1.710938 | 2 |
varana/varana/fit.py | pbrus/variability-analyser | 2 | 12770795 | <reponame>pbrus/variability-analyser<filename>varana/varana/fit.py<gh_stars>1-10
"""
Fit a sum of sines to the light curve.
"""
from math import sqrt, pow, atan2
from typing import Callable, Tuple, List
import numpy as np
from numpy import ndarray
from scipy.optimize import curve_fit
from varana.freq_comb import lin... | 2.90625 | 3 |
caption_vae/version.py | jiahuei/test-caption-actions | 3 | 12770796 | <reponame>jiahuei/test-caption-actions
# -*- coding: utf-8 -*-
"""
Created on 31 Dec 2020 12:18:55
@author: jiahuei
"""
__version__ = "0.4.0"
| 0.523438 | 1 |
examples/async.py | cmheisel/presentation-python-threading | 0 | 12770797 | <gh_stars>0
"""
Thanks to http://skipperkongen.dk/2016/09/09/easy-parallel-http-requests-with-python-and-asyncio/ for the pattern.
"""
import asyncio
from timeit import default_timer as timer
import requests
URLS = [
"http://slowyourload.net/5/https://chrisheisel.com",
"http://slowyourload.net/4/https://chr... | 3.265625 | 3 |
python/cudf/io/json.py | tgravescs/cudf | 1 | 12770798 | <filename>python/cudf/io/json.py
# Copyright (c) 2019, NVIDIA CORPORATION.
import cudf
from cudf.utils import ioutils
import pandas as pd
import warnings
@ioutils.doc_read_json()
def read_json(path_or_buf, *args, **kwargs):
"""{docstring}"""
warnings.warn("Using CPU via Pandas to read JSON dataset, this ma... | 2.5625 | 3 |
setup.py | CUrW-SL/distributed_hechms | 1 | 12770799 | from setuptools import setup,find_packages
setup(
name='hechmsd',
version='1.0.0',
packages=find_packages(),
url='http://www.curwsl.org/',
license='',
author='hasitha',
author_email='<EMAIL>',
description='HecHms Distributed version',
include_package_data=True,
install_requires=... | 1.023438 | 1 |
app/auth/models.py | farooq-teqniqly/envino | 0 | 12770800 | from datetime import datetime
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(UserMixin, db.Model):
id = db.Column(db.String(32), primary_key=True)
username = db.Column(db.String(128), index=True, unique=True, nullable=False)
email = db.Column(db.St... | 2.6875 | 3 |
scripts/swipe_parameter.py | zjc263/GPU_SDR | 9 | 12770801 | import sys,os,random
import numpy as np
try:
import pyUSRP as u
except ImportError:
try:
sys.path.append('..')
import pyUSRP as u
except ImportError:
print "Cannot find the pyUSRP package"
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=... | 2.640625 | 3 |
update_data.py | PatShot/simpleCryptoViz | 0 | 12770802 | <filename>update_data.py
#!/usr/bin/env python3
import requests
import os
import pandas as pd
from datetime import datetime, timedelta
#Constants
API_BASE = 'https://api.coingecko.com/api/v3/'
ASSET_PLAT = '/asset_platforms'
COIN_LIST = '/coins/list'
def make_data_dir():
new_dir = os.path.join(os.getcwd(), 'data... | 2.84375 | 3 |
labs/lab2-b.py | sw33tr0ll/aws-training | 2 | 12770803 | <gh_stars>1-10
#!/usr/bin/env python3
import boto3
s3_client = boto3.client('s3')
# retrieve list of buckets
raw_response = s3_client.list_buckets()
# for each bucket in your list....
for bucket in raw_response['Buckets']:
bucketName = bucket['Name']
# grab (raw) information about the objects in that buc... | 3.359375 | 3 |
src/main/python/systemds/operator/algorithm/builtin/shortestPath.py | mdbloice/systemds | 372 | 12770804 | <reponame>mdbloice/systemds
# -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF lice... | 1.804688 | 2 |
gnet/gnet_manager_four_rooms_subgoals_3d.py | jleung1/goal_modelling_rl | 0 | 12770805 | <filename>gnet/gnet_manager_four_rooms_subgoals_3d.py
from gnet.gnet_manager import GNetManager
import numpy as np
DEBUG = False
class FourRoomSubgoals3DGNetManager(GNetManager):
def __init__(self, env, gnet_goals, qrm=False):
super().__init__(env, gnet_goals, last_num_goals=50, max_exploration_rate=0.8)... | 2.375 | 2 |
MedTAG_Dockerized/MedTAG_sket_dock_App/sket/sket/sket.py | MedTAG/medtag-core | 6 | 12770806 | <filename>MedTAG_Dockerized/MedTAG_sket_dock_App/sket/sket/sket.py
import os
import uuid
import json
from .rep_proc.report_processing import ReportProc
from .ont_proc.ontology_processing import OntoProc
from .nerd.nerd import NERD
from .rdf_proc.rdf_processing import RDFProc
from .utils import utils
class SKET(obje... | 2 | 2 |
satellite/output/slicer.py | mtsmarcoto/deep-learning | 0 | 12770807 | <gh_stars>0
import logging
import os
import gdal
from satellite import settings
from os.path import basename
from PIL import Image
class Slicer:
"""
When infering, images with bigger dimensions than the ones used for training should be handled before predictions.
This class provide the utilities for that... | 2.75 | 3 |
dsplot/tree/__init__.py | avere001/dsplot | 8 | 12770808 | from .binary_tree import BinaryTree
| 1.070313 | 1 |
liquid/golden/unless_tag.py | jg-rp/liquid | 19 | 12770809 | <filename>liquid/golden/unless_tag.py
"""Golden tests cases for testing liquid's `unless` tag."""
from liquid.golden.case import Case
cases = [
Case(
description="literal false condition",
template=r"{% unless false %}foo{% endunless %}",
expect="foo",
),
Case(
description=... | 2.28125 | 2 |
Contest/ABC001/b/main.py | mpses/AtCoder | 0 | 12770810 | <reponame>mpses/AtCoder<gh_stars>0
#!/usr/bin/env python3
m = int(input())
if m < 100:
print("00")
elif m <= 5000:
print(str(m//100).zfill(2))
elif m <= 30000:
print(m//1000 + 50)
elif m <= 70000:
print((m//1000 - 30)//5 + 80)
else:
print(89) | 3.15625 | 3 |
algorithms/math/modular_exponentiation.py | jainrocky/python-ds | 1,723 | 12770811 | # to compute modular power
# Iterative Function to calculate
# (x^y)%p in O(log y)
def power(x, y, p) :
res = 1 # Initialize result
# Update x if it is more
# than or equal to p
x = x % p
while (y > 0) :
# If y is odd, multiply
# x with result
... | 3.953125 | 4 |
tests/test_basics.py | leuchtum/folderman | 0 | 12770812 | <gh_stars>0
import pytest
from folderman import Folder
def test_root_path():
pass
| 1.085938 | 1 |
players/cheating_idiot_player.py | timotree3/hanabi-1 | 25 | 12770813 | """A despicable Hanabi player.
Cheating Idiot never hints. He peeks at his cards. When he has a play, he
picks one randomly. When he doesn't, he discards randomly.
"""
from hanabi_classes import *
from bot_utils import get_plays
class CheatingIdiotPlayer(AIPlayer):
@classmethod
def get_name(cls):
... | 3.140625 | 3 |
gpscraper/forms/permissions.py | alverelt/gpscraper | 1 | 12770814 | import json
def permissions(app_id):
form = {
'f.req': [[[
'xdSrCf',
f'[[null,["{app_id}",7],[]]]',
None,
'1'
]]]
}
form['f.req'] = json.dumps(form['f.req'], separators=(',', ':'))
return form | 2.1875 | 2 |
radicalsdk/radar/v1_constants.py | moodoki/radical_sdk | 7 | 12770815 | import os
import numpy as np
class TupperwearD435_0:
F = np.load(os.path.join(os.path.dirname(__file__), 'v1_data/f_matrix.npy'))
P = np.load(os.path.join(os.path.dirname(__file__), 'v1_data/p_matrix_original.npy'))
class TupperwearD435:
F = np.load(os.path.join(os.path.dirname(__file__), 'v1_data/f_matri... | 2.46875 | 2 |
src/pykeen/evaluation/__init__.py | camillepradel/pykeen | 2 | 12770816 | # -*- coding: utf-8 -*-
"""Evaluators.
========= =============================================
Name Reference
========= =============================================
rankbased :class:`pykeen.evaluation.RankBasedEvaluator`
sklearn :class:`pykeen.evaluation.SklearnEvaluator`
========= =====================... | 1.71875 | 2 |
api/urls.py | NiklasMerz/shoppinglist | 0 | 12770817 | <reponame>NiklasMerz/shoppinglist
from django.urls import include, path
from rest_framework import routers
from api import views
from rest_framework.schemas import get_schema_view
router = routers.DefaultRouter()
router.register(r'lists', views.ListViewSet)
router.register(r'catalogitems', views.CatalogItemViewSet)
ro... | 2.109375 | 2 |
tally_ho/apps/tally/views/home.py | onaio/tally-ho | 12 | 12770818 | from django.urls import reverse
from django.shortcuts import redirect, render
from django.views.generic import TemplateView
from guardian.mixins import LoginRequiredMixin
from tally_ho.libs.permissions import groups
from tally_ho.apps.tally.models import UserProfile
GROUP_URLS = {
groups.AUDIT_CLERK: "audit",
... | 1.859375 | 2 |
name_recommender/pipeline/run_lstm_model.py | lassevalentini/NameRecommender | 0 | 12770819 | <gh_stars>0
import json
import joblib
from azureml.core.model import Model
# Called when the service is loaded
def init():
global model
# Get the path to the deployed model file and load it
model_path = Model.get_model_path("name_lstm")
model = joblib.load(model_path)
# Called when a request is rece... | 2.875 | 3 |
asset/api.py | 745184532/cmdb | 251 | 12770820 | from rest_framework import generics
from .models import AssetInfo
from .serializers import AssetSerializer
from rest_framework import permissions
class AssetList(generics.ListCreateAPIView):
queryset = AssetInfo.objects.all()
serializer_class = AssetSerializer
permission_classes = (permissions.AllowAny,)
... | 1.960938 | 2 |
chaussette/_paste.py | ProzorroUKR/chaussette | 74 | 12770821 | <gh_stars>10-100
import os
from six.moves import configparser
from logging.config import fileConfig
try:
from paste.deploy import loadapp
except ImportError:
raise ImportError("You need to install PasteDeploy")
def paste_app(path):
# Load the logging config from paste.deploy .ini, if any
path, hsh, ... | 2.375 | 2 |
backend/bitcoin_arbitrage/api/views.py | landdafku11/cryptocurrencybot | 1 | 12770822 | <reponame>landdafku11/cryptocurrencybot
import logging
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from bitcoin_arbitrage.models import Spread, Tri_Spread
from bitcoin_arbitrage.api.mixins import MonitorMixin
from .serial... | 2.078125 | 2 |
utils/slack_msg_fmt.py | angeleneleow/rocket2 | 14 | 12770823 | <filename>utils/slack_msg_fmt.py
"""Utility class for formatting Slack Messages."""
def wrap_slack_code(str):
"""Format code."""
return f"`{str}`"
def wrap_code_block(str):
"""Format code block."""
return f"```\n{str}\n```"
def wrap_quote(str):
"""Format quote."""
return f"> {str}\n"
def... | 2.171875 | 2 |
transparentai_ui/app/controllers/projects.py | Nathanlauga/transparentai-ui | 1 | 12770824 | from flask import request, render_template, redirect, url_for, session, jsonify, abort
from flask_babel import _
import os.path
import pandas as pd
from transparentai import sustainable
from ..models import Project
from ..models.modules import ModuleSustainable
from .services.projects import format_project, control_p... | 2.40625 | 2 |
languages/python/2.learn_more_py_the_hard_way/ex06/find.py | banminkyoz/learn | 4 | 12770825 | <filename>languages/python/2.learn_more_py_the_hard_way/ex06/find.py
from sys import exit
import argparse
import os.path
import re
class Find:
args = ()
result_count = 0
def __init__(self):
self.get_arguments()
self.check_arguments()
self.search()
def get_arguments(self):
... | 3.578125 | 4 |
python/constants.py | raymonshansen/dungeon | 4 | 12770826 | import pygame as pg
TILE_D = 32
# Comment in for small or big screen
# HD screen
SCREEN_TW, SCREEN_TH = 50, 30
# Low res screen
SCREEN_TW, SCREEN_TH = 35, 20
SCREEN_W_PX = SCREEN_TW * TILE_D
SCREEN_H_PX = SCREEN_TH * TILE_D
SCREEN_SIZE = (SCREEN_W_PX, SCREEN_H_PX)
MAP_VIEW_TW = int(SCREEN_TW * 0.7)
MAP_VIEW_TH ... | 2.5 | 2 |
data_collection/gazette/spiders/sc_pescaria_brava.py | kaiocp/querido-diario | 454 | 12770827 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScPescariaBravaSpider(FecamGazetteSpider):
name = "sc_pescaria_brava"
FECAM_QUERY = 'entidade:"Prefeitura Municipal de Pescaria Brava"'
TERRITORY_ID = "4212650"
| 1.375 | 1 |
testa_usuario.py | ecompfin-ufrgs/economia_computacional1 | 2 | 12770828 | <filename>testa_usuario.py
"""
Programa 2
Descrição: Este programa pede a entrada de dados pelo usuário
até que o dado seja do tipo adequado.
Autor: <NAME>
Versão: 0.0.1
"""
# Entrada
# Atribuição de variáveis: usuários do sistema
usuario1 = "nelson"
usuario2 = "joao"
usuario3 = "juan"
usuario4 = "nat... | 3.625 | 4 |
tests/test_nrms/test_nrms.py | ParticleMedia/recommenders | 0 | 12770829 | """Global settings and imports"""
import sys
sys.path.append("../../")
import os
import numpy as np
import zipfile
from tqdm import tqdm
import scrapbook as sb
from tempfile import TemporaryDirectory
import tensorflow as tf
tf.get_logger().setLevel('ERROR') # only show error messages
from reco_utils.recommender.deepre... | 1.898438 | 2 |
tests/analysis/test_pearson_integration.py | AISyLab/side-channel-attacks | 14 | 12770830 | <gh_stars>10-100
import unittest
import os.path
import numpy as np
from sca.__main__ import CONST_DEFAULT_PLAIN_FILE
from sca.__main__ import CONST_DEFAULT_TRACES_FILE
from sca.__main__ import CONST_DEFAULT_KEYS_FILE
from sca.analysis.pearson import Pearson
class TestPearsonIntegration(unittest.TestCase):
"""Tes... | 2.40625 | 2 |
file_handling/excepation handling program test/print_excepation_information_in_msg.class_program.py | swarajRaut01/Python | 0 | 12770831 | <reponame>swarajRaut01/Python
#print excepation information as a msg in program
try:
print(10/0)
except ZeroDivisionError as msg:
print("the type of error:",msg.__class__)
| 2.859375 | 3 |
Linguagens/Python/Exercicios/cursos_em_video/aulas-22_23/107.py | rafaelvizu/Estudos | 0 | 12770832 | <filename>Linguagens/Python/Exercicios/cursos_em_video/aulas-22_23/107.py<gh_stars>0
from pacotes import ex107
print('\033[36;40mExercício Python #107 - Exercitando módulos em Python\033[m\n')
v = float(input('Digite o preço: R$'))
print(f'\nA metade de {v} é R${ex107.metade(v)}')
print(f'O dobro de {v} é R${ex107... | 3.265625 | 3 |
java/aspects/checkstyle_aspect/defs.bzl | birkland/dwtj_rules_java | 0 | 12770833 | '''Defines the `checkstyle_aspect`.
'''
load("//java:providers/JavaCompilationInfo.bzl", "JavaCompilationInfo")
load(
"//java:common/extract/toolchain_info.bzl",
"extract_java_runtime_toolchain_class_path_separator",
"extract_checkstyle_toolchain_info",
)
_JAVA_RUNTIME_TOOLCHAIN_TYPE = "@dwtj_rules_java//... | 2.28125 | 2 |
iaso/api/source_versions_serializers.py | BLSQ/iaso-copy | 0 | 12770834 | <filename>iaso/api/source_versions_serializers.py
import logging
import sys
from io import StringIO
from rest_framework import serializers
from iaso.diffing import Differ, Dumper
from iaso.management.commands.command_logger import CommandLogger
from iaso.models import SourceVersion, OrgUnit, OrgUnitType, Task
from ia... | 1.921875 | 2 |
GEOS_Util/coupled_diagnostics/verification/stress_mon_clim/stress_qscat.py | GEOS-ESM/GMAO_Shared | 1 | 12770835 | #!/bin/env python
import os
import scipy as sp
import matplotlib.pyplot as pl
from mpl_toolkits.basemap.cm import sstanom, s3pcpn_l
from matplotlib import dates
from g5lib import field
# Read validation data set
obs={}
path=os.environ['NOBACKUP']+'/verification/stress_mon_clim'
execfile(path+'/ctl.py')
obs['ctl']=ctl... | 1.820313 | 2 |
IMU/VTK-6.2.0/ThirdParty/Twisted/twisted/test/ssl_helpers.py | timkrentz/SunTracker | 4 | 12770836 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Helper classes for twisted.test.test_ssl.
They are in a separate module so they will not prevent test_ssl importing if
pyOpenSSL is unavailable.
"""
from __future__ import division, absolute_import
from twisted.python.compat impor... | 2.140625 | 2 |
microscopeimagequality/constants.py | MihailSalnikov/microscopeimagequality | 77 | 12770837 | <gh_stars>10-100
"""Common constants used across image quality modules."""
VALID_MASK_FORMAT = 'valid_mask_%s'
CERTAINTY_MASK_FORMAT = 'certainty_mask_%s'
PREDICTIONS_MASK_FORMAT = 'predictions_mask_%s'
ORIG_IMAGE_FORMAT = 'orig_name=%s'
PATCH_SIDE_LENGTH = 84
REMOTE_MODEL_CHECKPOINT_PATH = "https://storage.googleapi... | 1.039063 | 1 |
tests/test_aioweenect.py | eifinger/aioweenect | 1 | 12770838 | <reponame>eifinger/aioweenect
"""Tests for `aioweenect.aioweenect`."""
import json
import os
from typing import Any
import aiohttp
import pytest
from aioweenect import AioWeenect
API_HOST = "apiv4.weenect.com"
API_VERSION = "/v4"
@pytest.mark.asyncio
async def test_get_user_with_invalid_token(aresponses):
"""T... | 2.421875 | 2 |
python/testData/intentions/PyConvertTypeCommentToVariableAnnotationIntentionTest/typeHintFollowedByComment_after.py | jnthn/intellij-community | 2 | 12770839 | <gh_stars>1-10
var: int = undefined()
| 0.84375 | 1 |
drl/envs/wrappers/stateless/test_clip_reward.py | lucaslingle/pytorch_drl | 0 | 12770840 | from drl.envs.testing import LockstepEnv
from drl.envs.wrappers.stateless.clip_reward import ClipRewardWrapper
def test_clip_reward():
env = LockstepEnv()
wrapped = ClipRewardWrapper(env, low=0.0, high=0.5, key='extrinsic')
_ = wrapped.reset()
o_tp1, r_t, d_t, i_t = wrapped.step(0)
assert r_t['ex... | 2.046875 | 2 |
src/genie/libs/parser/iosxe/tests/c9300/ShowControllers/cli/equal/golden_output_expected.py | balmasea/genieparser | 0 | 12770841 | expected_output = {
"interface_name": "Gi1/0/1",
"if_id": "75",
"phy_registers": {
"0": {
"register_number": "0000",
"hex_bit_value": "1140",
"register_name": "Control Register",
"bits": "0001000101000000",
},
"1": {
"regist... | 1.421875 | 1 |
GameEngine/Application.py | Nathcat/2D-GameEngine | 0 | 12770842 | from tkinter import *
from PIL import ImageTk, Image
from GameEngine.Vector import *
class Application:
def __init__(self, title, size, fps):
self.root = Tk()
self.root.title(title)
self.width, self.height = size
self.root.geometry(f"{self.width}x{self.height}")
self.root.... | 2.859375 | 3 |
hello-xarray/write_profile.py | NIVANorge/s-enda-playground | 0 | 12770843 | #%%
from datetime import datetime
import xarray as xr
from cfxarray.profile import depthcoords, profiledataset
from cfxarray.base import dataarraybydepth
# %%
temperature1 = dataarraybydepth(
name="temperature",
standard_name="sea_water_temperature",
long_name="Sea water temperature",
units="degree_C... | 2.0625 | 2 |
utils/selenium_utils.py | Brandonthe/oosbot | 0 | 12770844 | from chromedriver_py import binary_path as driver_path
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver import Chrome, ChromeOptions # TODO: Combine these two dependencies. Leaving it for now since it touches too many sites atm.
from selenium.webdriver.chrome.options import Options
from seleni... | 2.3125 | 2 |
2021/CVE-2021-34429/poc/pocsploit/CVE-2021-34429.py | hjyuan/reapoc | 421 | 12770845 | <reponame>hjyuan/reapoc
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Jetty Authorization Before Parsing and Canonicalization Variation''',
"description": '''For Eclipse Jetty versions 9.4.37-9.4.42, 10.0.1-10.0.5 & 11.0.1-11.0.5, URIs can be craf... | 2.578125 | 3 |
feedcollector/rss.py | ctnitschke/feedcollector | 0 | 12770846 | """
Module for handling of RSS (as in Really Simple Syndication
or Rich Site Summary) feeds.
:copyright: (c) 2019 by <NAME>
:license: Apache 2.0, see LICENSE for more details.
"""
from .util import hash_xml_subtree
def merge_feeds(new_root, old_root):
"""
Merge two rss feeds contained in xml.etree.ElementTree... | 2.65625 | 3 |
fv-beginner/ex-08-memory/memtx.py | DonaldKellett/nmigen-beginner | 1 | 12770847 | from nmigen import *
from nmigen.back.pysim import *
from nmigen.asserts import *
from nmigen.test.utils import *
from nmigen.build import *
from nmigen.build import ResourceError
from nmigen.vendor.lattice_ecp5 import *
from nmigen_boards.resources import *
from functools import reduce
from math import ceil, log
impo... | 2.3125 | 2 |
migrations/versions/f0ddbf9cdd26_add_ingredient_availability_table.py | brauls/ingredients-service | 0 | 12770848 | """add ingredient availability table
Revision ID: f0ddbf9cdd26
Revises: 7cf38c4ce08a
Create Date: 2019-06-28 21:34:49.780023
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f0ddbf9cdd26'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def... | 1.359375 | 1 |
Leetcode/Sorting,_Binary_Search/1_-_Easy/349._Intersection_of_Two_Arrays.py | Khalid-Sultan/Algorithms-Prep | 1 | 12770849 | <reponame>Khalid-Sultan/Algorithms-Prep
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
l = set(nums1)
ret = [i for i in nums2 if i in l]
return list(set(ret)) | 3.796875 | 4 |
misago/misago/core/testproject/searchfilters.py | vascoalramos/misago-deployment | 2 | 12770850 | def test_filter(search):
return search.replace("MMM", "Marines, Marauders and Medics")
| 1.851563 | 2 |