code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y =... | AndyLamperski/lemkelcp | lemkelcp/lemkelcp.py | Python | mit | 5,431 |
import xml.etree.ElementTree as ET
import datetime
import sys
import openpyxl
import re
import dateutil
def main():
print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG
print 'Argument List:', str(sys.argv) #DEBUG
Payrate = raw_input("Enter your pay rate: ") #DEBUG
sNumber = raw_input("Enter 900#: ... | JamesPavek/payroll | timesheet.py | Python | mit | 2,615 |
from PySide import QtCore, QtGui
class MakinFrame(QtGui.QFrame):
mousegeser = QtCore.Signal(int,int)
def __init__(self,parent=None):
super(MakinFrame,self).__init__(parent)
self.setMouseTracking(True)
def setMouseTracking(self, flag):
def recursive_set(parent):
for child in parent.findChildren(QtCore.QObj... | imakin/PersonalAssistant | GameBot/src_py/makinreusable/makinframe.py | Python | mit | 610 |
from graphics_module.objects import *
import numpy as np
def make_pixels_array_basic(amount):
return np.full(10,Pixel(), dtype=np.object)
def make_pixels_array_config_based(config):
if config.colorscheme == "b&w":
c = Color()
elif config.colorscheme == "light":
c = Color(r=245,g=235,b=234,... | sindresf/The-Playground | Python/Machine Learning/LSTM Music Visualizer/LSTM Music Visualizer/graphics_module/initialization.py | Python | mit | 576 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Nate Coraor <nate@coraor.org>
#
# This file is part of Ansible
#
# Ansible 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 License... | martenson/ansible-common-roles | paths/library/zfs_permissions.py | Python | mit | 9,934 |
__author__ = 'olga'
import numpy as np
from prettyplotlib.colors import blue_red, blues_r, reds
from prettyplotlib.utils import remove_chartjunk, maybe_get_fig_ax
def pcolormesh(*args, **kwargs):
"""
Use for large datasets
Non-traditional `pcolormesh` kwargs are:
- xticklabels, which will put x tic... | olgabot/prettyplotlib | prettyplotlib/_pcolormesh.py | Python | mit | 4,451 |
"""
To use this, create a settings.py file and make these variables:
TOKEN=<oath token for github>
ORG=<your org in github>
DEST=<Path to download to>
"""
from github import Github
from subprocess import call
import os
from settings import TOKEN, ORG, DEST
def download():
"""Quick and Dirty Download all repos funct... | sqor/3rdeye | fetch_repos.py | Python | mit | 789 |
from distutils.core import setup, Extension
setup(
name = 'iMX233_GPIO',
version = '0.1.0',
author = 'Stefan Mavrodiev',
author_email = 'support@olimex.com',
url = 'https://www.olimex.com/',
license = 'MIT',
descrip... | mikevoyt/iMX233_GPIO | setup.py | Python | mit | 1,271 |
from flask import Blueprint
from flask import current_app
from flask import request
from flask import jsonify
from flask import abort
from flask import render_template
from flask import redirect
from flask import url_for
from flask import flash
from werkzeug.exceptions import NotFound
from printus.web.models import Re... | matrixise/printus | old_code/printus/web/views/general/__init__.py | Python | mit | 2,782 |
"""
commswave
=========
Takes device communications up and down according to a timefunction.
Comms will be working whenever the timefunction returns non-zero.
Configurable parameters::
{
"timefunction" : A timefunction definition
"threshold" : (optional) Comms will only work when the timefunction ... | DevicePilot/synth | synth/devices/commswave.py | Python | mit | 3,252 |
from setuptools import setup, find_packages
with open('requirements.txt') as reqs:
inst_reqs = reqs.read().split('\n')
setup(
name='autobot',
version='0.1.0',
packages=find_packages(),
author='Mikael Knutsson',
author_email='mikael.knutsson@gmail.com',
description='A bot framework made acc... | mikn/autobot | setup.py | Python | mit | 648 |
"""File related wrapper functions to streamline common use cases"""
import manage as manage
from manage import find_file, find_file_re, list_dir
import operation as operation
from operation import hash_file, read_file, slice_file, write_file
| qevo/py_file_helper | file_helper/__init__.py | Python | mit | 243 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""test_03b_subcmd_primer3.py
Test primer3 subcommand for pdp script. These tests require primer3 v2+.
This test suite is intended to be run from the repository root using:
pytest -v
(c) The James Hutton Institute 2017-2019
Author: Leighton Pritchard
Contact:
leighton... | widdowquinn/find_differential_primers | tests/test_03b_subcmd_primer3.py | Python | mit | 8,352 |
import os
def run(name='test1.py'):
filename = os.getcwd() + name
exec(compile(open(filename).read(), filename, 'exec'))
| karljakoblarsson/Rattan-Geometry | Utils.py | Python | mit | 130 |
# Copyright (C) 2010 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 ... | lordmos/blink | Tools/Scripts/webkitpy/layout_tests/port/test.py | Python | mit | 29,134 |
from jupyter_workflow.data import get_fremont_data
import pandas as pd
def test_fremont_data():
data = get_fremont_data()
assert all(data.columns == ['West','East','Total'])
assert isinstance(data.index,pd.DatetimeIndex)
| irenalanc/JupyterPythonPals | jupyter_workflow/tests/test_data.py | Python | mit | 234 |
#Unused
def fail():
for t in [TypeA, TypeB]:
x = TypeA()
run_test(x)
#OK by name
def OK1(seq):
for _ in seq:
do_something()
print("Hi")
#OK counting
def OK2(seq):
i = 3
for x in seq:
i += 1
return i
#OK check emptiness
def OK3(seq):
for thing in seq:
... | github/codeql | python/ql/test/query-tests/Variables/unused/test.py | Python | mit | 2,148 |
from __future__ import division
import random
import matrix
from tile import Tile
class Island(object):
def __init__(self, width=300, height=300):
self.radius = None
self.shore_noise = None
self.rect_shore = None
self.shore_lines = None
self.peak = None
self.spoke... | supermitch/Island-Gen | island.py | Python | mit | 4,697 |
from __future__ import absolute_import, unicode_literals
from builtins import str
import os
import pytest
import io
from glob import glob
from psd_tools import PSDImage
from psd2svg import psd2svg
FIXTURES = [
p for p in glob(
os.path.join(os.path.dirname(__file__), 'fixtures', '*.psd'))
]
@pytest.ma... | kyamagu/psd2svg | tests/test_convert.py | Python | mit | 1,077 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_02_01/operations/_express_route_connections_operations.py | Python | mit | 22,003 |
# -*- coding: utf-8 -*-
import unittest
from pyparsing import ParseException
from tests.utils.grammar import get_record_grammar
"""
CWR Non-Roman Alphabet Agreement Party Name grammar tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
... | weso/CWR-DataApi | tests/grammar/factory/record/test_npa.py | Python | mit | 4,113 |
# -*- coding:utf-8 -*-
from collections import defaultdict
import numpy
class ThompsonAgent:
def __init__(self, seed=None):
self._succeeds = defaultdict(int)
self._fails = defaultdict(int)
self._np_random = numpy.random.RandomState(seed)
def choose(self, arms, features=None):
... | ohtaman/pynm | pynm/reinforce/bandit/thompson.py | Python | mit | 683 |
"""Sensitive variant calling using VarDict.
Defaults to using the faster, equally sensitive Java port:
https://github.com/AstraZeneca-NGS/VarDictJava
if 'vardict' or 'vardict-java' is specified in the configuration. To use the
VarDict perl version:
https://github.com/AstraZeneca-NGS/VarDict
specify 'vardict-perl'.... | lpantano/bcbio-nextgen | bcbio/variation/vardict.py | Python | mit | 15,244 |
"""add account id
Revision ID: 3734300868bc
Revises: 3772e5bcb34d
Create Date: 2013-09-30 18:07:21.729288
"""
# revision identifiers, used by Alembic.
revision = '3734300868bc'
down_revision = '3772e5bcb34d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('account_profile', sa.Colu... | vsilent/smarty-bot | alembic/versions/3734300868bc_add_account_id.py | Python | mit | 391 |
pkg_dnf = {
'collectd': {},
'collectd-chrony': {},
'collectd-curl': {},
'collectd-curl_json': {},
'collectd-curl_xml': {},
'collectd-netlink': {},
'rrdtool': {},
}
if node.os == 'fedora' and node.os_version >= (26):
pkg_dnf['collectd-disk'] = {}
svc_systemd = {
'collectd': {
... | rullmann/bundlewrap-collectd | items.py | Python | mit | 5,646 |
import tkinter as tk
from time import sleep
from playsound import playsound
import config
import fasttick
from helpmessage import fasttick_help_message
import misc
from tickerwindow import TickerWindow
class GUIfasttick(TickerWindow):
def __init__(self, app):
super().__init__(app)
misc.delete_anci... | JevinJ/Bittrex-Notify | src/GUIfasttick.py | Python | mit | 3,213 |
import os
import sys
root_path = os.path.abspath("../../../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
import tensorflow as tf
from _Dist.NeuralNetworks.Base import Generator4d
from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d
from _Dist.NeuralNetworks.NNUtil import Activations... | carefree0910/MachineLearning | _Dist/NeuralNetworks/i_CNN/CNN.py | Python | mit | 3,860 |
import re
import functools
from slackbot.bot import respond_to
from app.modules.shogi_input import ShogiInput, UserDifferentException, KomaCannotMoveException
from app.modules.shogi_output import ShogiOutput
from app.slack_utils.user import User
from app.helper import channel_info, should_exist_shogi
@respond_to('... | setokinto/slack-shogi | app/shogi.py | Python | mit | 4,557 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import collections
import os
import re
import torch
from fairseq.file_io import PathManager
def aver... | pytorch/fairseq | scripts/average_checkpoints.py | Python | mit | 6,075 |
# input lib
from pygame.locals import *
import pygame, string
class ConfigError(KeyError): pass
class Config:
""" A utility for configuration """
def __init__(self, options, *look_for):
assertions = []
for key in look_for:
if key[0] in options.keys(): exec('self.'+key[0]... | antismap/MICshooter | sources/lib/eztext.py | Python | mit | 11,212 |
# -*- coding:utf-8 -*-
from setuptools import setup
setup(
name = "mobileclick",
description = "mobileclick provides baseline methods and utility scripts for the NTCIR-12 MobileClick-2 task",
author = "Makoto P. Kato",
author_email = "kato@dl.kuis.kyoto-u.ac.jp",
license = "MIT Lice... | mpkato/mobileclick | setup.py | Python | mit | 1,565 |
'''
charlie.py
---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi
Relies upon RPi.GPIO written by Ben Croston
The MIT License (MIT)
Copyright (c) 2016 Amanda Cole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati... | mandyRae/pythonic-charlieplex | charlie.py | Python | mit | 5,714 |
# vi: ts=8 sts=4 sw=4 et
#
# robot.py: web robot detection
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the Draco2 a... | geertj/draco2 | draco2/draco/robot.py | Python | mit | 2,805 |
from django.conf.urls import patterns, url
from rai00base.raccordement import getModeleRaccordement, createRaccordement, deleteRaccordement, listRaccordement
urlpatterns = patterns('',
url('getModeleRaccordement/$', getModeleRaccordement),
url('createRaccordement/$', createRaccordement),
url('deleteRaccord... | DarioGT/docker-carra | src/rai00base/urls.py | Python | mit | 401 |
value_None = object()
class FactoryException(Exception):
pass
class Factory:
class Item:
def __init__(self, factory, i):
self.factory = factory
self.i = i
@property
def value(self):
return self.factory.value(self.i)
@value.setter
... | bigblindbais/pytk | src/pytk/factory/factory.py | Python | mit | 1,952 |
import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
#notice what i did, since it is an object
df['H-L'] = df.High - df.Low
print df.head()
df['100MA'] = pd.rolling_mean(df['Close'], 100)
# must do a slice, since there will be no value for 100... | PythonProgramming/Pandas-Basics-with-2.7 | pandas 5 - Column Operations (Basic mathematics, moving averages).py | Python | mit | 416 |
import numpy as np
from nlpaug.augmenter.spectrogram import SpectrogramAugmenter
from nlpaug.util import Action
import nlpaug.model.spectrogram as nms
class LoudnessAug(SpectrogramAugmenter):
"""
Augmenter that change loudness on mel spectrogram by random values.
:param tuple zone: Default value is (0.2... | makcedward/nlpaug | nlpaug/augmenter/spectrogram/loudness.py | Python | mit | 1,919 |
"""
HLS and Color Threshold
-----------------------
You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore
this a bit further and look at a couple examples to see why a color space like HLS can be more robust.
"""
import numpy as np
import cv2
import matplot... | akshaybabloo/Car-ND | Term_1/advanced_lane_finding_10/color_space_10_8.py | Python | mit | 2,835 |
#!/usr/bin/python
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import time
import argparse
from datetime import datetime, timedelta, tzinfo
from textwrap import dedent
import json
from random import choice
import webbrowser
import itertools
import log... | bendemott/solr-zkutil | solrzkutil/__init__.py | Python | mit | 38,530 |
import cv2
import numpy as np
import sys
def reshapeImg(img, l, w, p):
# reshape image to (l, w) and add/remove pixels as needed
while len(img) % p != 0:
img = np.append(img, 255)
olds = img.size / p
news = l*w
if news < olds:
img = img[:p*news]
elif news > olds:
img = np.concatenate( (img, np.zeros(p*(ne... | andykais/painting-base2 | examples/create-image2.py | Python | mit | 839 |
import numpy
import pandas
import statsmodels.api as sm
'''
In this exercise, we will perform some rudimentary practices similar to those of
an actual data scientist.
Part of a data scientist's job is to use her or his intuition and insight to
write algorithms and heuristics. A data... | rmhyman/DataScience | Lesson1/titanic_data_heuristic1.py | Python | mit | 2,937 |
# -*- coding: utf-8 -*-
"""
Translator module that uses the Google Translate API.
Adapted from Terry Yin's google-translate-python.
Language detection added by Steven Loria.
"""
from __future__ import absolute_import
import json
import re
import codecs
from textblob.compat import PY2, request, urlencode
from textblob.... | nvoron23/TextBlob | textblob/translate.py | Python | mit | 2,924 |
'''
These classes specify the attributes
that a view object can have when editing views
'''
__author__ = 'William Emfinger'
__copyright__ = 'Copyright 2016, ROSMOD'
__credits__ = ['William Emfinger', 'Pranav Srinivas Kumar']
__license__ = 'GPL'
__version__ = '0.4'
__maintainer__ = 'William Emfinger'
__email__ = 'emfin... | finger563/editor | src/view_attributes.py | Python | mit | 3,890 |
#! /usr/bin/env python3
import vk
import sys
import json
# get access token
#app_id = 4360605
#url = "http://api.vkontakte.ru/oauth/authorize?client_id=" + str(app_id) + "&scope=4&redirect_uri=http://api.vk.com/blank.html&display=page&response_type=token"
#webbrowser.open_new_tab(url)
#exit()
word = sys.argv[1]
txt... | dm-urievich/learn_vk_api | test_api.py | Python | mit | 849 |
#HV Control &
#Read and Plot from the PMT
#This code is to record the data that is received into the Teensy's ADC.
#Includes the HV control and replotting the results at the end.
#See CSV Dataplot notebook to plot old experiment data.
from __future__ import division
from __future__ import print_function
from pyqtgr... | gregnordin/micropython_pyboard | 150729_pyboard_to_pyqtgraph/serial_pyboard_to_python.py | Python | mit | 9,779 |
import re
list_re = re.compile(r'\((.*)\) \"(.*)\" \"(.*)\"')
class Response(object):
# There are three possible server completion responses
OK = "OK" # indicates success
NO = "NO" # indicates failure
BAD = "BAD" # indicates a protocol error
class ListResponse(object):
def __init__(self, li... | clara-labs/imaplib3 | imaplib3/response.py | Python | mit | 513 |
#!/usr/bin/env python
import argparse
import bz2
import gzip
import os.path
import sys
from csvkit import CSVKitReader
from csvkit.exceptions import ColumnIdentifierError, RequiredHeaderError
def lazy_opener(fn):
def wrapped(self, *args, **kwargs):
self._lazy_open()
fn(*args, **kwargs)
return... | cypreess/csvkit | csvkit/cli.py | Python | mit | 15,243 |
#
#
#March 2014
#Adam Breznicky - TxDOT TPP - Mapping Group
#
#This is an independent script which requires a single parameter designating a directory.
#The script will walk through each subfolder and file within the designated directory, identifying the MXD files
#and re-sourcing the Comanche database connections to ... | TxDOT/python | standalone/AdminPrefix_Resourcer_v1.py | Python | mit | 3,702 |
# -*- coding: utf-8 -*-
import sys
import time
from subprocess import call
#add the project folder to pythpath
sys.path.append('../../')
from library.components.SensorModule import SensorModule as Sensor
from library.components.MetaData import MetaData as MetaData
class Raspistill(Sensor):
def __init__(self):
... | OpenSpaceProgram/pyOSP | library/sensors/Raspistill.py | Python | mit | 2,060 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/connection_monitor_parameters.py | Python | mit | 2,077 |
# https://projecteuler.net/problem=81
from projecteuler.FileReader import file_to_2D_array_of_ints
# this problem uses a similar solution to problem 18, "Maximum Path Sum 1."
# this problem uses a diamond instead of a pyramid
matrix = file_to_2D_array_of_ints("p081.txt", ",")
y_max = len(matrix) - 1
x_max = len(matri... | Peter-Lavigne/Project-Euler | p081.py | Python | mit | 699 |
import unittest
from hamlpy.parser.core import (
ParseException,
Stream,
peek_indentation,
read_line,
read_number,
read_quoted_string,
read_symbol,
read_whitespace,
read_word,
)
from hamlpy.parser.utils import html_escape
class ParserTest(unittest.TestCase):
def test_read_whit... | nyaruka/django-hamlpy | hamlpy/test/test_parser.py | Python | mit | 4,020 |
#! /usr/bin/env python
# Copyright (c) 2019 Red Hat, Inc.
# Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# 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 w... | metacloud/molecule | setup.py | Python | mit | 12,584 |
from django.contrib import admin
from xbee_module.models import xbee_module
# Register your models here.
admin.site.register(xbee_module); | EricJones89/SmartHome | SmartHome/xbee_module/admin.py | Python | mit | 139 |
def represents_int(value):
try:
int(value)
return True
except ValueError:
return False
def bytes_to_gib(byte_value, round_digits=2):
return round(byte_value / 1024 / 1024 / float(1024), round_digits)
def count_to_millions(count_value, round_digits=3):
return round(count... | skomendera/PyMyTools | providers/value.py | Python | mit | 359 |
import mmap
import os.path
import re
from collections import OrderedDict
from .base_handler import BaseHandler
from .iso9660 import ISO9660Handler
from utils import MmappedFile, ConcatenatedFile
class GDIParseError(ValueError):
pass
class GDIHandler(BaseHandler):
def test(self):
if not re.match('^.*... | drx/rom-info | handlers/dreamcast.py | Python | mit | 4,779 |
frame_len = .1
keys = {
'DOWN': 0x42,
'LEFT': 0x44,
'RIGHT': 0x43,
'UP': 0x41,
'Q': 0x71,
'ENTER': 0x0a,
}
apple_domain = 1000
food_values = {
'apple': 3,
}
game_sizes = {
's': (25, 20),
'm': (50, 40),
'l': (80, 40),
}
initial_size = 4
| tancredi/python-console-snake | snake/config.py | Python | mit | 282 |
from distutils.core import setup
import sslserver
setup(name="django-sslserver",
version=sslserver.__version__,
author="Ted Dziuba",
author_email="tjdziuba@gmail.com",
description="An SSL-enabled development server for Django",
url="https://github.com/teddziuba/django-sslserver",
pa... | mapennell/django-sslserver | setup.py | Python | mit | 759 |
"""
Dump Mapper
This script acts as a map/function over the pages in a set of MediaWiki
database dump files. This script allows the algorithm for processing a set of
pages to be spread across the available processor cores of a system for faster
analysis.
This script can also be imported as a module to expose the ... | maribelacosta/wikiwho | wmf/dump/map.py | Python | mit | 7,155 |
from __future__ import absolute_import
from __future__ import unicode_literals
import collections
import jsonschema
DEFAULT_GENERATE_CONFIG_FILENAME = 'generate_config.yaml'
GENERATE_OPTIONS_SCHEMA = {
'type': 'object',
'required': ['repo', 'database'],
'properties': {
'skip_default_metrics': ... | ucarion/git-code-debt | git_code_debt/generate_config.py | Python | mit | 1,667 |
"""
@file
@brief Buffer as a logging function.
"""
from io import StringIO
class BufferedPrint:
"""
Buffered display. Relies on :epkg:`*py:io:StringIO`.
Use it as follows:
.. runpython::
:showcode:
def do_something(fLOG=None):
if fLOG:
fLOG("Did something.... | sdpython/pyquickhelper | src/pyquickhelper/loghelper/buffered_flog.py | Python | mit | 844 |
from django.contrib import admin
from bananas.apps.appointment.forms import AppointmentForm
from bananas.apps.appointment.models import Appointment
from bananas.apps.appointment.models import AppointmentType
@admin.register(Appointment)
class AppointmentAdmin(admin.ModelAdmin):
list_display = (
'time',
... | tmcdonnell87/bananas | bananas/apps/appointment/admin.py | Python | mit | 1,876 |
# -*- coding: utf-8 -*-
import datetime
import os
#compsiteとcommandをあわせたような形
#ContextがhandlerでCommandが処理
class JobCommand(object):
def execute(self, context):
if context.getCurrentCommand() != 'begin':
raise Exception('illegal command ' + str(context.getCurrentCommand()))
command_list... | t10471/python | practice/src/design_pattern/Interpreter.py | Python | mit | 2,299 |
from copy import copy
import silk.utils.six as six
from silk.singleton import Singleton
def default_permissions(user):
if user:
return user.is_staff
return False
class SilkyConfig(six.with_metaclass(Singleton, object)):
defaults = {
'SILKY_DYNAMIC_PROFILING': [],
'SILKY_IGNORE_... | Alkalit/silk | silk/config.py | Python | mit | 1,268 |
# -*- coding: utf-8 -*-
import django_dynamic_fixture as fixture
from unittest import mock
from django import urls
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.auth.models import User
from django.test import TestCase
from readthedocs.core.models import UserProfile
from readthedocs.... | rtfd/readthedocs.org | readthedocs/rtd_tests/tests/projects/test_admin_actions.py | Python | mit | 2,812 |
class Base(object):
def meth(self):
pass
class Derived1(Base):
def meth(self):
return super().meth()
class Derived2(Derived1):
def meth(self):
return super().meth()
class Derived3(Derived1):
pass
class Derived4(Derived3, Derived2):
def meth(self):
return super... | github/codeql | python/ql/test/3/library-tests/PointsTo/inheritance/test.py | Python | mit | 496 |
# -*- coding: utf-8 -*-
import sys
def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
... | DawudH/scrapy_real-estate | plot/print_progressbar.py | Python | mit | 1,262 |
import os
from conan.tools.files.files import save_toolchain_args
from conan.tools.gnu import Autotools
from conans.test.utils.mocks import ConanFileMock
from conans.test.utils.test_files import temp_folder
def test_source_folder_works():
folder = temp_folder()
os.chdir(folder)
save_toolchain_args({
... | conan-io/conan | conans/test/unittests/tools/gnu/autotools_test.py | Python | mit | 857 |
# -*- coding: utf-8 -*-
import sys
def diff(a,b):
return compareTree(a, b)
def getType(a):
if isinstance(a, dict):
return 'object'
elif isinstance(a, list):
return 'array'
elif isinstance(a, str):
return 'string'
elif isinstance(a, int):
return 'number'
elif isi... | syuhei176/json-mergepy | jsonutil.py | Python | mit | 3,813 |
#!/usr/bin/env python3
# Copyright (c) 2016 The PlanBcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test segwit transactions and blocks on P2P network."""
from test_framework.mininode import *
from test_framewo... | planbcoin/planbcoin | test/functional/p2p-segwit.py | Python | mit | 90,174 |
# -*- coding: utf-8 -*-
"""
Decorators module
"""
import logging
from docktors.core import decorated
from docktors.wdocker import DockerContainer
logger = logging.getLogger(__name__)
def docker(func=None, **kwargs):
"""
Decorator to startup and shutdown a docker container.
:param image: The name of the ... | Patouche/pydocktors | docktors/decorators.py | Python | mit | 1,226 |
import json
class JSONRenderer(object):
def render(self, data):
return json.dumps(data)
| Quantify-world/apification | src/apification/renderers.py | Python | mit | 101 |
from django.apps import AppConfig
class MemosConfig(AppConfig):
name = 'memos'
| a-kirin/Dockerfiles | sample01/web/sample01/memos/apps.py | Python | mit | 85 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj... | jpvantuyl/python_koans | python2/koans/about_method_bindings.py | Python | mit | 2,996 |
#
# (c) Simon Marlow 2002
#
import sys
import os
import string
import getopt
import platform
import time
import re
from testutil import *
from testglobals import *
# Readline sometimes spews out ANSI escapes for some values of TERM,
# which result in test failures. Thus set TERM to a nice, simple, safe
# value.
os.... | iliastsi/gac | testsuite/driver/runtests.py | Python | mit | 8,165 |
"""
These settings are used by the ``manage.py`` command.
With normal tests we want to use the fastest possible way which is an
in-memory sqlite database but if you want to create South migrations you
need a persistant database.
Unfortunately there seems to be an issue with either South or syncdb so that
defining two... | bitmazk/cmsplugin-redirect | cmsplugin_redirect/tests/south_settings.py | Python | mit | 586 |
import re
from .base import EventBuilder
from .._misc import utils
from .. import _tl
from ..types import _custom
class NewMessage(EventBuilder, _custom.Message):
"""
Represents the event of a new message. This event can be treated
to all effects as a `Message <telethon.tl.custom.message.Message>`,
s... | LonamiWebs/Telethon | telethon/_events/newmessage.py | Python | mit | 4,114 |
from __future__ import unicode_literals
import django
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, Client
from django.test.client import RequestFactory
from django.test.utils import override... | quamilek/django-custard | custard/tests/test.py | Python | mit | 13,067 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""zigzi, Platform independent binary instrumentation module.
Copyright (c) 2016-2017 hanbum park <kese111@gmail.com>
All rights reserved.
For detailed copyright information see the file COPYING in the root of the
distribution archive.
"""
import argparse
from PEInstrume... | ParkHanbum/zigzi | __init__.py | Python | mit | 4,427 |
# -*- coding: utf-8 -*-
"""
Clement Michard (c) 2015
"""
import os
import sys
import nltk
from emotion import Emotion
from nltk.corpus import WordNetCorpusReader
import xml.etree.ElementTree as ET
class WNAffect:
"""WordNet-Affect ressource."""
def __init__(self, wordnet16_dir, wn_domains_dir):
"... | Arnukk/TDS | wnaffect.py | Python | mit | 3,540 |
#!/usr/bin/env python
import cv2
import cv2.cv as cv
class Display:
def setup(self, fullscreen):
cv2.namedWindow('proj_0', cv2.WINDOW_OPENGL)
if fullscreen:
cv2.setWindowProperty('proj_0', cv2.WND_PROP_FULLSCREEN, cv.CV_WINDOW_FULLSCREEN)
def draw(self, image):
... | light-swarm/lightswarm_render | scripts/display.py | Python | mit | 385 |
from typing import Iterable, Callable, Optional, Any, List, Iterator
from dupescan.fs._fileentry import FileEntry
from dupescan.fs._root import Root
from dupescan.types import AnyPath
FSPredicate = Callable[[FileEntry], bool]
ErrorHandler = Callable[[EnvironmentError], Any]
def catch_filter(inner_filter: FSPredicat... | yellcorp/dupescan | dupescan/fs/_walker.py | Python | mit | 4,089 |
#!/usr/bin/env python
import sys
import os
import subprocess
import shutil
import fix_rocks_network
import json
pxelinux_kernels_dir='/tftpboot/pxelinux/';
centos7_templates_dir='./centos7_ks'
centos7_dir='/export/rocks/install/centos7/';
centos7_ks_scripts_dir=centos7_dir+'/scripts/';
centos7_pxeboot_dir=centos7_dir... | kgururaj/rocks-centos7 | setup_for_centos7.py | Python | mit | 4,371 |
# -*- coding: utf-8 -*-
import logging
from . import constants
logger = logging.getLogger(constants.NAME)
| dantezhu/yunbk | yunbk/log.py | Python | mit | 109 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Prints a summary of the contents of the IPHAS source catalogue.
"""
import os
from astropy.io import fits
from astropy import log
import numpy as np
import sys
from dr2 import constants
n_sources = 0
n_r20 = 0
n_reliable = 0
n_deblend = 0
n_reliable_deblend = 0
n_pair =... | barentsen/iphas-dr2 | scripts/summary.py | Python | mit | 1,682 |
# TODO implement a smoothing function perhaps
# (Ie only accept frames within x distance of previous frame) | swirlingsand/self-driving-car-nanodegree-nd013 | p4-CarND-Advanced-Lane-Lines/methods/laneDetection/qualityControl.py | Python | mit | 109 |
"""
WSGI config for asteria project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... | tunegoon/asteria | asteria/wsgi.py | Python | mit | 1,136 |
from copy import copy
import sys
from textwrap import dedent
import warnings
import logging
import numpy
from six.moves import xrange
import theano
from theano.compat import izip
from six import integer_types
from theano.gradient import DisconnectedType
from theano import gof
from theano.gof import Apply, Constant, h... | nke001/attention-lvcsr | libs/Theano/theano/tensor/subtensor.py | Python | mit | 84,816 |
__all__ = ["melfilterbank", "windowing", "spectrogram", "resample"]
import melfilterbank
import windowing
import spectrogram
import resample | twerkmeister/iLID | preprocessing/audio/__init__.py | Python | mit | 141 |
from models.team import Team
from models.tournament import Tournament
from models.tree import ProbableTournamentTree
import unittest
import pdb
class TestTeam(unittest.TestCase):
def setUp(self):
self.tournament = Tournament()
self.teams = self.tournament.teams
self.usa = Team.get_for_coun... | steinbachr/world-cup-challenge | tests/test_models.py | Python | mit | 3,657 |
import pytest
from click.testing import CliRunner
from parkour import cli
import md5
def file_checksums_equal(file1, file2):
with open(file1) as f:
checksum1 = md5.new(f.read()).digest()
with open(file2) as f:
checksum2 = md5.new(f.read()).digest()
return checksum1==checksum2
def test_t... | buenrostrolab/proatac | tests/test_cli.py | Python | mit | 575 |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def CMC():
return 'Welcome to the Container Master Class by Cerulean Canvas'
if __name__ == '__main__':
app.run(host='0.0.0.0')
| tarsoqueiroz/Docker | Study/Oreilly Kubernetes and Docker/s2d9/app.py | Python | mit | 198 |
from flask import (Flask, session, render_template, request, redirect,
url_for, make_response, Blueprint, current_app)
import requests
import json
from datetime import datetime, timedelta
from flask.ext.cors import CORS, cross_origin
bp = Blueprint('audioTag', __name__)
def create_app(blueprint=bp... | janastu/audio-tagger | servers/audioApp.py | Python | mit | 3,589 |
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
number = 0
for i in range(len(s)):
number = number * 26 + ord(s[i]) - ord('A') + 1
return number
| FeiZhan/Algo-Collection | answers/leetcode/Excel Sheet Column Number/Excel Sheet Column Number.py | Python | mit | 255 |
import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
e... | lucas2109/estruturaDados | pilha.py | Python | mit | 1,546 |
# -*- coding: utf-8 -*-
import unittest
import mock
class DynamicFieldsMixinTestCase(unittest.TestCase):
"""Test functionality of the DynamicFieldsMixin class."""
def test_restrict_dynamic_fields(self):
| chewse/djangorestframework-dynamic-fields | test_dynamicfields.py | Python | mit | 218 |
#####################################################
#
# A library for getting match information for a given team at a given event
# out of the Blue Alliance API
#
# Authors: Andrew Merrill and Jacob Bendicksen (Fall 2014)
#
# Requires the blueapi.py library
######################################################
#thi... | jacobbendicksen/BlueAPI | matchinfo.py | Python | mit | 4,831 |
"""
WSGI config for gevsckio project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gevsckio.settings")
from django.core... | arthuralvim/django-gevsckio-example | gevsckio/wsgi.py | Python | mit | 391 |
# -*- coding: utf-8 -*-
u'''\
:mod:`ecoxipy.pyxom` - Pythonic XML Object Model (PyXOM)
========================================================
This module implements the *Pythonic XML Object Model* (PyXOM) for the
representation of XML structures. To conveniently create PyXOM data structures
use :mod:`ecoxipy.pyxom.o... | IvIePhisto/ECoXiPy | ecoxipy/pyxom/__init__.py | Python | mit | 21,834 |
from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, type, **kwargs):
self.type = type
self.properties = kwargs
class Observer:
def update(self):
raise NotImplementedError("Not implemented"... | fmca/ctxpy | ctx/toolkit.py | Python | mit | 2,280 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.