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 |
|---|---|---|---|---|---|---|
parser/fase2/team20/execution/executeSentence2.py | LopDlMa/tytus | 0 | 10000 | <gh_stars>0
from .AST.sentence import *
from .AST.expression import *
from .AST.error import *
import sys
sys.path.append("../")
from console import *
def executeSentence2(self, sentence):
if isinstance(sentence, CreateDatabase):
h=0
elif isinstance(sentence, ShowDatabases):
... | 2.421875 | 2 |
src/test/cli/component.py | huseyinbolt/cord-tester | 0 | 10001 | <filename>src/test/cli/component.py
# Copyright 2017-present Open Networking Foundation
#
# 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
#
# Unl... | 1.398438 | 1 |
python-framework/handlers/base/auth.py | huangxingx/python-framework | 7 | 10002 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: x.huang
# @date:17-8-4
import logging
from pony.orm import db_session
from handlers.base.base import BaseRequestHandler
class LoginRequireError(Exception):
pass
class AuthBaseHandler(BaseRequestHandler):
""" 登录验证的基类 """
def prepare(self):
... | 2.21875 | 2 |
pysol/core/helpers.py | lotfio/pysol | 2 | 10003 | # -*- coding: utf-8 -*-
#| This file is part of cony
#|
#| @package Pysol python cli application
#| @author <<NAME>>
#| @license MIT
#| @version 0.1.0
#| @copyright 2019 <NAME>
import sys
# load module function
# this function loads a module by string name
def load_module(module):
module_path ... | 2.15625 | 2 |
autograd_hacks/test_autograd_hacks.py | jusjusjus/autograd-hacks | 1 | 10004 | <reponame>jusjusjus/autograd-hacks<gh_stars>1-10
import torch
import torch.nn as nn
import torch.nn.functional as F
import pytest
from . import autograd_hacks
class StriddenNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 20, 5, stride=2, padding=2)
self.c... | 2.75 | 3 |
tests/test_command.py | paulfurley/Mailpile | 1 | 10005 | <gh_stars>1-10
import unittest
import mailpile
from mock import patch
from mailpile.commands import Action as action
from tests import MailPileUnittest
class TestCommands(MailPileUnittest):
def test_index(self):
res = self.mp.rescan()
self.assertEqual(res.as_dict()["status"], 'success')
def ... | 2.53125 | 3 |
navrep/envs/rosnavtrainencodedenv.py | ReykCS/navrep | 0 | 10006 | <reponame>ReykCS/navrep
from gym import spaces
import numpy as np
from scipy import interpolate
import yaml
from navrep.envs.navreptrainenv import NavRepTrainEnv
from navrep.rosnav_models.utils.reward import RewardCalculator
from navrep.rosnav_models.utils.reward import RewardCalculator
class RosnavTrainEncodedEnv(N... | 2.21875 | 2 |
pdm/models/repositories.py | gaojiuli/pdm | 1 | 10007 | <gh_stars>1-10
from __future__ import annotations
import sys
from functools import wraps
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple
from pdm._types import CandidateInfo, Source
from pdm.context import context
from pdm.exceptions import CandidateInfoNotFound, CorruptedCacheError
... | 2.015625 | 2 |
tests/backends/test_cookie.py | euri10/starsessions | 31 | 10008 | import pytest
from starsessions import SessionBackend
@pytest.mark.asyncio
async def test_cookie_read_write(cookie: SessionBackend, session_payload: dict) -> None:
new_id = await cookie.write(session_payload, "session_id")
assert await cookie.read(new_id) == session_payload
@pytest.mark.asyncio
async def t... | 2.28125 | 2 |
sqlalchemy_dremio/db.py | thbeh/sqlalchemy_dremio | 14 | 10009 | <gh_stars>10-100
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
from pyarrow import flight
from sqlalchemy_dremio.exceptions import Error, NotSupportedError
from sqlalchemy_dremio.flight_auth import H... | 2.25 | 2 |
docker-images/rasa2/snips_services/tts_server.py | sanyaade-machine-learning/opensnips_original | 57 | 10010 | <gh_stars>10-100
#!/opt/rasa/anaconda/bin/python
# -*-: coding utf-8 -*-
""" Snips core and nlu server. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import time
import os
from socket import error as... | 2.265625 | 2 |
gtd/migrations/0018_context_color.py | jimbofreedman/naggingnelly-api | 0 | 10011 | <gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-02 17:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gtd', '0017_auto_20180108_1508'),
]
operations = [
migrations.A... | 1.492188 | 1 |
neuralintents/main.py | nitori/neuralintents | 0 | 10012 | from abc import ABCMeta, abstractmethod
import random
import json
import pickle
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.... | 2.28125 | 2 |
cogs/TieThePie.py | Engineer152/Engineer-Bot | 0 | 10013 | <reponame>Engineer152/Engineer-Bot
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='your prefix',owner_ids = {your user id},case_insensitive=True )
class TieThePie(commands.Cog):
def __init__(self,client):
self.client=client
@commands.command()
async def tiethepie(self,... | 2.796875 | 3 |
python/lsst/eotest/simulation/generate_Fe55_images.py | tguillemLSST/eotest | 3 | 10014 | """
@brief Generate Fe55 images and associated darks and bias images
according to section 5.4 of the E/O document (Dec 19, 2012 version).
@author <NAME> <<EMAIL>>
"""
import os
import numpy as np
from sim_inputs import *
from sim_tools import *
def generate_Fe55_images(exptimes, nxrays, outdir, sensorid, gain=gain,
... | 2.15625 | 2 |
pcdet/models/backbones_3d/pfe/voxel_set_abstraction.py | rayguan97/M3DETR | 21 | 10015 | import math
import numpy as np
import torch
import torch.nn as nn
from ....ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules
from ....ops.pointnet2.pointnet2_stack import pointnet2_utils as pointnet2_stack_utils
from ....utils import common_utils
from ...backbones_2d.transformer import ... | 1.867188 | 2 |
metabot2txt/display.py | HeitorBoschirolli/metabot2txt | 0 | 10016 | <filename>metabot2txt/display.py<gh_stars>0
import os
def display_on_editor(text):
with open('.metabot2txt', 'w') as f:
f.write(text)
os.system('gedit .metabot2txt')
def display_list_on_editor(texts):
if os.path.isfile('.metabot2txt'):
os.remove('.metabot2txt')
for text in texts... | 2.859375 | 3 |
cogs/errors.py | i1470s/IVRY | 3 | 10017 | #PRIMARY IMPORTS
import discord, os, datetime, sys, json, traceback, logging
#SECONDARY IMPORTS
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from discord.ext import commands
from data import config
#LOGGING
logger = logging.getLogger("ivry")
logger.debug("errors.py Started")
class Er... | 2.3125 | 2 |
Using Python to Access Web Data/Problem 6_Extracting Data from JSON 5.py | Karoline0097/University-of-Michigan-Python-for-Everybody | 0 | 10018 | <reponame>Karoline0097/University-of-Michigan-Python-for-Everybody
## Problem 5: Extracting Data from JSON
# Example: http://py4e-data.dr-chuck.net/comments_42.json
# data consists of a number of names and comment counts in JSON
# {
# comments: [
# {
# name: "Matthias"
# count: 97
# },
# {
# ... | 3.8125 | 4 |
lessons/day_05/python/app.py | jiaguilera/a-walk-in-graphql | 16 | 10019 | from ariadne import make_executable_schema, load_schema_from_path
from ariadne.asgi import GraphQL
from resolvers import query, skill, person, eye_color, mutation
# import schema from GraphQL file
type_defs = load_schema_from_path("./schema.gql")
schema = make_executable_schema(
type_defs, query, skill, person, ... | 1.703125 | 2 |
src/__main__.py | andreaswatch/piTomation | 0 | 10020 | import importlib
import time
from pathlib import Path
import os
import sys
def import_plugins():
#find actual path
realpath = os.path.realpath(__file__)
dirname = os.path.dirname(realpath)
#add modules & plugins
plugin_path = os.path.join(dirname, "plugins")
for dir_path in Path(plugin_path).... | 2.546875 | 3 |
src/decanter/core/extra/utils.py | MatthewK3023/decanter-ai-core-sdk | 0 | 10021 | """
Functions support other modules.
"""
import uuid
def check_response(response, key=None):
"""CHeck the api response.
Make sure the status call is successful and the response have specific key.
Return:
class: `Response <Response>`
"""
code = response.status_code
if not 200 <= code ... | 3.0625 | 3 |
03/03.py | stevenpclark/aoc2021 | 1 | 10022 | <reponame>stevenpclark/aoc2021<gh_stars>1-10
import numpy as np
def filter_data(data, use_most_common):
_, nc = data.shape
for c in range(nc):
nr, _ = data.shape
if nr <= 1:
break
col_score = sum(data[:,c])/nr
if use_most_common:
keep_val = col_s... | 2.859375 | 3 |
distillation/build_student.py | fengxiaoshuai/CNN_model_optimizer | 0 | 10023 | <filename>distillation/build_student.py
import tensorflow as tf
import numpy as np
with tf.variable_scope("student"):
input_label = tf.placeholder(dtype=tf.float32, shape=[10, 10], name="label")
input_image = tf.placeholder(dtype=tf.float32, shape=[10, 224, 224, 3], name="input")
conv1 = tf.layers.conv2d(... | 2.421875 | 2 |
code/statistical_tests.py | ChamiLamelas/Math36B_FinalProject | 0 | 10024 | import scipy.stats
import numpy as np
def f_test(sample_x, sample_y, larger_varx_alt):
"""
Computes the F-value and corresponding p-value for a pair of samples and alternative hypothesis.
Parameters
----------
sample_x : list
A random sample x1,...,xnx. Let its (underlying) variance be ox... | 3.265625 | 3 |
pawpyseed/compiler.py | akashkumarsingh612/pawpyseed | 0 | 10025 | <gh_stars>0
import os, subprocess
def compile_core(comp, scilib):
"""
ATTENTION, NOT FINISHED
"""
subprocess.call(("make pawpy_%s"%comp).split())
def compile_core(comp, scilib):
"""
ATTENTION, NOT FINISHED
"""
subprocess.call("make hfc".split()) | 2.359375 | 2 |
finnhub_python/socket.py | humdings/finnhub-python | 0 | 10026 | <reponame>humdings/finnhub-python<filename>finnhub_python/socket.py
"""
Example usage of Finnhub socket API.
"""
from __future__ import print_function # Py2 compat
import websocket
from finnhub_python.utils import get_finnhub_api_key
def write_line(data, fname):
with open(fname, 'a+') as f:
f.write(data ... | 3.078125 | 3 |
pycovjson/cli/convert.py | RileyWilliams/pycovjson | 10 | 10027 | """
Pycovjson - Command line interface
Author: rileywilliams
Version: 0.1.0
"""
import argparse
from pycovjson.write import Writer
from pycovjson.read_netcdf import NetCDFReader as Reader
def main():
"""
Command line interface for pycovjson - Converts Scientific Data Formats into CovJSON and saves to disk.
... | 3.34375 | 3 |
duels/duels.py | ridinginstyle00/redcogs | 8 | 10028 | <reponame>ridinginstyle00/redcogs
import discord
from discord.ext import commands
from .utils import checks
from .utils.dataIO import dataIO
from __main__ import send_cmd_help
from __main__ import settings
from datetime import datetime
from random import choice
from random import sample
from copy import deepco... | 2.484375 | 2 |
paranuara/citizens/models/citizens.py | SPLAYER-HD/Paranuara | 0 | 10029 | <gh_stars>0
"""Citizens model."""
# Django
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
# models
from paranuara.companies.models import Company
# PostgreSQL fields
from django.contrib.postgres.fields import JSONField
# Utilities
f... | 2.40625 | 2 |
tests/utils.py | niwibe/cobrascript | 1 | 10030 | <reponame>niwibe/cobrascript<filename>tests/utils.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from cobra.utils import normalize
def norm(data):
return normalize(data)
| 1.335938 | 1 |
rgislackbot/dispatcher/dispatchconfig.py | raginggeek/RGISlackBot | 0 | 10031 | <reponame>raginggeek/RGISlackBot
class DispatchConfig:
def __init__(self, raw_config):
self.registered_commands = {}
for package in raw_config["handlers"]:
for command in package["commands"]:
self.registered_commands[command] = {
"class": package["clas... | 2.140625 | 2 |
chess/rules.py | DevStrikerTech/Chess-Engine | 18 | 10032 | <gh_stars>10-100
import pygame
from chess.board import Board
from .variable_declaration import black_piece, white_piece, position_piece, board_square_size
class Rules:
def __init__(self, window):
self._init()
self.window = window
def update(self):
self.chess_board.draw_pieces(self.win... | 3.359375 | 3 |
kivygames/games/noughtsandcrosses/__init__.py | jonathanjameswatson/kivygames | 0 | 10033 | import numpy as np
from kivygames.games import Game
import kivygames.games.noughtsandcrosses.c as c
class CellOccupiedError(Exception):
pass
class NoughtsAndCrosses(Game):
minPlayers = 2
maxPlayers = 2
hasAI = True
gridShape = (3, 3)
def __init__(self):
Game.__init__(self)
... | 2.921875 | 3 |
03-Decouvrez-POO/download_agents.py | gruiick/openclassrooms-py | 0 | 10034 | <reponame>gruiick/openclassrooms-py
#! /usr/bin/env python
import argparse
import json
import time
import urllib.error
import urllib.request
def main():
parser = argparse.ArgumentParser(description="Download agents from pplapi.com")
parser.add_argument("-c", "--count", type=int, default=10, help="Number of ag... | 2.828125 | 3 |
Commands/images.py | Mariobob/Proton | 0 | 10035 | <reponame>Mariobob/Proton<gh_stars>0
import functools
import re
import asyncio
from io import BytesIO
from discord.ext import commands
import discord
from Utils import canvas
import random
class Images:
"""
Contains commands for manipulation of images.
"""
def __init__(self, bot):
self.bot = ... | 2.890625 | 3 |
labJS/conf.py | lpomfrey/django-labjs | 0 | 10036 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from appconf import AppConf
from django.conf import settings # noqa
class LabjsConf(AppConf):
ENABLED = not settings.DEBUG
DEBUG_TOGGLE = 'labjs'
| 1.101563 | 1 |
tests/test_nanoevents_vector.py | danbarto/coffea | 0 | 10037 | import awkward as ak
from coffea.nanoevents.methods import vector
import pytest
ATOL = 1e-8
def record_arrays_equal(a, b):
return (ak.fields(a) == ak.fields(b)) and all(ak.all(a[f] == b[f]) for f in ak.fields(a))
def test_two_vector():
a = ak.zip(
{
"x": [[1, 2], [], [3], [4]],
... | 2.34375 | 2 |
testing/python/telBuggyScript2.py | sys-bio/rrplugins | 0 | 10038 | import roadrunner
import teplugins as tel
i = 0
#for i in range(100):
try:
noisePlugin = tel.Plugin ("tel_add_noise")
print noisePlugin.listOfProperties()
# Create a roadrunner instance
rr = roadrunner.RoadRunner()
rr.load("sbml_test_0001.xml")
# Generate data
data = rr.simulate(0, 10, 51... | 2.453125 | 2 |
encyclopaedia/labels.py | tcyrus/renpy-encyclopaedia | 0 | 10039 | <reponame>tcyrus/renpy-encyclopaedia
from renpy import store
class Labels(store.object):
"""Controls how the labels that display Encyclopaedia data appear.
Attributes:
percentage_label (str): Placed next to the percentage unlocked number
page_label (str): Placed before the entry page displaye... | 3.1875 | 3 |
ncservice/ncDeviceOps/threaded/get_configs.py | cunningr/yanccm | 0 | 10040 | <filename>ncservice/ncDeviceOps/threaded/get_configs.py
import logging
from ncservice.ncDeviceOps.nc_device_ops import NcDeviceOps
from ncservice.ncDeviceOps.task_report import TaskReport
from ncservice.ncDeviceOps.threaded.base_thread_class import BaseThreadClass
logger = logging.getLogger('main.{}'.format(__name__))... | 2.0625 | 2 |
CodeHS/Looping/DoubleForLoop.py | Kev-in123/ICS2O7 | 2 | 10041 | <gh_stars>1-10
"""
This program visualizes nested for loops by printing number 0 through 3
and then 0 through 3 for the nested loop.
"""
for i in range(4):
print("Outer for loop: " + str(i))
for j in range(4):
print(" Inner for loop: " + str(j)) | 4.03125 | 4 |
saleor/graphql/channel/tests/test_base_channel_listing.py | fairhopeweb/saleor | 15,337 | 10042 | from collections import defaultdict
import graphene
import pytest
from django.core.exceptions import ValidationError
from ....shipping.error_codes import ShippingErrorCode
from ..mutations import BaseChannelListingMutation
def test_validate_duplicated_channel_ids(channel_PLN, channel_USD):
# given
channel_i... | 2.40625 | 2 |
francoralite/apps/francoralite_front/tools.py | Francoralite/francoralite | 2 | 10043 | # -*- coding: utf-8 -*-
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: <NAME> / Coopérative ARTEFACTS <<EMAIL>>
import requests
from django.conf import settings
from django.contrib import messages
from dja... | 1.882813 | 2 |
python2.7/site-packages/twisted/internet/iocpreactor/client.py | 84KaliPleXon3/sslstrip-hsts-openwrt | 4 | 10044 | <reponame>84KaliPleXon3/sslstrip-hsts-openwrt<filename>python2.7/site-packages/twisted/internet/iocpreactor/client.py
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
import socket
from twisted.persisted import styles
from twisted.internet.base import BaseConnector
from twisted.inter... | 1.882813 | 2 |
pypika/tests/dialects/test_mssql.py | uhrm/pypika | 0 | 10045 | <gh_stars>0
import unittest
from pypika import Table
from pypika.analytics import Count
from pypika.dialects import MSSQLQuery
from pypika.utils import QueryException
class SelectTests(unittest.TestCase):
def test_normal_select(self):
q = MSSQLQuery.from_("abc").select("def")
self.assertEqual('S... | 2.515625 | 3 |
Postprocessing/Hardt/Hardt.py | maliha93/Fairness-Analysis-Code | 0 | 10046 | <reponame>maliha93/Fairness-Analysis-Code
import cvxpy as cvx
import numpy as np
from collections import namedtuple
from metric import metric, cd
import pandas as pd
import sys
from helper import make_dataset
class Model(namedtuple('Model', 'pred label')):
def logits(self):
raw_logits = np.clip(np.log(self... | 2.828125 | 3 |
tests/test_exceptions.py | nesnahnoj/py3-textract | 2 | 10047 | <filename>tests/test_exceptions.py
import unittest
import os
import subprocess
import base
class ExceptionTestCase(base.GenericUtilities, unittest.TestCase):
"""This class contains a bunch of tests to make sure that textract
fails in expected ways.
"""
def test_unsupported_extension_cli(self):
... | 2.953125 | 3 |
dloud_ads/circular_queue.py | dataloudlabs/dloud-ads | 0 | 10048 | <gh_stars>0
"""Queue implementation using circularly linked list for storage."""
class CircularQueue:
"""Queue implementation using circularly linked list for storage."""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next'
... | 3.65625 | 4 |
suplemon/helpers.py | johnmbaughman/suplemon | 0 | 10049 | <reponame>johnmbaughman/suplemon<gh_stars>0
# -*- encoding: utf-8
"""
Various helper constants and functions.
"""
import os
import re
import sys
import time
import traceback
def curr_time():
"""Current time in %H:%M"""
return time.strftime("%H:%M")
def curr_time_sec():
"""Current time in %H:%M:%S"""
... | 2.703125 | 3 |
geofem/emg3d/meshes.py | iisadoramacedo/geofem-master | 0 | 10050 | """
:mod:`meshes` -- Discretization
===============================
Everything related to meshes appropriate for the multigrid solver.
"""
# Copyright 2018-2020 The emg3d Developers.
#
# This file is part of emg3d.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except... | 2.015625 | 2 |
QUICK_START/NODE_SQUEEZESEG_CLUSTER/src/script/squeezeseg/utils/clock.py | Hqss/DINK | 189 | 10051 | <reponame>Hqss/DINK
#! /usr/bin/python2
# -*- coding: utf-8 -*-
"""
Clock function to take running time following Segmatch.
"""
# BSD 3-Clause License
#
# Copyright (c) 2019, FPAI
# Copyright (c) 2019, SeriouslyHAO
# Copyright (c) 2019, xcj2019
# Copyright (c) 2019, Leonfirst
#
# All rights reserved.
#
# Redistribution... | 2.265625 | 2 |
office365/sharepoint/view_collection.py | andebor/Office365-REST-Python-Client | 0 | 10052 | <gh_stars>0
from office365.runtime.client_object_collection import ClientObjectCollection
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office365.sharepoint.view import View
class ViewCollection(ClientObjectCollection):
"""Represents a collection of View resources... | 2.25 | 2 |
common-scrapers/common_src/scrapers/second_extinction.py | mrPaintMan/blog-scraper | 0 | 10053 | from common_src.lib.model.post import Post
from common_src.lib.model.source import Source
from common_src.scrapers.abstract_scraper import make_soup, remove_dups, now
SOURCE_CODE = "second_extinction"
WEBSITE = "https://www.secondextinctiongame.com/news"
ALT_IMAGE = 'https://www.secondextinctiongame.com/static/242486b... | 2.90625 | 3 |
systems/ILSVRC12/AlexNet/alexnet.py | mdatres/quantlab | 7 | 10054 | #
# alexnet.py
#
# Author(s):
# <NAME> <<EMAIL>>
#
# Copyright (c) 2020-2021 ETH Zurich.
#
# 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
# ... | 2.4375 | 2 |
e/mail-relay/web/apps/core/migrations/0012_auto_20151105_1442.py | zhouli121018/nodejsgm | 0 | 10055 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0011_customersetting'),
]
operations = [
migrations.AlterField(
model_name='customersetting'... | 1.375 | 1 |
madlib/main.py | FredericIV/PythonPractice | 0 | 10056 | <filename>madlib/main.py<gh_stars>0
#!/bin/python3
# Libraries
import sys
import array
import textwrap
# Variable Declaration
madlib_selection = "example.txt"
madlib_array = array.array('i')
copy_state = False
user_filler = ""
new_madlib = []
if len(sys.argv) != 1:
print(len(sys.argv))
if sys.argv[1] == "-":... | 3.625 | 4 |
src/tests/control/test_devices.py | bsod85/pretix | 0 | 10057 | import pytest
from django.utils.timezone import now
from pretix.base.models import Device, Event, Organizer, Team, User
from pretix.base.models.devices import generate_api_token
@pytest.fixture
def organizer():
return Organizer.objects.create(name='Dummy', slug='dummy')
@pytest.fixture
def event(organizer):
... | 1.882813 | 2 |
mcp/augmentation/album.py | j20232/moco_image_pipeline | 5 | 10058 | <reponame>j20232/moco_image_pipeline
import numpy as np
from PIL import Image, ImageOps, ImageEnhance
import albumentations as A
# ndarray: H x W x C
def apply_aug(aug, image):
return aug(image=image)["image"]
# ----------------------------------- Blur -------------------------------------------
class RandomBl... | 2.53125 | 3 |
website/util/sanitize.py | bdyetton/prettychart | 0 | 10059 | # -*- coding: utf-8 -*-
import bleach
import json
def strip_html(unclean):
"""Sanitize a string, removing (as opposed to escaping) HTML tags
:param unclean: A string to be stripped of HTML tags
:return: stripped string
:rtype: str
"""
return bleach.clean(unclean, strip=True, tags=[], attribu... | 3.375 | 3 |
mainTrain.py | PolarizedLightFieldMicroscopy/LFMNet2 | 0 | 10060 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.utils import data
from torch import optim
import torchvision.models as models
from torch.autograd import Variable
import torchvision as tv
import random
import math
import time
from datetime i... | 2.34375 | 2 |
tools/utils.py | valsworthen/toxic-comment-classification | 10 | 10061 | <filename>tools/utils.py
"""Utilities"""
import pandas as pd
import numpy as np
from attrdict import AttrDict
import yaml
def average_predictions(cv_predictions, n_splits, num_samples = 153164, num_labels = 6):
"""Average k-fold predictions stored in a dict"""
preds = np.zeros((num_samples, num_labels))
fo... | 2.703125 | 3 |
dags/exercise1.py | mikef-nl/airflow-training-skeleton | 0 | 10062 | <filename>dags/exercise1.py<gh_stars>0
import airflow
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
args = {
'owner': 'Mike',
'start_date': airflow.utils.dates.days_ago(2),
}
dag = DAG(
dag_id='exercise1',
default_args=args,
schedule_interval=None
)
t1 ... | 2.25 | 2 |
pyhelp/scripts/produce_meteo_maps.py | jnsebgosselin/help | 12 | 10063 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 27 10:54:25 2018
@author: jsgosselin
"""
# ---- Standard Library Imports
from itertools import product
import os.path as osp
import os
# ---- Third Party Imports
import netCDF4
from geopandas import GeoDataFrame
import pandas as pd
from shapely.geometr... | 2.265625 | 2 |
platform/core/tests/test_activitylogs/test_service.py | hackerwins/polyaxon | 0 | 10064 | <reponame>hackerwins/polyaxon<filename>platform/core/tests/test_activitylogs/test_service.py
# pylint:disable=ungrouped-imports
import uuid
import pytest
import activitylogs
from db.models.activitylogs import ActivityLog
from events.registry.experiment import EXPERIMENT_DELETED_TRIGGERED
from events.registry.user im... | 1.953125 | 2 |
tests/framework/test_ingress.py | praus/shapy | 54 | 10065 | import unittest
from shapy.framework.tcelements import *
from shapy.framework.executor import run
from tests import TCTestCase
class TestIngress(TCTestCase):
def setUp(self):
self.interface = Interface('lo')
def test_ingress_filter(self):
q = IngressQdisc()
q.add(RedirectFilter('... | 2.203125 | 2 |
software/hippietrap/gradient.py | mayhem/led-chandelier | 2 | 10066 | <reponame>mayhem/led-chandelier<gh_stars>1-10
from colorsys import hsv_to_rgb
from math import fabs, fmod
import os
from hippietrap.color import Color
class Gradient(object):
def __init__(self, palette, num_leds = 1):
# palletes are in format [ (.345, (128, 0, 128)) ]
self._validate_palette(palet... | 2.9375 | 3 |
stix_shifter_modules/elastic/entry_point.py | 6un9-h0-Dan/stix-shifter | 1 | 10067 | from stix_shifter_utils.utils.entry_point_base import EntryPointBase
from stix_shifter_utils.modules.cim.stix_translation.cim_data_mapper import CimDataMapper
from stix_shifter_utils.modules.car.stix_translation.car_data_mapper import CarDataMapper
from .stix_translation.stix_to_elastic import StixToElastic
class Entr... | 1.851563 | 2 |
src/http_pick/pickergui.py | thomaspcole/http-pick | 0 | 10068 | <filename>src/http_pick/pickergui.py
from PyQt5.QtWidgets import (QMainWindow, QToolButton, QWidget, QHBoxLayout)
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore
from math import floor
import sys
class MainWindow(QMainWindow):
def __init__(self, browsers, iconsize=72, displayappname=False, x=0, y=0, callba... | 2.53125 | 3 |
genetic_pwdcrack.py | robotenique/AI-programming | 3 | 10069 | """
Crack a password using a genetic algorithm!
"""
import random as rnd
def main():
"""
This file implements a genetic algorithm to solve the problem of
cracking a given password, by creating 'generations' of different
words, selecting the best, breeeding them, applying a simple crossover
(randomi... | 3.75 | 4 |
openverse_catalog/dags/providers/provider_api_scripts/science_museum.py | yavik-kapadia/openverse-catalog | 25 | 10070 | <reponame>yavik-kapadia/openverse-catalog<filename>openverse_catalog/dags/providers/provider_api_scripts/science_museum.py
import logging
from common.licenses import get_license_info
from common.loader import provider_details as prov
from common.requester import DelayedRequester
from common.storage.image import ImageS... | 2.140625 | 2 |
digitaltape.py | heerdyes/tapegame | 0 | 10071 | <filename>digitaltape.py
# tape variables
TS_MAX=1000
# the digital tape model
class DTape:
def __init__(self,size,alphabet,noopidx=0):
if size>TS_MAX:
self.size=TS_MAX
else:
self.size=size
if len(alphabet)==0:
raise Exception('alphabet has zero symbols')... | 3.109375 | 3 |
webhook-cdk/lambda/vars.py | ncalteen/github-webhook-lambda-example | 0 | 10072 | <reponame>ncalteen/github-webhook-lambda-example
import json
# Output must be returned in the format mentioned below:
# https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format
lambda_response = {
"isBase64Encoded": Fals... | 1.90625 | 2 |
gym_unblockme/envs/unblockme_render.py | fedingo/gym-unblockme | 3 | 10073 | import pygame
import time
import numpy as np
import sys
gray = (150, 150, 150)
white = (255, 255, 255)
black = (0, 0, 0, )
red_block = (255, 0, 0)
red_border = (76, 0, 19)
block_color = (255, 128, 0)
border_color = (165,42,42)
screen = None
SIDE = 50
BORDER = 5
MARGIN = 5
LINE = 1
h_switch = True
def __draw_hor... | 3.0625 | 3 |
scaffolds/__init__.py | chhsiao1981/frontend_template | 0 | 10074 | # API
from pyramid.scaffolds import PyramidTemplate
import os
import re
import logging
def _camelcase_to_upper_camel_case(the_str):
if not the_str:
return ''
return the_str[0].upper() + the_str[1:]
def _upper_camelcase_to_camelcase(the_str):
if not the_str:
return ''
return the_str[... | 2.625 | 3 |
phy/cluster/tests/test_supervisor.py | mikailweston/phy | 0 | 10075 | # -*- coding: utf-8 -*-
"""Test GUI component."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
#from contextlib import contextmanager
from pytest import yield_fixture, fixture, raises
import ... | 1.898438 | 2 |
Source/CommandManager.py | SOBotics/Botpy | 5 | 10076 | <filename>Source/CommandManager.py
#
# CommandManager.py
# Botpy
#
# Created by <NAME> on 4th September 2017.
#
#
import threading
import chatexchange as ce
class CommandManager:
def __init__(self, commands):
self.commands = commands
self.running_commands = []
def run_command(self, command):
... | 2.296875 | 2 |
tests/periodicities/gen_makefile.py | jmabry/pyaf | 377 | 10077 | <reponame>jmabry/pyaf<filename>tests/periodicities/gen_makefile.py
import os
import glob
subdirs = glob.glob("tests/periodicities/*");
subdirs = ['tests/periodicities/Month',
'tests/periodicities/Minute',
'tests/periodicities/Week',
'tests/periodicities/Business_Hour',
'test... | 2.328125 | 2 |
test/test_util_registry.py | SimulatedANeal/carpedm | 2 | 10078 | #
# Copyright (C) 2018 <NAME>.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
#
# Portions of this module are copied or lightly modified from the
# Tensor2Tensor registry_test module, so here is their license:
#
# Copyright 2018 The Tensor2Ten... | 2.125 | 2 |
pay-api/migrations/versions/8f7565cf50c1_.py | stevenc987/sbc-pay | 0 | 10079 | <reponame>stevenc987/sbc-pay
"""empty message
Revision ID: 8f7565cf50c1
Revises: 872760122cc9, <KEY>
Create Date: 2020-10-02 11:11:49.823678
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = ('872760122cc9', '<KEY>')
branch_labels = None
d... | 1.0625 | 1 |
iotronic/wamp/agent.py | smartmeio/stack4things-openstack-iotronic | 1 | 10080 | <reponame>smartmeio/stack4things-openstack-iotronic<filename>iotronic/wamp/agent.py<gh_stars>1-10
# Copyright 2017 MDSLAB - University of Messina
# 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 ob... | 1.828125 | 2 |
src/export_to_poseviz.py | anibali/metro-pose3d | 52 | 10081 | <gh_stars>10-100
#!/usr/bin/env python3
import argparse
import logging
import sys
import numpy as np
import util
def main():
flags = initialize()
logging.debug(f'Loading from {flags.in_path}')
a = np.load(flags.in_path, allow_pickle=True)
all_results_3d = {}
for image_path, coords3d_pred in zip... | 2.234375 | 2 |
xcube/core/gen2/local/helpers.py | bcdev/xcube | 97 | 10082 | # The MIT License (MIT)
# Copyright (c) 2021 by the xcube development team and contributors
#
# 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... | 2.28125 | 2 |
core/log.py | dl-stuff/dl9 | 0 | 10083 | """Simulation logs"""
from __future__ import annotations # default once 3.10
import sys
from enum import Enum
from typing import Type, TYPE_CHECKING
if TYPE_CHECKING:
from core.timeline import Timeline
class LogKind(Enum):
def __str__(self) -> str:
return self.name
DEBUG = 0
SIM = 1
class... | 2.65625 | 3 |
zipline/__init__.py | chalant/pluto | 0 | 10084 | # #
# # Copyright 2015 Quantopian, 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 a copy of the License at
# #
# # http://www.apache.org/licenses/LICENSE-2.0
# #
# # Unless required by applicable la... | 1.570313 | 2 |
smarts/core/utils/traffic_history_service.py | c-h-a-r-l-i-e/SMARTS | 0 | 10085 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. 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
# to us... | 1.804688 | 2 |
src/basics/sql_lite/update_data.py | FoxNeo/MyPythonProjects | 0 | 10086 | <gh_stars>0
import sqlite3
connect = sqlite3.connect("production.db")
cursor = connect.cursor()
cursor.execute("UPDATE PERSON SET edad = 19 WHERE nombre = 'Conker'")
connect.commit()
connect.close()
| 2.703125 | 3 |
calvin/runtime/south/plugins/media/defaultimpl/image.py | josrolgil/exjobbCalvin | 1 | 10087 | <filename>calvin/runtime/south/plugins/media/defaultimpl/image.py
import pygame
from StringIO import StringIO
import cv2
import os
import numpy
class Image(object):
"""
Image object
"""
def __init__(self):
self.display = None
def show_image(self, image, width, height):
"""
... | 2.9375 | 3 |
durin/models.py | mlodic/django-rest-durin | 0 | 10088 | <filename>durin/models.py<gh_stars>0
import binascii
from os import urandom
import humanize
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from durin.settings import durin_settings
from durin.signals import token_... | 2.09375 | 2 |
linter.py | CudaText-addons/cuda_lint_htmltidy | 0 | 10089 | <filename>linter.py
# Copyright (c) 2013 <NAME>
# Change for CudaLint: <NAME>.
# License: MIT
import os
from cuda_lint import Linter, util
if os.name=='nt':
_exe = os.path.join(os.path.dirname(__file__), 'tidy_win32', 'tidy')
else:
_exe = 'tidy'
class HtmlTidy(Linter):
syntax = ('HTML', 'HTML_')
cmd ... | 2.25 | 2 |
PP4E-Examples-1.4/Examples/PP4E/Dstruct/Basic/inter2.py | AngelLiang/PP4E | 0 | 10090 | "set operations for multiple sequences"
def intersect(*args):
res = []
for x in args[0]: # scan the first list
for other in args[1:]: # for all other arguments
if x not in other: break # this item in each one?
else:
res.append(x) #... | 3.59375 | 4 |
airtech_api/utils/error_messages/serialization_errors.py | chidioguejiofor/airtech-api | 1 | 10091 | <reponame>chidioguejiofor/airtech-api<gh_stars>1-10
msg_dict = {
'resource_not_found':
'The resource you specified was not found',
'invalid_gender':
"The gender you specified is invalid!!",
'many_invalid_fields':
'Some errors occured while validating some fields. Please check and try again',
... | 2.578125 | 3 |
blog/be/server/serialization/__init__.py | kamko/lnu_ht19_4ME310_final_project | 0 | 10092 | from .marshmallow import ma
from .schemas import ArticleSchema
__all__ = [
'ma',
'ArticleSchema'
]
| 1.0625 | 1 |
scripts/fast_queue.py | ourresearch/openalex-guts | 48 | 10093 | import argparse
from time import sleep, time
from collections import defaultdict
from sqlalchemy import orm, text, insert, delete
from sqlalchemy.orm import selectinload
import models
from app import db
from app import logger
from scripts.queue import JsonWorks, JsonAuthors, JsonConcepts, JsonInstitutions, JsonVenues... | 2.234375 | 2 |
cogs/memes.py | Code-Cecilia/botman-rewrite | 2 | 10094 | import json
import discord
from discord.ext import commands
from assets import internet_funcs
from assets.list_funcs import chunks
class Memes(commands.Cog, description="Memes from https://imgflip.com/"):
def __init__(self, bot):
self.bot = bot
with open("config.json") as configFile:
... | 2.578125 | 3 |
examples/forest_fire/run.py | fire-suppression-abm/mesa | 1,704 | 10095 | <filename>examples/forest_fire/run.py
from forest_fire.server import server
server.launch()
| 1.109375 | 1 |
scripts/collect_timelines1.py | tedhchen/twitter_timeline_tools | 0 | 10096 | <reponame>tedhchen/twitter_timeline_tools
# Prep
import json, configparser, pickle, csv, logging, os
import pandas as pd
from tweepy import AppAuthHandler, API, Cursor
# Reading in configuation
params = configparser.ConfigParser()
params.read('config.ini')
# Functions
# Takes config file and returns authenticated api... | 2.6875 | 3 |
aquarius/app/auth_util.py | oceanprotocol/provider-backend | 0 | 10097 | <gh_stars>0
#
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
from eth_utils import is_address
from web3 import Web3
def sanitize_addresses(addresses):
return [Web3.toChecksumAddress(a) for a in addresses if is_address(a)]
def compare_eth_addresses(address, checker, logger):
... | 2.921875 | 3 |
oscar/lib/python2.7/site-packages/phonenumbers/data/region_DJ.py | sainjusajan/django-oscar | 0 | 10098 | """Auto-generated file, do not edit by hand. DJ metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_DJ = PhoneMetadata(id='DJ', country_code=253, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[27]\\d{7}', possible_length=(8,)),
... | 2.140625 | 2 |
llvm-7.0.0.src/utils/unicode-case-fold.py | sillywalk/grazz | 171 | 10099 | <filename>llvm-7.0.0.src/utils/unicode-case-fold.py<gh_stars>100-1000
#!/usr/bin/env python
"""
Unicode case folding database conversion utility
Parses the database and generates a C++ function which implements the case
folding algorithm. The database entries are of the form:
<code>; <status>; <mapping>; # <name>
... | 2.890625 | 3 |