repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
WillisXChen/django-oscar | oscar/lib/python2.7/site-packages/IPython/kernel/zmq/tests/test_session.py | Python | bsd-3-clause | 12,721 | 0.005817 | """test building messages with streamsession"""
#-------------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-... | qual(ident[0], b'foo')
self.assertEqual(new_msg['msg_id'],msg['msg_id'])
self.assertEqual(new_msg['msg_type'],msg['msg_type'])
self.assertEqual(new_msg['header'],msg['header'])
self.assertEqual(new_msg['content'],msg['content'])
self.assertEqual(new_msg['metadata'],msg['metadata'... | self.assertEqual(new_msg['parent_header'],msg['parent_header'])
self.assertEqual(new_msg['buffers'],[b'bar'])
self.session.send(A, msg, ident=b'foo', buffers=[b'bar'])
ident, new_msg = self.session.recv(B)
self.assertEqual(ident[0], b'foo')
self.assertEqual(new_msg['msg_id... |
jaycrossler/procyon | procyon/starcatalog/tests.py | Python | mit | 1,921 | 0.003644 | from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from procyon.starcatalog.models import Star
class StarCatalog(TestCase):
def setUp(self):
star1 = Star.objects.create(**{"HR": None, "spectrum": "G5", "Y": -28.6581, "VY": 5.7579e-05, "HD": None, "HIP": 70767, "RV"... | w(self):
"""
Tests the search view.
"""
c = Client()
| term = 'kelda'
db_lookup = Star.objects.filter(proper_name__icontains=term)
response = c.get(reverse('star-list-no-id') + '?q={term}'.format(term=term))
for i in db_lookup:
self.assertTrue(i in response.context['items'])
|
oser-cs/oser-website | tests/test_core/test_address.py | Python | gpl-3.0 | 1,331 | 0 | """Address model tests."""
from core.models import Address
from core.factory import AddressFactory
from tests.utils import ModelTestCase
class AddressTest(ModelTestCase):
"""Test the Address model."""
model = Address
field_tests = {
'line1': {
'verbose_name': 'ligne 1',
'... | ata(cls):
cls.obj = AddressFactory.create(
line1='3 Rue Joliot Curie',
post_code='91190',
city='Gi | f-sur-Yvette',
)
def test_str(self):
expected = '3 Rue Joliot Curie, 91190 Gif-sur-Yvette, France'
self.assertEqual(expected, str(self.obj))
|
MOOCworkbench/MOOCworkbench | experiments_manager/migrations/0002_auto_20170502_0952.py | Python | mit | 2,437 | 0.003283 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-02 09:52
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('cookiecutter_manager', '0002_auto_2017050... | name='travis',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='build_manager | .TravisInstance'),
),
migrations.AddField(
model_name='chosenexperimentsteps',
name='experiment',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='experiments_manager.Experiment'),
),
migrations.AddField(
model_name=... |
zuun77/givemegoogletshirts | codejam/2020/qual/q4.py | Python | apache-2.0 | 411 | 0.007299 | import sys
def solve(B):
ans = [0]*B
guess = 1
for _ in range(10):
print(guess)
sys.stdout.flush()
n = int(input().strip())
ans[guess-1] = n
guess += 1
print("". | join(map(str, ans)))
sys.stdout.flush()
result = input()
if result == "N":
sys.exit()
return
T, | B = map(int, input().split())
for case in range(1, T+1):
solve(B)
|
plusky/spec-cleaner | spec_cleaner/rpminstall.py | Python | bsd-3-clause | 1,588 | 0.001259 | # vim: set ts=4 sw=4 et: coding=UTF-8
from .rpmsection import Section
class RpmInstall(Section):
'''
Remove commands that wipe out the build root.
Replace %makeinstall (suse-ism).
'''
def add(self, line):
line = self._complete_cleanup(line)
# we do not want to cleanup b... | sub(' %{?_smp_mflags}', line)
if not self.minimal:
line = self._replace_remove_la(line)
line = self._replace_install_command(line)
Section.add(self, line)
def _replace_install_command(self, line):
"""
Replace various install commands with one unified mutatio... | rouble with it for now
# we can convert it later on
if self.reg.re_install.match(line):
line = make_install
# we can deal with additional params for %makeinstall so replace that
line = line.replace('%makeinstall', make_install)
return line
def _replace_remove_l... |
anurag03/integration_tests | cfme/tests/integration/test_aws_iam_auth_and_roles.py | Python | gpl-2.0 | 4,448 | 0.003372 | import pytest
from deepdiff import DeepDiff
from cfme.roles import role_access_ui_59z, role_access_ui_510z
from cfme.utils.appliance import ViaUI, find_appliance
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.blockers import BZ
from cfme.utils.conf import credentials
from cfme.utils.lo... | ['evmgroup-user', 'evmgroup-approver', 'evmgroup-desktop', 'evmgroup-vm_user',
'evmgroup-administrator', 'evmgroup-s | uper_administrator'])
for area in group_access.keys():
# using .get() on nav_visibility because it may not have `area` key
diff = DeepDiff(group_access[area], nav_visible.get(area, {}),
verbose_level=0, # If any higher, will flag string vs uni... |
sramana/rtc-schedule | uttar_pradesh.py | Python | unlicense | 2,884 | 0.001734 | """Timetable of buses operated by Uttar Pradesh S | tate Road Transport Corporation (UPSRTC)
"""
from datetime import datetime
import re
import scraperwiki
import | lxml.html
base_url = 'http://www.upsrtc.com/online/query/'
services = dict()
def find_by_text(element, selector, text):
for a in element.cssselect(selector):
if text in a.text_content():
return a
def clean(items):
cleaned = []
for item in items:
# Remove non-ascii character... |
beyondmetis/scikit-video | skvideo/motion/block.py | Python | bsd-3-clause | 38,685 | 0.002714 | import numpy as np
import os
import time
from ..utils import *
def _costMAD(block1, block2):
block1 = block1.astype(np.float)
block2 = block2.astype(np.float)
return np.mean(np.abs(block1 - block2))
def _minCost(costs):
h, w = costs.shape
if costs[h/2, w/2] == 0:
return np.int((h-1)/2),... | continue
else:
costs[idx] = _costMAD(imgP[i:i + mbSize, j:j + mbSize], imgI[refBlkVer:refBlkVer + mbSize, refBlkHor:refBlkHor + mbSize])
computations += 1
point = np.argmin(costs)
cost = ... | if (np.abs(LDSP[point][0]) == np.abs(LDSP[point][1])):
cornerFlag = 0
xLast = x
yLast = y
x += LDSP[point][0]
y += LDSP[point][1]
costs[:] = 65537
costs[4] = cost
... |
google/clusterfuzz | src/clusterfuzz/_internal/tests/core/bot/tasks/impact_task_test.py | Python | apache-2.0 | 35,361 | 0.002375 | # Copyright 2019 Google LLC
#
# 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 agreed to in writing, ... | self.testcase.job_type = 'job2'
self.testcase.project_name = 'chromium'
self.testcase.put()
def reload(self):
"""Reload testcase."""
self.t | estcase = self.testcase.key.get()
def expect_unchanged(self):
"""Expect testcase's impacts to be unchanged."""
self.reload()
self.assertIsNone(self.testcase.impact_stable_version)
self.assertIsNone(self.testcase.impact_beta_version)
self.assertIsNone(self.testcase.impact_head_version)
def expe... |
tylercrompton/streams | tests/__init__.py | Python | gpl-3.0 | 654 | 0 | # This file is part of Streams.
#
# Streams is free software: you can redistribute it and/or modify it
# u | nder the terms of the GNU General Public License as published by the
# Free Softwa | re Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# Streams is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more d... |
stefanklug/mapnik | scons/scons-local-2.3.6/SCons/Tool/MSCommon/sdk.py | Python | lgpl-2.1 | 14,900 | 0.006711 | #
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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... |
__revision__ = "src/engine/SCons/Tool/MSCommon/sdk.py rel_2.3.5:3347:d31d5a4e74b6 2015/07/31 14:36:10 bdbaddog"
__doc__ = """Module to detect the Platform/Windows SDK
PSDK 2003 R1 is the earliest version detected.
"""
import os
import | SCons.Errors
import SCons.Util
import common
debug = common.debug
# SDK Checks. This is of course a mess as everything else on MS platforms. Here
# is what we do to detect the SDK:
#
# For Windows SDK >= 6.0: just look into the registry entries:
# HKLM\Software\Microsoft\Microsoft SDKs\Windows
# All the keys in th... |
imbasimba/astroquery | astroquery/simbad/tests/test_simbad.py | Python | bsd-3-clause | 17,976 | 0.000056 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import re
import six
import pytest
import astropy.units as u
from astropy.table import Table
import numpy as np
from ... import simbad
from ...utils.testing_tools import MockResponse
from ...utils import commons
from ...exceptions import TableP... | ectids_async('Polaris')
response2 = simbad.core.Simbad().query_objectids_async('Polaris')
| assert response1 is not None and response2 is not None
assert response1.content == response2.content
def test_query_objectids(patch_post):
result1 = simbad.core.Simbad.query_objectids('Polaris')
result2 = simbad.core.Simbad().query_objectids('Polaris')
assert isinstance(result1, Table)
assert is... |
onoga/toolib | toolib/wx/controls/gant/LinkShape.py | Python | gpl-2.0 | 1,368 | 0.035819 | import wx
import wx.lib.ogl as ogl
cl | ass LinkShape(ogl.LineShape):
def __init__(self, canvas, link):
self.canvas = canvas
self.__link = link
ogl.LineShape.__init__(self)
#self.SetCanvas(canvas)
#line.SetPen(wx.BLACK_PEN)
#line.SetBrush(wx.BLACK_BRUSH)
self.AddArrow(ogl.ARROW_ARROW)
self.MakeLineControlPoints(3)
self._updateX()
self... | ._getShape(self.__link.getActivityFrom())
a2 = self.canvas._getShape(self.__link.getActivityTo())
p1, p2, p3 = self.GetLineControlPoints()
p1[0] = a1.GetX() + a1.GetWidth() / 2.
p2[0] = p3[0] = a2.GetX() - a2.GetWidth() / 2. + self.canvas.getDx() / 3.
def _updateY(self):
a1 = self.canvas._getShape(sel... |
viswimmer1/PythonGenerator | data/python_files/30004740/widgets.py | Python | gpl-2.0 | 9,892 | 0.007986 | import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFo... | ods.keys()))
class YUIBaseCSS(Widget):
css = [CSSLink("TGYUI", "base/base-min.css")]
yuibasecss = YUIBaseCSS()
class YUIResetCSS(Widget):
css = [CSSLink("TGYUI", "reset/reset-min.css")]
yuiresetcss = YUIResetCSS()
class YUIFontsCSS(Widget):
css = [CSSLink("TGYUI", "fon... | = [CSSLink("TGYUI", "grids/grids-min.css")]
yuigridscss = YUIGrids()
class YUIResetFontsGrids(Widget):
"""Use this in place of using all the three YUIResetCSS, YUIFontsCSS,
YUIGrids. You might want to explicitly include all three if you use other
widgets that depend on one of them, to avoid duplications... |
jadecastro/LTLMoP | src/lib/handlers/share/dummySensor.py | Python | gpl-3.0 | 6,284 | 0.007161 | #!/usr/bin/env python
"""
=====================================
dummySensor.py - Dummy Sensor Handler
=====================================
Displays a silly little window for faking sensor values by clicking on buttons.
"""
import threading, subprocess, os, time, socket
import numpy, math
import sys
class sensorHand... | ry killing all Python processes and trying again."
return
while self._running:
# Wait for and receive a message from the subwindow
try:
input,addrFrom = UDPSock.recvfrom(1024)
| except socket.timeout:
continue
if input == '': # EOF indicates that the connection has been destroyed
print "(SENS) Sensor handler listen thread is shutting down."
break
# Check for the initialization signal, if necessary
... |
PyThaiNLP/pythainlp | pythainlp/util/keywords.py | Python | apache-2.0 | 3,590 | 0 | # -*- coding: utf-8 -*-
from collections import Counter
from typing import Dict, List
from pythainlp.corpus import thai_stopwords
_STOPWORDS = thai_stopwords()
def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Count word frequecy given a list of Thai words with an option |
to exclude stopwords.
:param list words: a list of words
:param bool exclude_stopwords: If this parameter is set to **True**
| to exclude stopwords from counting.
Otherwise, the stopwords will be counted.
By default, `exclude_stopwords`is
set to **False**
:return: a Counter object representing word frequency from the t... |
villeneuvelab/vlpp | setup.py | Python | mit | 1,093 | 0.006404 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
description = """Villeneuve Lab PET Pipeline"""
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
from glob import glob
from setuptools import setup
DISTNA... | ong_description,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
#url=URL,
#download_url=DOWNLOAD_URL,
packages=[DISTNAME],
#scripts=glob('scripts/*') + glob('pipelines/*.nf'),
install_requires=INSTALL_REQUI | RES,
)
|
lithiumtech/skybase.io | skybase/skytask/service/record_state.py | Python | apache-2.0 | 3,815 | 0.002097 | import logging
import json
from skybase.skytask import SkyTask
from skybase.artiball import Artiball
from skybase.utils.logger import Logger
from skybase.ac | tions.dbstate import write_service_state_record
from skybase import skytask
from skybase.planet import Planet
from skybase.utils import simple_error_format
import skybase.actions.skycloud
import skybase.exceptions
def service_record_state_add_arguments(parser):
parser.add_argument(
'-p', '--planet',
... | ction='store',
required=True,
help='planet name')
parser.add_argument(
'-a', '--artiball',
dest='source_artiball',
action='store',
required=True,
help='Packaged Release Bundle Name (required)'
)
parser.add_argument(
'-r', '--provider',
... |
houssine78/addons | product_internal_ref/models/product.py | Python | agpl-3.0 | 368 | 0.013624 | # -*- coding: utf-8 -*-
# © 2017 Houssine BAKKALI - Coop IT Easy
# License AGPL-3.0 or later (http:// | www.gnu.org/licenses/agpl). |
from openerp import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
default_code = fields.Char(related='product_variant_ids.default_code', string='Internal Reference', store=True) |
elfnor/sverchok | nodes/generator/image.py | Python | gpl-3.0 | 6,178 | 0.001964 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | out):
layout.prop_search(self, "name_image", bpy.data, 'images', text="image")
row = layout.row(align=True)
row.scale_x = 10.0
row.prop(self, "R", text="R")
row.prop(self, "G", text="G")
row.prop(self, "B", text="B")
def process(self):
inputs, outputs = self.... | erX = int(self.Xvecs)
if inputs['vecs Y'].is_linked:
IntegerY = min(int(inputs['vecs Y'].sv_get()[0][0]), 100)
else:
IntegerY = int(self.Yvecs)
step_x_linked = inputs['Step X'].is_linked
step_y_linked = inputs['Step Y'].is_linked
StepX = inputs['Step X']... |
acysos/odoo-addons | edicom/models/product_product.py | Python | agpl-3.0 | 532 | 0 | # -*- coding: utf-8 -*-
# Copyright 2020 Ignacio Ibeas <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class ProductProduct(models.Model):
_inherit = 'product.product'
edicom_tipart = fields.Selection(
string='Tipo articulo'... | ad de expedición'),
('TU', 'Unidad Comerciada'),
('VQ', 'Producto de medid | a variable')],
default='CU')
|
bkpathak/HackerRank-Problems | collections/strings/permuataion.py | Python | mit | 648 | 0.015432 | #https://www.youtube.com/watch?v=hqijNdQTBH8
def permute1(lst):
if len(lst) == 0:
yield []
elif len(lst) == 1:
yield lst
else:
for i in range(len(lst)):
| x = lst[i]
xs = lst[:i]+lst[i+1:]
for p in permute1(xs):
| yield [x] + p
def permute2(str,left,right):
if left == right:
print(str)
else:
for i in range(left,right):
str[i], str[left] = str[left], str[i]
permute2(str,left+1,right)
str[i], str[left] = str[left], str[i]
data = list("ABC")
permute2(data... |
chrisjdavie/shares | website_searching/telegraph_tips/test_function.py | Python | mit | 164 | 0.030488 | '''
Created on 2 Se | p 2014
@author: chris
'''
def main():
from telegraph_tips import tele_tip
symb = 'IRV.L'
if __name__ == '__main__':
m | ain() |
Cadasta/cadasta-geoodk | xforms/renderers.py | Python | agpl-3.0 | 2,727 | 0.000733 | from rest_framework import renderers
from django.utils.xmlutils import SimplerXMLGenerator
from django.utils.six.moves import StringIO
from django.utils.encoding import smart_text
from rest_framework.compat import six
from rest_framework import negotiation
import json
"""
@author: Jon Nordling
@date: 06/19/2016
XFor... | tor(stream, self.charset)
xml.startDocument()
xml.startElement(self.root_node, {'xmlns': self.xmlns})
self._to_xml(xml, data)
xml.endElement(self.root_node)
| xml.endDocument()
return stream.getvalue()
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement(self.element_node, {})
self._to_xml(xml, item)
xml.endElement(self.element_node)
... |
poldracklab/crn-app-registration-tool | setup.py | Python | apache-2.0 | 2,099 | 0.001429 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
PACKAGE_NAME = 'cappat'
def main():
""" Install entry-point """
from os import path as op
from glob import glob
from inspect import getfile, currentframe
from setuptools import setup, find_packages
from io import open # pylint: disable=W0622
... | c', 'old-wrappers', 'tests']),
package_data={'cappat': [
'tpl/*.jnj2',
'data/wrapper.sh',
'data/default_app_params.json',
'data/default_app_inputs.json'
]},
entry_points={'console_scripts': [
'cap | pwrapp=cappat.wrapper:main',
'cappgen=cappat.appgen:main'
]},
# scripts=glob('scripts/*'),
zip_safe=False,
# Dependencies handling
setup_requires=ldict['SETUP_REQUIRES'],
install_requires=ldict['REQUIRES'],
dependency_links=ldict['LINKS_REQUIRES'],
... |
yslin/tools-zodlin | ubuntu/vim/script/debug/python/python_mandelbrot.py | Python | apache-2.0 | 1,868 | 0.008565 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2012 zod.yslin
#
# 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 ... | i1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')... | 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
|
yinzishao/NewsScrapy | thepaper/thepaper/spiders/travelweeklychina_spider.py | Python | lgpl-3.0 | 8,246 | 0.012463 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'yinzishao'
import re
from scrapy.exceptions import CloseSpider
import scrapy
from bs4 import BeautifulSoup
import logging
from thepaper.items import NewsItem
import json
logger = logging.getLogger("TravelWeeklyChinaSpider")
from thepaper.settings import *
clas... | 能设定停止条件
# print self.domain+url,"request"
yield scrapy.Request(self.domain+url,
callback=self.parse | _news,
meta={
"topic_id":post_data["PageKey"],"PageNumber":old_pagenumber
}
)
PageKey = post_data['PageKey']
flag_id =str(int(PageKe... |
JudoWill/glue | glue/qt/tests/test_qtutil.py | Python | bsd-3-clause | 13,748 | 0.000145 | # pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103
from __future__ import absolute_import, division, print_function
import pytest
from .. import qtutil
from ...external.qt import QtGui
from ...external.qt.QtCore import Qt
from mock import MagicMock, patch
from ..qtutil import GlueDataDialog
from ..qtutil import pr... | .currentIndexChanged.connect(assert_consistent)
self.combo.addItem('a', 1)
assert | good[0]
# addItems
self.combo.clear()
good[0] = False
self.combo.addItems('b c d'.split())
assert good[0]
# removeItem
self.combo.clear()
self.combo.addItem('a', 1)
good[0] = False
self.combo.removeItem(0)
assert good[0]
def tes... |
cdeboever3/WASP | CHT/combined_test.py | Python | apache-2.0 | 25,839 | 0.009908 | # Copyright 2013 Graham McVicker and Bryce van de Geijn
#
# 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... | ributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF AN | Y KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
import math
import time
import gzip
import argparse
from scipy.optimize import *
from scipy import cast
from scipy.special import gammaln
from scipy.special im... |
ADKosm/Recipes | Recipes/rcps/admin.py | Python | mit | 1,503 | 0.000698 | from django.contrib import admin
# Register your models here.
from rcps.models import *
class IngredientToRecipeInline(admin.TabularInline):
model = Ingredient.recipes.through
verbose_name = 'Ингредиент'
verbose_name_plural = 'Ингредиенты'
class EquipmentInline(admin.TabularInline):
model = Equipme... | erbose_name = 'Тег'
verbose_name_plural = 'Теги'
class RecipeAdmin(admin.ModelAdmin):
model = Recipe
fields = ['recipe_name', 'recipe_link']
inlines = (
IngredientToRecipeInline,
EquipmentInline,
TagInline,
)
class IngredientComponentInAlternativeInline(admin.TabularInlin... | rnativeAdmin(admin.ModelAdmin):
model = IngredientAlternative
inlines = (
IngredientComponentInAlternativeInline,
)
admin.site.register(Recipe, RecipeAdmin)
admin.site.register(Ingredient)
admin.site.register(IngredientAlternative, IngredientAlternativeAdmin)
admin.site.register(IngredientCategory... |
eviljeff/olympia | src/olympia/devhub/tests/test_models.py | Python | bsd-3-clause | 2,120 | 0 | from olympia import amo
from olympia.addons.models import Addon
from olympia.amo.tests import TestCase
from olympia.devhub.models import BlogPost
from olympia.files.models import File
from olympia.versions.models import Version
class TestVersion(TestCase):
fixtures = ['base/users', 'base/addon_3615']
def set... | .3')
version_two.save()
file_two = File(status=status, version=version_two)
file_two.save()
return version_two, file_two
def test_version_delete_status_unreviewed(self):
self._extra_version_and_ | file(amo.STATUS_AWAITING_REVIEW)
self.version.delete()
assert self.addon.versions.count() == 1
assert Addon.objects.get(id=3615).status == amo.STATUS_NOMINATED
def test_file_delete_status_null(self):
assert self.addon.versions.count() == 1
self.file.delete()
assert ... |
q2apro/graph-padowan | Lib/Settings.py | Python | gpl-2.0 | 25,024 | 0.013827 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.4
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import ... |
self.__dict__[name] = value
else:
raise AttributeError | ("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if meth... |
loopCM/chromium | tools/perf/perf_tools/dom_perf.py | Python | bsd-3-clause | 2,746 | 0.016387 | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import math
import os
from telemetry.core import util
from telemetry.page import page_measurement
from telemetry.page import page_set
def ... | + 'DOMWalk' },
{ 'url': BASE_PAGE + 'Events' },
{ 'url': BASE_PAGE + 'Get+Elements' },
{ 'url': BASE_PAGE + 'GridSort' },
{ 'url': BASE_PAGE + 'Template' }
]
}, os.path.abspath(__file__))
@property
def results_are_the_same_on_every_page(self):
return F... | _IsDone():
return tab.GetCookieByName('__domperf_finished') == '1'
util.WaitFor(_IsDone, 600, poll_interval=5)
data = json.loads(tab.EvaluateJavaScript('__domperf_result'))
for suite in data['BenchmarkSuites']:
# Skip benchmarks that we didn't actually run this time around.
if... |
ThiefMaster/indico | indico/migrations/versions/20200402_1113_933665578547_migrate_review_conditions_from_settings.py | Python | mit | 2,739 | 0.002556 | """Migrate review conditions from settings
Revision ID: 933665578547
Revises: 02bf20df06b3
Create Date: 2020-04-02 11:13:58.931020
"""
import json
from collections import defaultdict
from uuid import uuid4
from alembic import context, op
from indico.modules.events.editing.models.editable import EditableType
# rev... | e(
| 'INSERT INTO event_editing.review_conditions (type, event_id) VALUES (%s, %s) RETURNING id',
(type_, event_id),
)
revcon_id = res2.fetchone()[0]
for file_type in condition[1]:
conn.execute('''
INSERT INTO e... |
CS2014/USM | usm/autoslug/settings.py | Python | mit | 2,051 | 0.000488 | # coding: utf-8
#
# Copyright (c) 2008—2014 Andy Mikhailenko
#
# This file is part of django-autoslug.
#
# django-autoslug is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README for copying conditions.
#
"""
Dja... | CTION = 'some_app.slugify_func'
# custom function, callable:
AUTOSLUG_SLUGIFY_FUNCTION = some_app.slugify_func
# custom function, defined inline:
AUTOSLUG_SLUGIFY_FUNCTION = lambda slug: 'can i haz %s?' % slug
If no value is given, default value is used.
Default value is one of these dep... | ding on availability in given order:
* `unidecode.unidecode()` if Unidecode_ is available;
* `pytils.translit.slugify()` if pytils_ is available;
* `django.template.defaultfilters.slugify()` bundled with Django.
django-autoslug also ships a couple of slugify functions that use
the translitcodec_ Python libr... |
ellipsis14/dolfin-adjoint | tests_dolfin/test.py | Python | lgpl-3.0 | 3,724 | 0.011547 | #!/usr/bin/env python
import os, os.path
import sys
import subprocess
import multiprocessing
import time
from optparse import OptionParser
test_cmds = {'tlm_simple': 'mpirun -n 2 python tlm_simple.py',
'svd_simple': 'mpirun -n 2 python svd_simple.py',
'gst_mass': 'mpirun -n 2 python gst_mass... | ion("-t", type="string", dest="test_name", help = "To run one specific test, use -t TESTNAME. By default all test are run.")
parser.add_option("-s", dest="short_only", default = False, action="store_true", help = "To run the short tests only, use -s. By default all test are run.")
parser.add_option("--timings", dest="t... | asedir = os.path.dirname(os.path.abspath(sys.argv[0]))
subdirs = [x for x in os.listdir(basedir) if os.path.isdir(os.path.join(basedir, x))]
if options.test_name:
if not options.test_name in subdirs:
print "Specified test not found."
sys.exit(1)
else:
subdirs = [options.test_name]
long_tests = ["viscoe... |
wdmchaft/taskcoach | taskcoachlib/gui/splash.py | Python | gpl-3.0 | 1,689 | 0.003552 | '''
Task Coach - Your friendly task manager
Copyright (C) 2004-2010 Task | Coach developers <[email protected]>
Task Coach 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, or
(at your option) any later ver | sion.
Task Coach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with thi... |
GunnerJnr/_CodeInstitute | Stream-3/Full-Stack-Development/4.Hello-Django-Administration/4.-Wire-Up-A-Model-To-A-Template/challenge_solution/QuoteOfTheDay/Quotes_app/migrations/0001_initial.py | Python | mit | 702 | 0.001425 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-14 11:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name= | 'Quotes',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quoter_first_name', models.CharField(max_length=255)),
('quoter_last_name', models.CharField(max_length=255)),
| ('quote_text', models.CharField(max_length=255)),
],
),
]
|
sameerparekh/pants | src/python/pants/engine/round_manager.py | Python | apache-2.0 | 2,387 | 0.009217 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from collections imp... | """Describes the producer of a given product type."""
class RoundManager(object):
class MissingProductError(KeyError):
"""Indicates a required product type is provided by non-one."""
@staticmethod
def _index_products():
producer_info_by_product_typ | e = defaultdict(set)
for goal in Goal.all():
for task_type in goal.task_types():
for product_type in task_type.product_types():
producer_info = ProducerInfo(product_type, task_type, goal)
producer_info_by_product_type[product_type].add(producer_info)
return producer_info_by_pro... |
lmazuel/azure-sdk-for-python | azure-batch/azure/batch/models/pool_upgrade_os_options.py | Python | mit | 3,129 | 0.00032 | # 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 ... | ciated with the version of the resource
known to the client. The operation will be performed only if the
resource's current ETag on the service exactly matches the value specified
by the client.
:type if_match: str
:param if_none_match: An ETag value associated with the version of the
resour... | :type if_none_match: str
:param if_modified_since: A timestamp indicating the last modified time of
the resource known to the client. The operation will be performed only if
the resource on the service has been modified since the specified time.
:type if_modified_since: datetime
:param if_unmodifi... |
leyondlee/HoneyPy-Docker | HoneyPy-0.6.2/plugins/FTPUnix/FTPUnix.py | Python | gpl-3.0 | 2,806 | 0.029223 | from twisted.internet import protocol
from twisted.python import log
import uuid
import re
class FTPUnix(protocol.Protocol):
localhost = None
remote_host = None
session = None
### START CUSTOM VARIABLES ###############################################################
username = None
UNAUTH, INAUTH = range(... | etPeer()
self.session = uuid.uuid1()
log.msg('%s %s CONNECT %s %s %s %s %s' % (self.session, self.remote_host.type, self.local_host.host, self.local_host.port, self.factory.name, self.remote_host.host, self.remote_host.port))
def clientConnectionLost(self):
sel | f.transport.loseConnection()
def tx(self, data):
log.msg('%s %s TX %s %s %s %s %s %s' % (self.session, self.remote_host.type, self.local_host.host, self.local_host.port, self.factory.name, self.remote_host.host, self.remote_host.port, data.encode("hex")))
self.transport.write(data + '\r\r\n')
def rx(self, data... |
30loops/nova | nova/tests/test_compute.py | Python | apache-2.0 | 59,837 | 0.00137 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); y... | .NOTIFICATIONS = []
def fake_show(meh, context, id):
return {'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1}}
self.stubs.Set(fake_image._FakeImageService, 'show', fake_show)
def _create_instance(self, params=None):
"""Create a test instance"""
| if not params:
params = {}
inst = {}
inst['image_ref'] = 1
inst['reservation_id'] = 'r-fakeres'
inst['launch_time'] = '10'
inst['user_id'] = self.user_id
inst['project_id'] = self.project_id
type_id = instance_types.get_instance_type_by_name('m1.... |
pam-bot/SMSBeds | lib/jinja/constants.py | Python | gpl-2.0 | 1,622 | 0 | # -*- coding: utf-8 -*-
"""
jinja.constants
~~~~~~~~~~~~~~~
Various constants.
:copyright: 2007 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
#: list of lorem ipsum words used by the lipsum() helper function
LOREM_IPSUM_WORDS = u'''\
a ac accumsan ad adipiscing aenean aliqu... | nsequat conubia convallis cras cubilia cum curabitur curae cursus dapibus
diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend
elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames
faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse ha | c
hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum
justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem
luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie
mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non
nonummy no... |
c3cashdesk/c6sh | src/tests/troubleshooter/test_troubleshooter_views_ping.py | Python | agpl-3.0 | 624 | 0 | import pytest
from postix.core.models import Ping
from ..factories import cashdesk_factory, ping_factory
@pytest.mark.django_db
def test_troubleshooter_ping_view(troubleshooter_client):
[ping_factory(ponged=(index % | 3 != 0)) for index in range(10)]
desk = cashdesk_factory()
assert Ping.objects.count() == 10
response = troubleshooter_client.get('/troubleshooter/ping/')
assert response.status_code == 200
response = troubleshooter_client.post(
'/troubleshooter/ping/', {'cashdesk': desk.pk}, follow=True
... | ts.count() == 11
|
apacha/MusicSymbolClassifier | ModelTrainer/reporting/TrainingHistoryPlotter.py | Python | mit | 3,064 | 0.006854 | import numpy
from tensorflow.keras.callbacks import History
from matplotlib import pyplot
class TrainingHistoryPlotter:
@staticmethod
def plot_history(history: History, file_name: str, show_plot: bool = False):
epoch_list = numpy.add(history.epoch, 1) # Add 1 so it starts with epoch 1 instead of 0
... | al_output_bounding_box_loss", "Validation loss", "upper right")
TrainingHistoryPlotter.add_subplot(epoch_list, fig, history, 224, "Bounding-Box Accuracy",
"output_bounding_box_acc", "Training accuracy",
| "val_output_bounding_box_acc", "Validation accuracy", "lower right")
# pyplot.subplots_adjust(wspace=0.1)
pyplot.tight_layout()
pyplot.savefig(file_name)
if show_plot:
pyplot.show()
@staticmethod
def add_subplot(epoch_... |
neuropoly/spinalcordtoolbox | dev/denoise/ornlm/wavelet/cshift3D.py | Python | mit | 224 | 0.0625 | import nu | mpy as np
def cshift3D(x, m, d):
| s=x.shape
idx=(np.array(range(s[d]))+(s[d]-m%s[d]))%s[d]
if d==0:
return x[idx,:,:]
elif d==1:
return x[:,idx,:]
else:
return x[:,:,idx];
|
tomjelinek/pcs | pcs_test/tier0/lib/communication/test_qdevice_net.py | Python | gpl-2.0 | 690 | 0 | from uni | ttest import TestCase
class GetCaCert(TestCase):
"""
tested in:
pcs_test.tier0.lib.commands.test_quorum.AddDeviceNetTest
"""
class ClientSetup(TestCase):
"""
tested in:
pcs_test.tier0.lib.commands.test_quorum.AddDeviceNetTest
"""
class SignCertificate(TestCase):
"""
... |
pcs_test.tier0.lib.commands.test_quorum.AddDeviceNetTest
"""
class ClientImportCertificateAndKey(TestCase):
"""
tested in:
pcs_test.tier0.lib.commands.test_quorum.AddDeviceNetTest
"""
class ClientDestroy(TestCase):
"""
tested in:
pcs_test.tier0.lib.commands.test_quor... |
armikhael/software-center | softwarecenter/backend/channel.py | Python | gpl-3.0 | 12,773 | 0.003523 | # Copyright (C) 2010 Canonical
#
# Authors:
# Gary Lasker
# Michael Vogt
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will b... | _channel = None
other_channels = []
unknown_channel = []
local_channel = None
for (channel_name, channel_origin) in other_channel_list:
if not channel_name:
unknown_channel.append(SoftwareChannel(channel_name,
... | None,
installed_only=installed_only))
elif channel_name == distro_channel_name:
dist_channel = (SoftwareChannel(distro_channel_name,
channel_origin,
... |
tancredi/python-console-snake | snake/config.py | Python | mit | 282 | 0 |
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
|
encukou/qdex | qdex/delegate.py | Python | mit | 2,413 | 0.00083 | #!/usr/bin/env python
# Encoding: UTF-8
"""Part of qdex: a Pokédex using PySide and veekun's pokedex library.
A query models for pokémon
"""
from PySide import QtGui, QtCore
Qt = QtCore.Qt
class PokemonDelegate(QtGui.QStyledItemDelegate):
"""Delegate for a Pokémon
Shows summary information when the group o... | def sizeHint(self, option, index):
option.decorationSize = QtCore.QSize(0, 0)
self.view.model()._hack_small_icons = True
hint = super(PokemonNameDelegate, self).sizeHint(option, index)
self.view.model()._hack_small_icons = False
return hint
def paint(self, painter, option... | option.decorationAlignment = Qt.AlignBottom | Qt.AlignHCenter
super(PokemonNameDelegate, self).paint(painter, option, index)
|
projectscara2014/scara | working_directory/setup/block_position_setup_main.py | Python | mit | 5,886 | 0.040605 | #------------------------------------ SETUP ----------------------------------------------
import sys
WORKING_DIRECTORY = ''
SPLITTING_CHARACTER = ''
if sys.platform.startswith('win') :
SPLITTING_CHARACTER = '\{}'.format('')
elif sys.platform.startswith('darwin') :
SPLITTING_CHARACTER = '/'
def setup() :
def l... | arduino2.place()
elif keypress == 116 :
# "t" pressed
arduino2.pick()
entire_block_ | position_list = this_to_that.calculate_entire_block_position_list(dynamixel.GO_TO_DYNA_1_POS,\
dynamixel.GO_TO_DYNA_2_POS,arduino2.GO_TO_SERVO_POS)
print(entire_block_position_list)
if(dynamixel.GO_TO_DYNA_2_POS>0):
dynamixel.GO_TO_DYNA_1_POS = entire_block_position_list[0]
dynamixel.GO_TO_DYNA_2_POS ... |
vertigo235/Sick-Beard-XEM | sickbeard/clients/deluge.py | Python | gpl-3.0 | 8,453 | 0.009464 | # Author: Mr_Orange <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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... | .response.json()['error']
def _set_torrent_ratio(self, result):
if sickbeard.TORRENT_RATIO:
post_data = json.dumps({"method": "core.set_torrent_stop_at_ratio",
"params": [result.hash, True],
"id": 5
... | })
self._request(method='post', data=post_data)
post_data = json.dumps({"method": "core.set_torrent_stop_ratio",
"params": [result.hash,float(sickbeard.TORRENT_RATIO)],
"id": 6
... |
crystal150/CS350 | collector.py | Python | mit | 17,514 | 0.016844 | import io
import csv
import requests
import datetime
import time
from bs4 import BeautifulSoup
TRAIN_FILE = "train.csv"
DEFAULT_INTERVAL = 1800
TRAIN_FILE_HEAD = ["Insult", "Date", "Comment"]
def writeCsv(fname, text, delimiter = ","):
prev_data = list()
try:
fil... | nt.sort()
#print(prev_comment)
duplicated = [False] * len(text)
for i in range(0, len(text)):
if (text[i][2] | in prev_comment):
duplicated[i] = True
#print(duplicated)
try:
file = open(fname, "w")
writer = csv.writer(file, delimiter = delimiter, dialect = "excel")
writer.writerow(TRAIN_FILE_HEAD)
... |
hanlind/nova | nova/policies/security_groups.py | Python | apache-2.0 | 1,102 | 0 | # Copyright 2016 Cloudbase Solutions Srl
# 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 o | r agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_policy import poli... |
pblottiere/QGIS | python/plugins/processing/algs/gdal/rasterize_over.py | Python | gpl-2.0 | 5,222 | 0.002489 | # -*- coding: utf-8 -*-
"""
***************************************************************************
rasterize_over.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
********... | **************
"""
__author__ = 'Alexander Bruy'
__date__ = 'September 2013'
__copyright__ = '(C) 2013, Alexander Bruy'
import os
from qgis.PyQt.QtGui import QIcon
from qgis.core import (QgsRasterFileWriter,
QgsProcessingException,
Qgs | ProcessingParameterDefinition,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterField,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterNumber,
QgsProcessingParameterString,
... |
LeeKamentsky/CellProfiler | tutorial/example1e_groups.py | Python | gpl-2.0 | 8,354 | 0.003232 | '''<b>Example1e</b> demonstrates SettingsGroup
<hr>
There are many circumstances where it would be useful to let a user specify
an arbitrary number of a group of settings. For instance, you might want to
sum an arbitrary number of images together in your module or perform the
same operation on every listed image or obj... | or += group.addend.value
accumulator += group.multiplicand.value
#
# You can put strings, numbers, lists, tuples, dictionaries and
# | numpy arrrays into workspace_display data as well as lists,
# tuples and dictionaries of the above.
#
# The workspace will magically transfer these to itself when
# display() is called - this might happen in a different process
# or possibly on a different machine.
#
... |
patta42/pySICM | pySICM/_runGui.py | Python | gpl-3.0 | 969 | 0.001032 | # Copyright (C) 2015 Patrick Happel <[email protected]>
#
# This file is part of pySICM.
#
# pySICM is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Pub | lic License as published by the Free Software
# Foundation, either version 2 of the License, or (at your option | ) any later
# version.
#
# pySICM is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public... |
StackStorm/python-mistralclient | mistralclient/tests/unit/v2/test_cli_members.py | Python | apache-2.0 | 3,091 | 0 | # Copyright 2016 Catalyst IT Limited
#
# 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... | member_cmd.Create,
app_args=[MEMBER_DICT['resource_id'], MEMBER_DICT['resource_type'],
MEMBE | R_DICT['member_id']]
)
self.assertEqual(
('456', 'workflow', '1111', '2222', 'pending', '1', '1'),
result[1]
)
def test_update(self):
self.client.members.update.return_value = MEMBER
result = self.call(
member_cmd.Update,
app... |
ichuang/sympy | sympy/core/cache.py | Python | bsd-3-clause | 3,434 | 0.004077 | """ Caching facility for SymPy """
# TODO: refactor CACHE & friends into class?
# global cache registry:
CACHE = [] # [] of
# (item, {} or tuple of {})
from sympy.core.decorators import wraps
def print_cache():
"""print cache content"""
for item, cache in CACHE:
item = str(item)
... | s):
# always call function itself and compare it with cached version
r1 = func (*args, **kw_args)
r2 = cfunc(*args, **kw_args)
# try to see if the result is immutable
#
# this works because:
#
# hash([1,2,3]) -> raise TypeError
# hash({'a'... | ((1,[2,3])) -> raise TypeError
#
# hash((1,2,3)) -> just computes the hash
hash(r1), hash(r2)
# also see if returned values are the same
assert r1 == r2
return r1
return wrapper
def _getenv(key, default=None):
from os import getenv
return gete... |
jaumemarti/l10n-spain-txerpa | account_balance_reporting/account_balance_reporting_template.py | Python | agpl-3.0 | 9,107 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account balance reporting engine
# Copyright (C) 2009 Pexego Sistemas Informáticos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | .reporting.template.line']
# Read the current item data:
template = self.browse(cr, uid, rec_id, context=context)
# Create the template
new_id = self.create(
cr, uid, {
'name': '%s*' % template.name,
'type': 'user', # Copies are always user te... | t_xml_id.id,
'description': template.description,
'balance_mode': template.balance_mode,
'line_ids': None,
}, context=context)
# Now create the lines (without parents)
for line in template.line_ids:
line_obj.create(
... |
vadimadr/generator-djdj | generators/app/templates/django_project_template/wsgi.py | Python | mit | 428 | 0 | """
WSGI config for <%= slug %> | 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.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
... | <%= slug %>.settings.local")
application = get_wsgi_application()
|
linsalrob/PyFBA | PyFBA/fba/bounds.py | Python | mit | 4,803 | 0.003748 | import sys
from PyFBA import lp, log_and_message
def reaction_bounds(reactions, reactions_with_upsr, media, lower=-1000.0, mid=0.0, upper=1000.0, verbose=False):
"""
Set the bounds for each reaction. We set the reactions to run between
either lower/mid, mid/upper, or lower/upper depending on whether the
... | r in reactions:
direction = reactions[r].direction
else:
sys.stderr.write("Did not find {} in reactions\n".format(r))
direction = "="
"""
RAE 16/6/21
We no longer use this block to check for media components. Instead, we us the uptake_and_secre | tion_reactions
in external_reactions.py to do so.
We assume that if you provide uptake_and_secretion_reactions you have already culled them for the media, though
perhaps we should add a test for that.
"""
if False and (reactions[r].is_uptake_secretion or reacti... |
henry-chao/moltres-radio | dbInit.py | Python | mit | 668 | 0.013473 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://moltres:sertlom@localhost/moltres_radio'
db = SQLAlchemy(app)
class UserDAO(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(), primary_key=True)
active =... | umn(db.String())
password = db.Column(db.String())
salt = db.Column(db.String())
def __init__(self, username, active, activationKey, password, salt):
self.username = u | sername
self.active = active
self.activationKey = activationKey
self.password = password
self.salt = salt
|
zeroq/amun | vuln_modules/vuln-arkeia/arkeia_shellcodes.py | Python | gpl-2.0 | 60 | 0 | arkeia_request_stage_1 = "\x00\x | 4d\x00\x03\x00\x01\x03\x | e8"
|
dpgaspar/Flask-AppBuilder | flask_appbuilder/tests/security/test_auth_ldap.py | Python | bsd-3-clause | 41,672 | 0.000648 | import logging
import os
import unittest
from unittest.mock import Mock, patch
from flask import Flask
from flask_appbuilder import AppBuilder, SQLA
from flask_appbuilder.security.manager import AUTH_LDAP
import jinja2
import ldap
from mockldap import MockLdap
from ..const import USERNAME_ADMIN, USERNAME_READONLY
l... | "test"]})
ou_users = ("ou=users, | o=test", {"ou": ["users"]})
ou_groups = ("ou=groups,o=test", {"ou": ["groups"]})
user_admin = (
"uid=admin,ou=users,o=test",
{"uid": ["admin"], "userPassword": ["admin_password"]},
)
user_alice = (
"uid=alice,ou=users,o=test",
{
"uid": ["alice"],
"... |
ivanlyon/exercises | test/test_k_hardwoodspecies.py | Python | mit | 1,481 | 0.00135 | import io
import unittest
from unittest.mock import patch
from kattis import k_hardwoodspecies
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run an... | 448276
White Oak 10.344828
Willow 3.448276
Yellow Birch 3.448276
'''
with patch('sys.stdin', io.StringIO(inputs[1:])) as stdin,\
patch('sys.stdout', new_callable=io.StringIO) as s | tdout:
k_hardwoodspecies.main()
self.assertEqual(stdout.getvalue(), outputs[1:])
self.assertEqual(stdin.read(), '')
###############################################################################
if __name__ == '__main__':
unittest.main()
|
internship2016/sovolo | app/user/templatetags/user_tags.py | Python | mit | 902 | 0 | from django import template
register = template.Library()
@register.inclusion_tag('user/user_list.html', takes_context=True)
def user_list(context, users, title):
info = {'users': users, 'title': title}
if 'event' in context:
info['object'] = context['event']
return info
@register.inclusion_tag... | ist_large(context, | users, title):
return {'users': users, 'title': title}
@register.inclusion_tag('user/template_skilllist.html', takes_context=True)
def skill_list(context, skills, title):
request = context['request']
return {
'skills': skills,
'title': title,
'user': request.user,
}
@registe... |
Tan0/ironic | ironic/drivers/modules/ipmitool.py | Python | apache-2.0 | 44,249 | 0.000023 | # coding=utf-8
# Copyright 2012 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 NTT DOCOMO, INC.
# Copyright 2014 International Business Machines Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance ... | pported
return TIMING_SUPPORT
def _console_pwfile_path(uuid):
"""Return the file path for storing the ipmi password for a console."""
file_name = "%(uuid)s.pw" % {'uuid': uuid}
return os.path.join(CONF.tempdir, file_name)
@contextlib.contextmanager
def _make_password_file(password):
"""Makes... | porary file
:raises: PasswordFileFailedToCreate from creat |
marcharper/stationary | stationary/utils/math_helpers.py | Python | mit | 5,555 | 0.00072 | import numpy
from numpy import log
try:
from scipy.misc import logsumexp
except ImportError:
from numpy import logaddexp
logsumexp = logaddexp.reduce
def slice_dictionary(d, N, slice_index=0, slice_value=0):
"""
Take a three dimensional slice from a four dimensional
dictionary.
"""
s... | turn 0.5 * numpy.dot((x - y), (x - y))
return d
if q == 1:
return kl_divergence
if q == 2:
def d(x, y):
s = 0.
| for i in range(len(x)):
s += log(x[i] / y[i]) + 1 - x[i] / y[i]
return -s
return d
q = float(q)
def d(x, y):
s = 0.
for i in range(len(x)):
s += (numpy.power(y[i], 2 - q) - numpy.power(x[i], 2 - q)) / (2 - q)
s -= numpy.pow... |
flavour/eden | modules/templates/historic/CRMT/controllers.py | Python | mit | 3,111 | 0.007715 | # -*- coding | : utf-8 -*-
from gluon import current
#from gluon.html import *
from gluon.storage import Storage
from s3 import S3CustomController
THEME = "historic.CRMT"
# =============================================================================
class index(S3CustomController):
""" Custom Home Page """
def __call__(... | query = (atable.deleted == False)
output["total_activities"] = db(query).count()
#gtable = s3db.gis_location
#query &= (atable.location_id == gtable.id)
ogtable = s3db.org_group
ltable = s3db.project_activity_group
query &= (atable.id == ltable.activity_id) & \
... |
diego0020/PySurfer | examples/plot_freesurfer_normalization.py | Python | bsd-3-clause | 1,238 | 0 | """
Plot Freesurfer Normalization
=============================
This example shows how PySurfer can be used t | o examine the quality of
Freesurfer's curvature-driven normalization to a common template.
We are going to plot the contour of the subject's curvature estimate after
transforming that map into the common space (this step is performed outside
of PySurfer using the Freesurfer program ``mri_surf2surf``).
With a perfect ... | lines should follow the light/dark
gray boundary on the fsaverage surface. Large deviations may reflect problems
with the underlying data that you should investigate.
"""
import nibabel as nib
from surfer import Brain
print(__doc__)
brain = Brain("fsaverage", "both", "inflated")
for hemi in ["lh", "rh"]:
# Th... |
sebp/scikit-survival | tests/test_column.py | Python | gpl-3.0 | 14,897 | 0.002215 | from collections import OrderedDict
import numpy
from numpy.testing import assert_array_almost_equal, assert_array_equal
import pandas
import pandas.testing as tm
import pytest
from sksurv import column
@pytest.fixture()
def numeric_data():
data = pandas.DataFrame(numpy.arange(50, dtype=float).reshape(10, 5))
... | 8, 9]
assert_array_equal(non_numeric_data_frame.iloc[non_nan_idx, :].value | s,
result[:, numeric_data_frame.shape[1]:][non_nan_idx, :])
class TestEncodeCategorical:
@staticmethod
def test_series_categorical():
input_series = pandas.Series(pandas.Categorical.from_codes([1, 1, 0, 2, 0, 1, 2, 1, 2, 0, 0, 1, 2, 2],
... |
slundberg/shap | shap/explainers/other/_maple.py | Python | mit | 11,403 | 0.007717 | from .._explainer import Explainer
import numpy as np
from sklearn.model_selection import train_test_split
class Maple(Explainer):
""" Simply wraps MAPLE into the common SHAP interface.
Parameters
----------
model : function
User supplied function that takes a matrix of samples (# samples x # ... | ear_model import Ridge
from sklearn.metrics import mean_squared_error
import numpy as np
class MAPLE:
def | __init__(self, X_train, MR_train, X_val, MR_val, fe_type = "rf", fe=None, n_estimators = 200, max_features = 0.5, min_samples_leaf = 10, regularization = 0.001):
# Features and the target model response
self.X_train = X_train
self.MR_train = MR_train
self.X_val = X_val
self.MR_... |
redhat-cip/python-dciclient | dciclient/v1/shell_commands/component.py | Python | apache-2.0 | 2,918 | 0.001028 | # -*- encoding: utf-8 -*-
#
# Copyright 2015-2016 Red Hat, 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 applic... | rgs, k) for k in ["id", "file_id", "target"]}
return component.file_download(context, **params)
def file_list(context, args):
params = {k: getattr(args, k) for k in ["id", "sort", "limit", "offset", "where"]}
return component.file_l | ist(context, **params)
def file_delete(context, args):
component.file_delete(context, id=args.id, file_id=args.file_id, etag=args.etag)
def update(context, args):
params = {
k: getattr(args, k)
for k in [
"name",
"type",
"canonical_project_name",
... |
overtherain/scriptfile | software/googleAppEngine/lib/PyAMF/doc/tutorials/examples/actionscript/ohloh/python/client.py | Python | mit | 1,319 | 0.000758 | #!/usr/bin/python
#
# Copyright (c) The PyAMF Project.
# See LICENSE for details.
"""
This is an example of using the Ohloh API from a Python client.
Detailed information can be found at the Ohloh website:
http://www.ohloh.net/api
This example uses the ElementTree library for XML parsing
(included in Python 2.... | i_key = sys.argv[1]
email = sys.argv[2]
else:
print "Usage: client.py <api-key> <email-address>"
sys.exit()
elem = ohloh.getAccount(email, api_key)
# Output all the immediate child properties of an Account
for node in elem.find("result/account"):
if node.tag == "kudo_score":
print "%s:" % ... | print "%s:\t%s" % (node.tag, node.text)
|
estaban/pyload | module/plugins/hooks/UnSkipOnFail.py | Python | gpl-3.0 | 4,031 | 0.000248 | # -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in... | tus name
(i.e. "queued" for this Plugin)
It creates a temporary PyFile object using
"link" data, changes its status, and tells
the core.files-manager to save its data.
"""
pyfile = PyFile(self.core.files,
link.fid,
... | ze,
link.status,
link.error,
link.plugin,
link.packageID,
link.order)
pyfile.setStatus(new_status)
self.core.files.save()
pyfile.release()
|
MSEMJEJME/Get-Dumped | renpy/text/text.py | Python | gpl-2.0 | 43,754 | 0.010011 | # Copyright 2004-2012 Tom Rothamel <[email protected]>
#
# 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, m... | tware,
# and to | permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED,... |
AsimmHirani/ISpyPi | tensorflow/contrib/tensorflow-master/tensorflow/contrib/linalg/python/kernel_tests/linear_operator_udvh_update_test.py | Python | apache-2.0 | 12,056 | 0.007963 | # Copyright 2016 The TensorFlow Authors. 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 applica... | this operator makes use of inversion
# and determinant lemmas that are known to have stability issues.
return [(0, 0), (1, 1), (1, 3, 3), (3, 4, 4), (2, 1, 4, 4), (2, 10, 10)]
def _operator_and_mat_and_feed_dict(self, shape, dtype, use_placeholder):
# Recall A = L + UDV^H
shape = list(shape)
| diag_shape = shape[:-1]
k = shape[-2] // 2 + 1
u_perturbation_shape = shape[:-1] + [k]
diag_perturbation_shape = shape[:-2] + [k]
# base_operator L will be a symmetric positive definite diagonal linear
# operator, with condition number as high as 1e4.
base_diag = linear_operator_test_util.ra... |
tjm-1990/blueking | conf/default.py | Python | gpl-3.0 | 11,273 | 0.000861 | # -*- coding: utf-8 -*-
"""
Django settings for app-framework project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/r... | ===========================================================================
# 在蓝鲸智云开发者中心 -> 点击应用ID -> 基本信息 中获取 APP_ID 和 APP_TOKEN 的值
APP_ID = 'hello-world'
APP_TOKEN = 'c52de43b-ef43-49b2-8268-b53c5 | 271750a'
# 蓝鲸智云开发者中心的域名,形如:http://paas.bking.com
BK_PAAS_HOST = 'http://paas.bking.com'
# 是否启用celery任务
IS_USE_CELERY = True
# 本地开发的 celery 的消息队列(RabbitMQ)信息
BROKER_URL_DEV = 'amqp://guest:[email protected]:5672/'
# TOCHANGE 调用celery任务的文件路径, List of modules to import when celery starts.
CELERY_IMPORTS = (
'home_appli... |
carljm/django-adminfiles | adminfiles/models.py | Python | bsd-3-clause | 3,651 | 0.003013 | import os
import mimetypes
from django.conf import settings as django_settings
from django.db import models
from django.template.defaultfilters import slugify
from django.core.files.images import get_image_dimensions
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models impor... | content_type, self.sub_type] = mime_type.split('/')
except:
self.content_type = 'text'
sel | f.sub_type = 'plain'
super(FileUpload, self).save()
def insert_links(self):
links = []
for key in [self.mime_type(), self.content_type, '']:
if key in settings.ADMINFILES_INSERT_LINKS:
links = settings.ADMINFILES_INSERT_LINKS[key]
break
fo... |
mayfieldrobotics/ros-webrtc | test/integration/ros_coverage.py | Python | bsd-3-clause | 652 | 0.001534 | import contextlib
import os
import shutil
import sys
import rostest
@contextlib.contextmanager
def ros_coverage():
"""
https://github.com/ros/ros_comm/issues/558
"""
coverage_mode = '--cov' | in sys.argv
if co | verage_mode:
sys.argv.remove('--cov')
src = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.coveragerc')
dst = os.path.join(os.getcwd(), '.coveragerc')
if not os.path.exists(dst):
shutil.copyfile(src, dst)
rostest._start_coverage(['ros_webrtc'])
try:
... |
mysidewalk/training-django | 01-middling-python/01-slicing/solutions/02-gradebook-solution.py | Python | mit | 2,924 | 0.00342 | class GradeBook(object):
""" Stores and retrieves grades for students. Slicing allows grades to be retrieved by a range
of dates specified as a zero based integer for the day of the year
"""
def __init__(self, name='Unknown Class Gradebook', grades=[]):
""" Set a name for the grade book and ... | else:
self.grades[key] = self.grades[key]
return grades_between_dates
def add_grades(self, new_grades):
""" Add the list of new grades to the | existing list of grades
"""
self.grades = self.grades + new_grades
# Define the list of grades to be used
raw_grades = [
{'student_name': 'Billy', 'date': 14, 'grade': 87},
{'student_name': 'Melissa', 'date': 14, 'grade': 90},
{'student_name': 'Sarah', 'date': 14, 'grade': 83},
{'stude... |
lob/lob-python | lob/__init__.py | Python | mit | 410 | 0 | # Resources
from lob.resource import (
Address,
BankAccount,
BillingGroup,
BulkUSVerification,
BulkIntlVerification,
Ca | rd,
CardOrder,
Check,
Letter,
Postcard,
SelfMailer,
USAutocompletion,
USReverseGeocodeLookup,
USVerification,
USZipLookup,
IntlVerification
)
from lob.version import VERSION
api_key = None
api_ | base = 'https://api.lob.com/v1'
|
idjaw/keystone | keystone/tests/unit/test_v3.py | Python | apache-2.0 | 51,696 | 0 | # Copyright 2013 OpenStack 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
#
# Unless required by applicable law or agreed to in... | def remove_generated_paste_config(self):
try:
unit.remov | e_generated_paste_config(self.EXTENSION_TO_ADD)
except AttributeError:
pass
def setUp(self, app_conf='keystone'):
"""Setup for v3 Restful Test Cases.
"""
new_paste_file = self.generate_paste_config()
self.addCleanup(self.remove_generated_paste_config)
if... |
IdiosyncraticDragon/Reading-Notes | Python Parallel Programming Cookbook_Code/Chapter 3/kill_a_process.py | Python | apache-2.0 | 588 | 0.020408 | #kill a Process Chapter 3: Process Based Parallelism
import multiprocessing
import time
def foo():
print ('Starting function')
time.sleep(0.1)
print ('Finished function')
if __name__ == '__main__':
p = multiprocessing.Process(target=foo)
print ('Process before execut | ion:', p, p.is_alive())
p.start()
print ('Process running:', p, p.is_alive())
p.te | rminate()
print ('Process terminated:', p, p.is_alive())
p.join()
print ('Process joined:', p, p.is_alive())
print ('Process exit code:', p.exitcode)
|
spulec/moto | tests/test_core/test_mock_regions.py | Python | apache-2.0 | 2,220 | 0.000901 | import boto3
import mock
import os
import pytest
from moto import mock_dynamodb2, mock_sns, settings
from unittest import SkipTest
@mock_sns
def test_use_invalid_region():
if settings.TEST_SERVER_MODE:
raise SkipTest("ServerMode will throw different errors")
client = boto3.client("sns", region_name="a... | region"})
@mock.patch.dict(os.environ, {"MOTO_ALLOW_NONEXISTENT_REGION": "trUe"})
def test_use_unknown_region_from_env_but_allow_it():
if settings.TEST_SERVER_MODE:
raise SkipTest("Cannot set environemnt variables in ServerMode")
client = boto3.client("sns")
client.list_platform_applicatio | ns()["PlatformApplications"].should.equal([])
@mock_dynamodb2
@mock.patch.dict(os.environ, {"MOTO_ALLOW_NONEXISTENT_REGION": "trUe"})
def test_use_unknown_region_from_env_but_allow_it__dynamo():
if settings.TEST_SERVER_MODE:
raise SkipTest("Cannot set environemnt variables in ServerMode")
dynamo_db = ... |
tensorflow/probability | tensorflow_probability/python/distributions/finite_discrete.py | Python | apache-2.0 | 14,488 | 0.004694 | # Copyright 2018 The TensorFlow Probability Authors.
#
# 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 o... | eps(dtype))),
is_preferred=False))
# pylint: enable=g-long-lambda
@property
def outcomes(self):
return self._outcomes
@property
def logits(self):
"""Input argument `logits`."""
return self._c | ategorical.logits
@property
def probs(self):
"""Input argument `probs`."""
return self._categorical.probs
def _event_shape_tensor(self):
return tf.constant([], dtype=tf.int32)
def _event_shape(self):
return tf.TensorShape([])
def _cdf(self, x):
x = tf.convert_to_tensor(x, name='x')
... |
superphy/backend | app/modules/loggingFunctions.py | Python | apache-2.0 | 1,056 | 0.000947 | #!/usr/bin/env python
"""
Set up the logging
"""
import logging
import tempfile
import os
def initialize_logging():
"""
Set up the screen and file logging.
:return: The log filename
"""
# set up DEBUG logging to file, INFO logging to STDERR
log_file = os.path.join(tempfile.gettempdir()... | atter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
# set up logging to file - see previous sec | tion for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=log_file,
filemode='w')
# define a Handler which writes INF... |
google/timesketch | timesketch/lib/aggregators/term.py | Python | apache-2.0 | 7,953 | 0.000251 | # Copyright 2019 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... | 'display': True
}
]
@property
def chart_title(self):
"""Returns a title for the chart."""
if self.field:
return 'Top filtered results for "{0:s}"'.format(self.field)
return 'Top results for an unknown field after filtering'
# pylint: disable=arguments-di... | |
fbradyirl/home-assistant | homeassistant/components/streamlabswater/sensor.py | Python | apache-2.0 | 3,962 | 0.000252 | """Support for Streamlabs Water Monitor Usage."""
from datetime import timedelta
from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN
from homeassistant.const import VOLUME_GALLONS
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
DEPENDENCIES = ... | StreamLabsDailyUsage(Entity):
"""Monitors the daily water usage."""
def __init__(self, location_name, streamlabs_usage_data):
"""Initialize the daily water usage device."""
self._location_name = location_name
self._streamlabs_usage_data = streamlabs_usage_data
self._state = Non... | @property
def icon(self):
"""Return the daily usage icon."""
return WATER_ICON
@property
def state(self):
"""Return the current daily usage."""
return self._streamlabs_usage_data.get_daily_usage()
@property
def unit_of_measurement(self):
"""Return gallons a... |
PressLabs/cobalt | src/utils/service.py | Python | apache-2.0 | 941 | 0.001063 | # Copyright 2016 Presslabs SRL
#
# 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 agreed to in writing,... | der the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from abc import ABC, abstractmethod
class Service(ABC):
"""Abstract class for a se... | """Abstract start method, responsible for starting the service."""
pass
@abstractmethod
def stop(self):
"""Abstract stop method, responsible for gracefully stop the service."""
pass
|
DayGitH/Python-Challenges | DailyProgrammer/DP20160622B.py | Python | mit | 1,931 | 0.000518 | """
[2016-06-22] Challenge #272 [Intermediate] Dither that image
https://www.reddit.com/r/dailyprogrammer/comments/4paxp4/20160622_challenge_272_intermediate_dither_that/
# Description
[Dithering](https://en.wikipedia.org/wiki/Dither) is the intentional use of
noise to reduce the error of compression. If you start wi... | , I suggest picking a [Netpbm](https://en.wikipedia.org/wiki/Netpbm)
format, which is easy to read.
# Output
Output a two-color (e.g. Black and White) dithered image in your choice of
format. Again, I suggest picking a Netpbm format, which is easy to write.
# Notes
* [Here](http://www.tannerhelland.com/4660/dithering-e... | code/)
is a good resource for dithering algorithms.
# Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
Thanks to /u/skeeto for this [challenge idea]
(https://www.reddit.com/r/dailyprogrammer_ideas/comments/4nt7rp)
"""
def main():
pass
if __name__ == "__main__":
main()... |
jcolekaplan/WNCYC | src/main/api/getBuildingId.py | Python | mit | 1,479 | 0.006761 | import boto3
from decEncoder import *
from DynamoTable import *
def handler(event, context):
"""Dynamo resource"""
buildingTable = DynamoTable('Buildings')
return getBuildingId(event, buildingTable)
"""Lambda handler function for /buildings/{buildingId} API call
Returns building with the buildingId spe... | buildingIdVal)
if response.get('Item'):
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(response.get('Item'), cls | =DecimalEncoder)
}
else:
"""Error if not found"""
return {
'statusCode': 404,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Building not found'})
}
else:
"""No path parame... |
KaranToor/MA450 | google-cloud-sdk/lib/third_party/prompt_toolkit/terminal/win32_input.py | Python | apache-2.0 | 12,797 | 0.000469 | from __future__ import unicode_literals
from ctypes import windll, pointer
from ctypes.wintypes import DWORD
from six.moves import range
from prompt_toolkit.key_binding.input_processor import KeyPress
from prompt_toolkit.keys import Keys
from prompt_toolkit.mouse_events import MouseEventType
from prompt_toolkit.win32_... | ields `KeyPress` objects from the input records.
"""
for i in range(read.value):
ir = input_records[i]
# Get the right EventType from the EVENT_RECORD.
# (For some reason the Windows console application 'cmder'
# [http://gooseberrycreative.com/cmder/] can... | tTypes[ir.EventType])
# Process if this is a key event. (We also have mouse, menu and
# focus events.)
if type(ev) == KEY_EVENT_RECORD and ev.KeyDown:
for key_press in self._event_to_key_presses(ev):
yield key_press
... |
puttarajubr/commcare-hq | corehq/apps/mach/api.py | Python | bsd-3-clause | 1,569 | 0.003824 | import urllib
from django.conf import settings
import urllib2
from corehq.apps.sms.mixin import SMSBackend
from dimagi.ext.couchdbkit import *
from corehq.apps.mach.forms import MachBackendForm
MACH_URL = "http://smsgw.a2p.mme.syniverse.com/sms.php"
class MachBackend(SMSBackend):
account_id = StringProperty()
... | return (1.0 / self.max_sms_per_second)
def send(self, msg, delay=True, *args, **kwargs):
params = {
"id" : self.account_id,
"pw" : self.password,
"snr" : self.sender_id,
"dnr" : msg.phone_number,
}
try:
text = msg.text.enco... | icodeEncodeError:
params["msg"] = msg.text.encode("utf-16-be").encode("hex")
params["encoding"] = "ucs"
url = "%s?%s" % (MACH_URL, urllib.urlencode(params))
resp = urllib2.urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read()
return resp
|
informatics-isi-edu/microscopy | rbk/worker/delete_youtube/clientlib/rbk_delete_youtube_lib/client.py | Python | apache-2.0 | 9,450 | 0.006667 | #!/usr/bin/python
#
# Copyright 2017 University of Southern California
#
# 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 require... | outube_delete(youtube_uri)
if youtube_deleted == Tru | e:
self.logger.debug('SUCCEEDED deleted from YouTube the video with the URL: "%s".' % (youtube_uri))
columns = ["Youtube_Deleted", "Processing_Status"]
columns = ','.join([urlquote(col) for col in columns])
url = '/attributegroup/Common:De... |
valexandersaulys/airbnb_kaggle_contest | venv/lib/python3.4/site-packages/Theano-0.7.0-py3.4.egg/theano/sandbox/gpuarray/tests/test_conv_cuda_ndarray.py | Python | gpl-2.0 | 27,571 | 0.001197 | """
Tests for GPU convolution
"""
from __future__ import print_function
import sys
import time
import unittest
import numpy
from six.moves import xrange
import theano
from theano import tensor
from theano.tests.unittest_tools import seed_rng
# We let that import do the init of the back-end if needed.
from .config im... | e[0], ::kern_stride[1]]
npy_kern = npy_kern[:, :, | ::kern_stride[0], ::kern_stride[1]]
t2 = None
rval = True
try:
t0 = time.time()
cpuval = py_conv(npy_img, npy_kern, mode, subsample)
t1 = time.time()
i = gftensor4()
k = gftensor4()
op = GpuConv(border_mode=mode,
subsample=subsample,
... |
cybertoast/flask-mongoutils | loader.py | Python | bsd-3-clause | 65 | 0 | from fl | ask.ext.mongoeng | ine import MongoEngine
db = MongoEngine()
|
schanezon/webapp | test.py | Python | apache-2.0 | 278 | 0.010791 | from flask import Flask, redirect, abort, url_for
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
| return redir | ect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
if __name__ == '__main__':
app.run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.