repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
rohitranjan1991/home-assistant | homeassistant/components/homekit_controller/lock.py | """Support for HomeKit Controller locks."""
from __future__ import annotations
from typing import Any
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import Service, ServicesTypes
from homeassistant.components.lock import STATE_JAMMED, LockEntity
from homeassistant.co... |
UQ-UQx/PerspectivesX | perspectivesx_project/django_auth_lti/tests/test_verification.py | from unittest import TestCase
from mock import MagicMock
from django_auth_lti.verification import is_allowed
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
class TestVerification(TestCase):
def test_is_allowed_config_failure(self):
request = MagicMock(LTI={})
allowed... |
cgrima/subradar | subradar/Classdef.py | """Various Python classes"""
__author__ = 'Cyril Grima'
import numpy as np
from . import roughness, surface, utils
NAN = float('nan')
class Signal(object):
"""Signal relationships"""
def __init__(self, wf=NAN, bw=NAN, th=0., bmw=NAN, h=NAN, **kwargs):
self.wf = wf # Signal central frequency [Hz]
... |
dorvaljulien/StarFiddle | anim_plot.py | import time
import numpy as np
import cPickle as pk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.widgets import Button
class PlotAnimation:
"""
Takes a list of PySnap and launch an intera... |
olemb/mido | mido/messages/strings.py | from .specs import SPEC_BY_TYPE, make_msgdict
def msg2str(msg, include_time=True):
type_ = msg['type']
spec = SPEC_BY_TYPE[type_]
words = [type_]
for name in spec['value_names']:
value = msg[name]
if name == 'data':
value = '({})'.format(','.join(str(byte) for byte in va... |
tlake/advent-of-code | 2016/day04_security_through_obscurity/python/src/part1.py | #!/usr/bin/env python
"""Docstring."""
from collections import Counter
from functools import reduce
from common import (
get_input,
)
class RoomAnalyzer:
"""."""
def __init__(self, input_list=[]):
"""."""
self.input_list = input_list
def process_room_string(self, room_string):
... |
croxis/kmr | config.py | __author__ = 'croxis'
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'stuff lumps pumps in pajamas'
CSRF_ENABLED = True
OPENID_PROVIDERS = [
{'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id'},
{'name... |
cruor99/KivyMD | kivymd/spinner.py | # -*- coding: utf-8 -*-
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ListProperty, BooleanProperty
from kivy.animation import Animation
from kivymd.theming import ThemableBehavior
Builder.load_string('''
<MDSpinner>:
canvas.before:
PushMatri... |
drougge/wellpapp-pyclient | wellpapp/shell/fusefs.py | from __future__ import print_function
import fuse
import stat
import errno
import os
import sys
from wellpapp import Client, Tag, raw_exts
import re
from time import time, sleep
from hashlib import md5
from struct import pack, unpack
from zlib import crc32
from xml.sax.saxutils import escape as xmlescape
from os.path ... |
tgquintela/pyDataProcesser | pyDataProcesser/aux_functions.py |
"""
Auxiliar functions
------------------
Collection of main auxiliar functions.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import unicodedata
########################### Administrative functions ##########################
#############################################... |
aschleg/mathpy | mathpy/numerical/tests/test_roots.py | import numpy as np
import pytest
from mathpy.numerical.roots import newtonraph, bisection, secant
class TestRoots:
@staticmethod
def _test_func1(x):
return x ** 2 - 10
@staticmethod
def _test_func2(x):
return x ** 3 - 2 * x - 5
@staticmethod
def _test_func3(x... |
skyfielders/python-skyfield | skyfield/framelib.py | # -*- coding: utf-8 -*-
"""Raw transforms between coordinate frames, as NumPy matrices."""
from numpy import array
from .constants import ANGVEL, ASEC2RAD, DAY_S, tau
from .data.spice import inertial_frames as _inertial_frames
from .functions import mxm, rot_x, rot_z
def build_matrix():
# 'xi0', 'eta0', and 'da0'... |
pythonprobr/notmagic | pt-br/baralho_mut.py | #!/usr/bin/env python3
"""
>>> baralho = Baralho()
>>> len(baralho)
52
>>> baralho[0]
Carta(valor='2', naipe='paus')
>>> baralho[-1]
Carta(valor='A', naipe='espadas')
>>> from random import choice
>>> choice(baralho) #doctest:+SKIP
Carta(valor='4', naipe='paus')
... |
hardingnj/xpclr | setup.py | from setuptools import setup
from ast import literal_eval
def get_version(source='xpclr/__init__.py'):
with open(source) as sf:
for line in sf:
if line.startswith('__version__'):
return literal_eval(line.split('=')[-1].lstrip())
raise ValueError("__version__ not found")
VE... |
hnb2/flask-customers | tests/test_customers.py | '''
To run these tests you need to create a test database, instructions
are inside the README.md
'''
import customers
from customers.utils import db
import unittest
import json
import base64
class CustomersTestCase(unittest.TestCase):
'''
Test the customers application
'''
EMAIL = 'test@test.org'
... |
ktarrant/options_csv | journal/trades/migrations/0001_initial.py | # Generated by Django 2.1 on 2018-08-28 05:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Leg',
fields=[
('id', models.AutoField(auto_c... |
fopina/django-holidays | holidays/tests.py | from django.test import TestCase
from .utils import is_holiday
from datetime import date, timedelta
class HolidaysTests(TestCase):
longMessage = True
fixtures = ['demo']
def fullYearTest(self, group, year, holidays):
it = date(year, 1, 1)
end = date(year, 12, 31)
delta = timedelta... |
niksolaz/TvApp | remembermyseries/settings.py | """
Django settings for remembermyseries project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... |
umd-mith/bagcat | setup.py | from sys import version, exit
from setuptools import setup
requirements = open("requirements.txt").read().split()
with open("README.md") as f:
long_description = f.read()
setup(
name = 'bagcat',
version = '0.0.6',
url = 'https://github.com/umd-mith/bagcat/',
author = 'Ed Summers',
author_emai... |
whittlbc/jarvis | migrations/versions/82edf10df5bc_.py | """empty message
Revision ID: 82edf10df5bc
Revises: 94538cbba222
Create Date: 2017-02-04 22:52:25.279228
"""
# revision identifiers, used by Alembic.
revision = '82edf10df5bc'
down_revision = '94538cbba222'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
wireservice/csvkit | csvkit/utilities/csvsort.py | #!/usr/bin/env python
import agate
from csvkit.cli import CSVKitUtility, parse_column_identifiers
class CSVSort(CSVKitUtility):
description = 'Sort CSV files. Like the Unix "sort" command, but for tabular data.'
def add_arguments(self):
self.argparser.add_argument(
'-n', '--names', dest... |
mgk/thingpin | src/thingpin/pin.py | import time
from threading import Thread
import RPi
from RPi import GPIO
from collections import Iterable
import itertools
HIGH = GPIO.HIGH
LOW = GPIO.LOW
def set_pin_mode(mode):
"""
Set pin numbering mode for all pins.
Args:
mode (str): mode to set, must be 'BOARD' or 'BCM'
"""
GPIO.set... |
cortesi/qtile | docs/sphinx_qtile.py | # Copyright (c) 2015 dmpayton
#
# 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 use, copy, modify, merge, publish, distribute... |
jdfreder/testandroid | helpguide/rich.py | """Contains RichPage class"""
from __future__ import print_function
from kivy.uix.listview import ListView, CompositeListItem, ListItemButton, ListItemLabel
from kivy.adapters.simplelistadapter import SimpleListAdapter
from kivy.uix.label import Label
from kivy.uix.rst import RstDocument
from kivy.uix.boxlayout import ... |
somcomltd/django-rbac | rbac/models.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
try:
from django.contrib.contenttypes.generic import GenericForeignKey
except ImportError:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.exceptions import ObjectDoesNotExist
def _get_per... |
thethomaseffect/travers-media-tools | django_filepicker/forms.py | from django import forms
from django.core.files import File
from django.conf import settings
from .widgets import FPFileWidget
import urllib2
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class FPFieldMixin():
widget = FPFileWidget
default_mimetypes = "*/*"
... |
rdiaz82/mqttSqlLite | mqttsqlite/core/topics_controller.py | from mqttsqlite.orm.models import Topic
import json
from mqttsqlite.settings.private_settings import MANAGEMENT_PASSWORD, QUERY_PASSWORD
from .utils import Payload, Utils
class TopicsController (object):
def add_topic(self, msg):
received_data = json.loads(msg.payload)
payload = Utils().validate_... |
AlexRiina/django-s3direct | example/example/settings.py | """
Django settings for hello project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# B... |
techyteach-s/plugin.audio.abcradioaustralia | addon.py | from xbmcswift2 import Plugin, xbmcgui
plugin = Plugin()
@plugin.route('/')
def main_menu():
items = [
{'label': plugin.get_string(30000), 'path': "http://www.abc.net.au/res/streaming/audio/mp3/radio_national.pls",
'is_playable': True},
{'label': plugin.get_string(30001), 'path': "htt... |
erik-sn/xlwrap | xlwrap.py | import os
import ntpath
import xlrd
import openpyxl
from openpyxl.utils import coordinate_from_string, column_index_from_string
from openpyxl.utils.exceptions import CellCoordinatesException
class ExcelManager:
"""
Wrapper that opens and operates on .xls, .xlsx or .xlsm excel files. By
default we take in ... |
interactiveaudiolab/nussl | tests/core/test_mixing.py | import nussl
import numpy as np
import pytest
def test_pan_audio_signal(mix_and_sources):
mix, sources = mix_and_sources
sources = list(sources.values())
panned_audio = nussl.mixing.pan_audio_signal(sources[0], -45)
zeros = np.zeros_like(panned_audio.audio_data[0])
sum_ch = np.sum(panned_audio.a... |
msincenselee/vnpy | prod/jobs/refill_tdx_cb_stock_bars.py | # flake8: noqa
"""
下载通达信可转债1分钟bar => vnpy项目目录/bar_data/
上海股票 => SSE子目录
深圳股票 => SZSE子目录
"""
import os
import sys
import csv
import json
from collections import OrderedDict
import pandas as pd
vnpy_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if vnpy_root not in sys.path:
sys.path.appe... |
gcc-robotics/prometheus | software/narthex/PrometheusSerial.py | import json
import serial
class PrometheusSerial:
portPrefix = '/dev/ttyUSB'
portNumber = 0
connected = False
connection = None
socket = None
reactor = None
def __init__(self, reactor):
print "PrometheusSerial: Starting serial communication"
self.reactor = reactor
self.init()
def init(self):
seri... |
banglakit/spaCy | spacy/tests/sv/test_tokenizer.py | # encoding: utf8
from __future__ import unicode_literals
import pytest
SV_TOKEN_EXCEPTION_TESTS = [
('Smörsåsen används bl.a. till fisk', ['Smörsåsen', 'används', 'bl.a.', 'till', 'fisk']),
('Jag kommer först kl. 13 p.g.a. diverse förseningar', ['Jag', 'kommer', 'först', 'kl.', '13', 'p.g.a.', 'diverse', 'fö... |
guanhuamai/DPM | PythonSource/DecisionMakerLib/ApollingSelect.py | import sys
sys.path.append("..")
import math
import heapq
import numpy as np
import copy
from scipy import optimize
global nodes, edges, M, BaseMatrix
global left_edges, selected_edges, last_score, Hessian, record_inv_matrix, record_current_matrix
global crowdgauss_estimation_edges
global num_workers
normal_pdf = la... |
tzpBingo/github-trending | codespace/python/tencentcloud/tia/v20180226/tia_client.py | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... |
devartis/passbook | passbook/models.py | # -*- coding: utf-8 -*-
import decimal
import hashlib
import json
import zipfile
from io import BytesIO
from M2Crypto import SMIME
from M2Crypto import X509
from M2Crypto.X509 import X509_Stack
class Alignment:
LEFT = 'PKTextAlignmentLeft'
CENTER = 'PKTextAlignmentCenter'
RIGHT = 'PKTextAl... |
winiciuscota/OG-Bot | ogbot/scraping/movement.py | from bs4 import BeautifulSoup
from datetime import datetime
from scraper import *
from general import General
def get_arrival_time(arrival_time_str):
time = datetime.strptime(arrival_time_str.strip(), '%H:%M:%S').time()
now = datetime.now()
arrival_time = datetime.combine(now, time)
return arrival_tim... |
wuub/python_lcd | lcd/pyb_gpio_lcd_test8.py | """Implements a character based lcd connected via PCF8574 on i2c."""
from pyb import Pin
from pyb import delay, millis
from pyb_gpio_lcd import GpioLcd
# Wiring used for this example:
#
# 1 - Vss (aka Ground) - Connect to one of the ground pins on you pyboard.
# 2 - VDD - I connected to VIN which is 5 volts when yo... |
silberman/Deep-OSM | src/download_labels.py | '''
Extract Ways from OSM PBF files
'''
import osmium as o
import json, os, requests, sys, time
import shapely.wkb as wkblib
# http://docs.osmcode.org/pyosmium/latest/intro.html
# A global factory that creates WKB from a osmium geometry
wkbfab = o.geom.WKBFactory()
# set in Dockerfile as env variable
GEO_DATA_DIR = ... |
uber-common/deck.gl | bindings/pydeck/pydeck/types/string.py | from functools import total_ordering
from .base import PydeckType
@total_ordering
class String(PydeckType):
"""Indicate a string value in pydeck
Parameters
----------
value : str
Value of the string
"""
def __init__(self, s: str, quote_type: str = ""):
self.value = f"{quote... |
supistar/Botnyan | model/qrcreator.py | # -*- encoding:utf8 -*-
import cStringIO
import qrcode
class QRCodeCreator():
def __init__(self):
pass
def create(self, message):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
... |
V3sth4cks153/Python-Programs | equation_solver.py | # -*- coding: utf-8 -*-
#Import libraries
from sys import exit
from math import sqrt
#Print title (http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Equation%20Solver%20V2.1)
print " ____ __ _ ____ __ _ _____ ___"
print " / __/__ ___ _____ _/ /_(_)__ ___ ... |
facelessuser/TabsExtra | lib/file_strip/json.py | """
File Strip.
Licensed under MIT
Copyright (c) 2012 - 2016 Isaac Muse <isaacmuse@gmail.com>
"""
import re
from .comments import Comments
JSON_PATTERN = re.compile(
r'''(?x)
(
(?P<square_comma>
, # trailing comma
(?P<square_ws>[\s\r\n]*) ... |
nkmk/python-snippets | notebook/round_test.py | f = 123.456
print(round(f))
# 123
print(type(round(f)))
# <class 'int'>
print(round(f, 1))
# 123.5
print(round(f, 2))
# 123.46
print(round(f, -1))
# 120.0
print(round(f, -2))
# 100.0
print(round(f, 0))
# 123.0
print(type(round(f, 0)))
# <class 'float'>
i = 99518
print(round(i))
# 99518
print(round(i, 2))
# 9... |
Cesarmerjan/Pystatistic | Bartletts_test.py | import numpy as np
from scipy import stats
def Bartlett (matrix):
n = np.array([len(i) for i in matrix])
k = len(matrix)
N = n.sum()
Si2 = np.var(matrix, axis=1, ddof=1)
Sp2 = (np.array([(n[i]-1) * Si2[i] for i in range(k)]).sum() / (N - k))
term_1 = (N-k)*np.log(Sp2)
term_2 = np.array([... |
ArtemMIPT/sentiment_analysis | app.py | import functools
import re
import os
from flask import Flask, render_template, request, jsonify
from extensions import db, login_manager, csrf
import config
from sentiment_classifiers import SentimentClassifier, files, binary_dict
from vk_parser import VkFeatureProvider
app = Flask(__name__)
########################... |
portfoliome/postpy | postpy/pg_encodings.py | from encodings import normalize_encoding, aliases
from types import MappingProxyType
from psycopg2.extensions import encodings as _PG_ENCODING_MAP
PG_ENCODING_MAP = MappingProxyType(_PG_ENCODING_MAP)
# python to postgres encoding map
_PYTHON_ENCODING_MAP = {
v: k for k, v in PG_ENCODING_MAP.items()
}
def get_... |
ExaScience/smurff | python/smurff/smurff.py | from .trainsession import TrainSession
from .helper import FixedNoise
class SmurffSession(TrainSession):
def __init__(self, Ytrain, priors, is_scarce = True, Ytest=None, side_info=None, direct=True, *args, **kwargs):
TrainSession.__init__(self, priors=priors, *args, **kwargs)
self.addTrainAndTest(Y... |
bjodah/PyLaTeX | examples/full.py | #!/usr/bin/python
"""
This example demonstrates several features of PyLaTeX.
It includes plain equations, tables, equations using numpy objects, tikz plots,
and figures.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
# begin-doc-include
import numpy as np
from pylate... |
he7d3r/revscoring | revscoring/languages/features/regex_matches/__init__.py | """
Implements a feature set based off of a set of regexes applied to strings.
.. autoclass:: revscoring.languages.features.RegexMatches
:members:
:member-order: bysource
Supporting classes
------------------
.. autoclass:: revscoring.languages.features.regex_matches.Revision
:members:
:member-order:... |
Fewbytes/rubber-docker | levels/04_overlay/rd.py | #!/usr/bin/env python2.7
"""Docker From Scratch Workshop - Level 4: Add overlay FS.
Goal: Instead of re-extracting the image, use it as a read-only layer
(lowerdir), and create a copy-on-write layer for changes (upperdir).
HINT: Don't forget that overlay fs also requires a workdir.
Read more on overlay FS here... |
telegraphic/fits2hdf | aadnc_benchmarks/quinoa_idea/quinoa.py | # -*- coding: utf-8 -*-
"""
quinoa.py
=========
Create QUINOA compressed dataset.
QUINOA (QUasi Integer Noise Offset Adjustment) compression is a lossy compression
algorithm for floating point data, and is similar to the RICE-based compression
technique that FPACK uses on floating point data.
The FITS compression pa... |
bros-bioinfo/bros-bioinfo.github.io | COURS/M1/SEMESTRE2/ALGO/TD_Arbres.py | from typing import *
class Sommet:
def __init__(self, pere, etiquette=None):
self.pere = pere
self.fils = []
self.label = etiquette
if pere:
pere.fils.append(self)
class Arbre:
def __init__(self):
self.root = Sommet(None)
def fils(arbre: Arbre, sommet: S... |
rubikloud/pypicloud | pypicloud/access/base.py | """ The access backend object base class """
from collections import defaultdict
from passlib.apps import custom_app_context as pwd_context
from pyramid.security import (Authenticated, Everyone,
effective_principals, Allow, Deny,
ALL_PERMISSIONS)
from pyramid.... |
andela-ijubril/book-search | booker/bookstore/tests/test_views.py | from django.test import TestCase, Client
from bookstore.models import Book, Category
from django.core.urlresolvers import reverse
class BookStoreViewTestCase(TestCase):
def setUp(self):
self.client = Client()
self.category = Category.objects.create(name="programming", description="for the geeks")
... |
village-people/flying-pig | ai_challenge/agents/_ignorebeta_dqn_agent_batch.py | # 2017, Andrei N., Tudor B.
from sphinx.addnodes import centered
from ._ignore_Agent import Agent
from ._ignore_Agent import Transition
import matplotlib.pyplot as plt
from random import choice
import logging
import os
import numpy as np
import math
import random
import torch
import torch.nn as nn
import torch.opti... |
softlayer/softlayer-cinder-driver | slos/test/mocks/cinder/exception.py | #!/usr/bin/env python
class BaseException(Exception):
def __init__(self, message=None, **kwargs):
pass
class InvalidResults(BaseException):
pass
class InvalidConfigurationValue(BaseException):
pass
class VolumeBackendAPIException(BaseException):
pass
class InvalidSnapshot(BaseException... |
jcatw/scnn | scnn/graph_proportion_baseline_experiment.py | __author__ = 'jatwood'
import sys
import numpy as np
from sklearn.metrics import f1_score, accuracy_score
from sklearn.linear_model import LogisticRegression
import data
import util
import kernel
import structured
from baseline_graph_experiment import GraphDecompositionModel
def graph_proportion_baseline_experiment... |
koddsson/coredata-python-client | docs/conf.py | # -*- coding: utf-8 -*-
""" Sphinx configuration file. """
#
# Coredata API client documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 6 19:20:17 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration value... |
vaidhy/python-linkedin-fork | linkedin/tests/linkedin_request_test.py | '''
Created on Aug 31, 2011
@author: Iftach
'''
from linkedin.tests import *
from linkedin import linkedin
class LinkedInRequestTest(LinkedInTestBase):
def test_request_token(self):
self._test_request_token(False)
def test_request_token_gae(self):
self._init_gae()
... |
menghanY/LeetCode-Python | Array/RemoveDuplicatesfromSortedArray.py | # Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
#
# Do not allocate extra space for another array, you must do this in place with constant memory.
#
# For example,
# Given input array nums = [1,1,2],
#
# Your function should return length = 2, wi... |
PersianWikipedia/pywikibot-core | pywikibot/families/vikidia_family.py | # -*- coding: utf-8 -*-
"""Family module for Vikidia."""
#
# (C) Pywikibot team, 2010-2018
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals
from pywikibot import family
class Family(family.SubdomainFamily):
"""Family class for Vikidia."""
... |
jasonkeene/python-ubersmith | ubersmith/api.py | """Lower level API, configuration, and HTTP stuff."""
import six
import time
from ubersmith.compat import total_ordering, file_type
import requests
from ubersmith.exceptions import (
RequestError,
ResponseError,
UpdatingTokenResponse,
MaintenanceResponse,
)
from ubersmith.utils import (
append_qs,... |
cevap/ion | test/functional/interface_http.py | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the RPC HTTP basics."""
from test_framework.test_framework import BitcoinTestFramework
from test_... |
Udzu/pudzu | dataviz/flagstriband.py | from pudzu.charts import *
df = pd.read_csv("datasets/flagstriband.csv")
df = pd.concat([pd.DataFrame(df.colours.apply(list).tolist(), columns=list("TMB")), df], axis=1).set_index("colours")
FONT, SIZE = calibri, 24
fg, bg = "black", "#EEEEEE"
default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a4... |
coolharsh55/hdd-indexer | setup.py | """Setup for HDD-indexer
This module provides the setup for ``hdd-indexer`` by downloading its
`dependencies`, creating the `database`, createing a sampel `user`.
Usage:
$ python setup.py
Dependencies:
The dependencies are installed with pip.
$ pip install -r requirements.txt
Database:
The d... |
jonaustin/advisoryscan | django/django/contrib/localflavor/it/it_province.py | # -*- coding: utf-8 -*
PROVINCE_CHOICES = (
('AG', 'Agrigento'),
('AL', 'Alessandria'),
('AN', 'Ancona'),
('AO', 'Aosta'),
('AR', 'Arezzo'),
('AP', 'Ascoli Piceno'),
('AT', 'Asti'),
('AV', 'Avellino'),
('BA', 'Bari'),
# ('BT', 'Barletta-Andria-Trani'), # active starting from 2009... |
bstinsonmhk/python-template | {{cookiecutter.project_repo}}/docs/conf.py | # -*- coding: utf-8 -*-
#
# {{ cookiecutter.project_repo }} documentation build configuration file, created by
# sphinx-quickstart on Sat Dec 19 13:16:21 2015.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# aut... |
killuazhu/vimrc | sources_non_forked/deoplete.nvim/rplugin/python3/deoplete/filter/converter_truncate_menu.py | # ============================================================================
# FILE: converter_truncate_menu.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license
# ============================================================================
from .base import Base
from deoplete.util impor... |
DailyActie/Surrogate-Model | 01-codes/tensorflow-master/tensorflow/models/image/mnist/convolutional.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
simras/CLAP | scripts/mk_ErrorModel.py | #!/usr/bin/python
# mk_ErrorModel.py -m 0.125
# Example
# By Simon H. Rasmussen
# Bioinformatics Centre
# University of Copenhagen
#
def wLines(mutP):
# range of qualities 0...41
for qual in range(42):
for base in ["A","C","G","T"]:
# quality base P(a|base) P(c|base) P(g|base... |
yowmamasita/social-listener-exam | ferris/core/controller.py | import webapp2
import re
import weakref
from webapp2 import cached_property
from webapp2_extras import sessions
from google.appengine.api import users
from ferris.core.ndb import encode_key, decode_key
from ferris.core.uri import Uri
from ferris.core import inflector, auth, events, views, request_parsers, response_hand... |
bnmrrs/runkeeper-api | runkeeper/httpclient.py | #
# The MIT License
#
# Copyright (c) 2009 Ben Morris
#
# 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 use, copy, modi... |
wooga/play-deliver | playdeliver/listing.py | """This module helps for uploading and downloading listings from/to play."""
import os
import json
from file_util import mkdir_p
from file_util import list_dir_abspath
def upload(client, source_dir):
"""Upload listing files in source_dir. folder herachy."""
print('')
print('upload store listings')
pri... |
KT12/hands_on_machine_learning | convnets.py | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.datasets import load_sample_image
from sklearn.datasets import load_sample_images
# Utility functions
def plot_image(image):
plt.imshow(image, cmap="gray", interpolation="nearest")
plt.axis("off")
def plot_color_image(image... |
mikelum/pyspeckit | pyspeckit/spectrum/writers/txt_writer.py | from __future__ import print_function
try:
import atpy
atpyOK = True
except ImportError:
atpyOK = False
# rewrite this garbage
class write_txt(object):
def __init__(self, Spectrum):
self.Spectrum = Spectrum
def write_data(self, clobber = True):
"""
Write all fit informatio... |
coddingtonbear/django-measurement | tests/forms.py | from django import forms
from django_measurement.forms import MeasurementField
from tests.custom_measure_base import DegreePerTime, Temperature, Time
from tests.models import MeasurementTestModel
class MeasurementTestForm(forms.ModelForm):
class Meta:
model = MeasurementTestModel
exclude = []
c... |
OiNutter/rivets | test/test_scss.py | import sys
sys.path.insert(0,'../')
if sys.version_info[:2] == (2,6):
import unittest2 as unittest
else:
import unittest
import os
import lean
import shutil
import datetime
import time
from rivets_test import RivetsTest
import rivets
CACHE_PATH = os.path.relpath("../../.sass-cache", __file__)
COMPASS_PATH = os.path... |
commaai/openpilot | selfdrive/car/subaru/values.py | from selfdrive.car import dbc_dict
from cereal import car
Ecu = car.CarParams.Ecu
class CarControllerParams:
def __init__(self, CP):
if CP.carFingerprint == CAR.IMPREZA_2020:
self.STEER_MAX = 1439
else:
self.STEER_MAX = 2047
self.STEER_STEP = 2 # how often we update the steer c... |
stonescar/multi-user-blog | blogmods/handlers/new_post.py | from main_handler import Handler
from ..models import Posts
from .. import utils
class NewPost(Handler):
"""Handler for new post page"""
@utils.login_required
def get(self):
self.render("newpost.html")
@utils.login_required
def post(self):
subject = self.request.get("subject")
... |
Kaarel94/Ozobot-Python | ozopython/__init__.py | from tkinter import ttk
from ozopython.colorLanguageTranslator import ColorLanguageTranslator
from .ozopython import *
from tkinter import *
def run(filename):
code = ozopython.compile(filename)
colorcode = ColorLanguageTranslator.translate(code)
def load(prog, prog_bar):
colormap = {
... |
mcieslik-mctp/papy | src/papy/util/codefile.py | """
:mod:`papy.util.codefile`
=========================
Provides template strings for saving **PaPy** pipelines directly as Python
source code.
"""
# imap call signature
I_SIG = ' %s = NuMap(worker_type="%s", worker_num=%s, stride=%s, buffer=%s, ' + \
'ordered =%s, skip =%s, name ="%s")\n'
# pi... |
zooliet/UWTracking | src/trackers/dlib_tracker/dlib_tracker.py |
import cv2
import numpy as np
import imutils
from utils import util
import dlib
import itertools
class DLIBTracker:
def __init__(self):
self._tracker = dlib.correlation_tracker()
self.detector = cv2.BRISK_create(10)
# self.detector = cv2.AKAZE_create()
# self.detector = cv2.xfeatur... |
gista/django-selectfilter | selectfilter/utils.py | # -*- coding: utf-8 -*-
# request helpers
def _cleanValue(value):
mapping = {
"True": True,
"False": False,
"None": None,
}
return mapping.get(value, value)
def lookupToString(lookup_dict):
"""
Convert the lookup dict into a string.
e.g.:
{"field1": "a", "field2": "b"} -> "field1=a,field2=b"
"""
ret... |
prophile/jacquard | doc/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# jacquard documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 13 04:43:44 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... |
odrling/peony-twitter | docs/conf.py | # -*- coding: utf-8 -*-
#
# Peony documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 30 16:36:34 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... |
RedMadRobot/rmr_django | rmr/middleware/json.py | import json
from django import http
from django.conf import settings
from rmr.types import JsonDict
class RequestDecoder:
content_type = 'application/json'
allowed_methods = {
'POST', 'PUT', 'PATCH',
}
def process_request(self, request):
if request.method not in self.allowed_metho... |
Proteus-tech/nikola | nikola/plugins/task/rss.py | # -*- coding: utf-8 -*-
# Copyright © 2012-2013 Roberto Alsina and others.
# 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 t... |
benoitc/pywebmachine | tests/decisions/b08_test.py | import t
class b08(t.Test):
class TestResource(t.Resource):
def is_authorized(self, req, rsp):
if req.headers.get('authorization') == 'yay':
return True
return 'oauth'
def to_html(self, req, rsp):
return "nom nom"
def test_... |
rozap/arb | src/api/campbx.py | import urllib2
import base64
import simplejson as json
import logging
from urllib import urlencode
from functools import partial
log = logging.getLogger(__name__)
log_formatter = logging.Formatter('%(name)s - %(message)s')
log_handler = logging.StreamHandler()
log_handler.setFormatter(log_formatter)
log.addHandler(lo... |
m3zbaul/ai-search | simulated_annealing.py | # coding=utf-8
import random
import math
import n_queen
def simulated_annealing_search(problem):
# annealing parameters
alpha = 0.99
T = 10000.0
T_min = 3.95
current = problem
while T > T_min:
T = T * alpha
successor = n_queen.NQueenState.random_successor(current)
E = c... |
mjochum64/flask-blog | blog.py | # blog.py - controller
# -*- coding: utf-8 -*-
# imports
from flask import Flask, render_template, request, session, \
flash, redirect, url_for, g
import sqlite3
from functools import wraps
# configuration
DATABASE = 'blog.db'
USERNAME = 'admin'
PASSWORD = 'test'
SECRET_KEY = u'zbu#<)sA6qp<=Swr!§h?qCVs5'
app = F... |
cescobarresi/ciscoreputation | ciscoreputation/__about__.py | # encoding: utf-8
import os.path
__all__ = [
"__title__", "__summary__", "__uri__", "__version__",
"__author__", "__email__", "__license__", "__copyright__",
]
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
except NameError:
base_dir = None
__title__ = "ciscoreputation"
__summary__ = "G... |
tiangolo/fastapi | docs_src/request_files/tutorial001_02_py310.py | from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes | None = File(None)):
if not file:
return {"message": "No file sent"}
else:
return {"file_size": len(file)}
@app.post("/uploadfile/")
async def create_upload_file(file: Uploa... |
PyFilesystem/pyfilesystem2 | fs/wrapfs.py | """Base class for filesystem wrappers.
"""
from __future__ import unicode_literals
import typing
import six
from . import errors
from .base import FS
from .copy import copy_file, copy_dir
from .info import Info
from .path import abspath, join, normpath
from .error_tools import unwrap_errors
if typing.TYPE_CHECKING... |
kfdm/django-simplestats | quickstats/urls.py | from . import views
from django.urls import path
urlpatterns = [
path("", views.PublicWidgets.as_view(), name="home"),
path("create/widget", views.WidgetCreate.as_view(), name="widget-create"),
path("subscription/<pk>/delete", views.SubscriptionDelete.as_view(), name="subscription-delete"),
path("user... |
ipfs/py-ipfs-api | test/unit/test_http_httpx.py | # Only add tests to this file if they really are specific to the behaviour
# of this backend. For cross-backend or `http_common.py` tests use
# `test_http.py` instead.
import http.cookiejar
import math
import pytest
pytest.importorskip("ipfshttpclient.http_httpx")
import ipfshttpclient.http_httpx
cookiejar = http.co... |
mstoppert/adventofcode | 06/answer.py | import numpy
file = open("input.txt")
lights = numpy.zeros((1000,1000), 'int')
def split_instruction(line):
split = line.split(' ')
if "turn on" in line or "turn off" in line:
instruction = "%s_%s" % (split[0], split[1])
first_pair = [int(x) for x in split[2].split(",")]
second_pair =... |
cpaulik/pyscaffold | tests/extensions/test_travis.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from os.path import exists as path_exists
from pyscaffold.api import create_project
from pyscaffold.cli import run
from pyscaffold.extensions import travis
def test_create_project_with_travis(tmpfolder):
# Given options with the travis extension,
opts ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.