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
indexofire/gork
src/gork/application/know/plugins/attachments/models.py
Python
mit
6,582
0.002583
# -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ...
nKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') ...
ent revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filena...
DarkmatterVale/ChatterBot
tests/test_utils.py
Python
bsd-3-clause
2,741
0.000732
# -*- coding: utf-8 -*- from unittest import TestCase from chatterbot.utils.clean import clean_whit
espace from chatterbot.utils.clean import clean from chatterbot.utils.module_loading import import_module from chatterbot.utils.pos_tagger import POSTagger from chatterbot.utils.stop_words import StopWordsManager from chatterbot.utils.word_net import Wordnet class UtilityTests(TestCase): def test_import_module(s...
import_module("datetime.datetime") self.assertTrue(hasattr(datetime, 'now')) def test_pos_tagger(self): pos_tagger = POSTagger() tokens = pos_tagger.tokenize("what time is it") self.assertEqual(tokens, ['what', 'time', 'is', 'it']) def test_stop_words(self): stopwords...
StellarCN/py-stellar-base
stellar_sdk/xdr/liquidity_pool_withdraw_result.py
Python
apache-2.0
2,123
0.001413
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from xdrlib import Packer, Unpacker from ..type_checked import type_checked from .liquidity_pool_withdraw_result_code import LiquidityPoolWithdrawResultCode __all__ = ["LiquidityPoolWithdrawResult"] @type_check...
if code == LiquidityPoolWithdrawResultCode.LIQUIDITY_POOL_WITHDRAW_SUCCESS: return cls(code=code) return cls(code=code) def to_xdr_bytes(self) -> bytes: packer = Packer() self.pack(packer) return packer.get_buffer() @classmethod def from_xdr_bytes(cls, xdr: byte...
unpacker = Unpacker(xdr) return cls.unpack(unpacker) def to_xdr(self) -> str: xdr_bytes = self.to_xdr_bytes() return base64.b64encode(xdr_bytes).decode() @classmethod def from_xdr(cls, xdr: str) -> "LiquidityPoolWithdrawResult": xdr_bytes = base64.b64decode(xdr.encod...
docker-tow/tow
tow/modules.py
Python
apache-2.0
427
0
""" TODO: add comments """ import imp import sys
import os def load_module(env, module_path, name): """ This method load module file """ module_file = os.path.join(module_path, "%s.py" % name) mod = None if os.path.exists(module_file): mod = imp.new_module(name) mod.__dict__.update({"env": env}) sys.modules[name] = mod ...
return mod
opendatagroup/cassius
tags/cassius-0_1_0_0/cassius/containers.py
Python
apache-2.0
141,242
0.004198
# Standard Python packages import math, cmath import re import itertools import numbers import random # Special dependencies import numpy, numpy.random # sudo apt-get install python-numpy # import minuit # no package # Augustus dependencies from augustus.kernel.unitable import UniTable # Cassius interdependencies im...
constructor or later as member data. The frame arguments are interpreted only by the backend and are replaced with defaults if not present. Public Members: All frame arguments that have been set. """ _not_frameargs = [] def __init__(self, **frameargs): self.__dict__.upda
te(frameargs) def __repr__(self): return "<Frame %s at 0x%x>" % (str(self._frameargs()), id(self)) def _frameargs(self): output = dict(self.__dict__) for i in self._not_frameargs: if i in output: del output[i] for i in output.keys(): if i[0] == "_": del ...
googleapis/python-dialogflow
google/cloud/dialogflow_v2beta1/services/conversations/__init__.py
Python
apache-2.0
765
0
# -*- coding: utf-8 -*-
# Copyright 2022 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, 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 speci...
Wintellect/WintellectWebinars
2019-01-24-async-python-kennedy/code/the_unsync/thesync.py
Python
apache-2.0
1,632
0.002451
import asyncio import datetime import math from unsync import unsync import aiohttp import requests def main(): t0 = datetime.datetime.now() tasks = [ comp
ute_some(), compute_some(), compute_some(), download_some(), download_some(), download_some_more(), download_some_more(), wait_some(), wait_some(), wait_some(), wait_some(), ] [t.result() for t in tasks] dt = datetime.datetime...
t("Synchronous version done in {:,.2f} seconds.".format(dt.total_seconds())) @unsync(cpu_bound=True) def compute_some(): print("Computing...") for _ in range(1, 10_000_000): math.sqrt(25 ** 25 + .01) @unsync() async def download_some(): print("Downloading...") url = 'https://talkpython.fm/ep...
Azure/azure-sdk-for-python
sdk/search/azure-search-documents/samples/sample_data_source_operations.py
Python
mit
2,842
0.004926
# 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. # --------------------------------------------------------------------...
a_source_connection(): # [START get_data_source_connection] result = client.get_data_source_connection("sample-data-source-connection") print("Retrived Data Source Connection 'sample-data-source-connection'") # [END get_data_source_connection] def delete_data_sourc
e_connection(): # [START delete_data_source_connection] client.delete_data_source_connection("sample-data-source-connection") print("Data Source Connection 'sample-data-source-connection' successfully deleted") # [END delete_data_source_connection] if __name__ == '__main__': create_data_source_conn...
deepmind/graph_nets
graph_nets/tests/graphs_test.py
Python
apache-2.0
5,437
0.004966
# Copyright 2018 The GraphNets 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 applicabl...
["edges", "senders"],), ("senders but no receivers", ["edges", "receivers"],), ("edges but no senders/receivers", ["receivers", "senders"],), ) def test_inconsistent_none_fields_raise_error_on_replace(sel
f, none_fields): graph = graphs.GraphsTuple(**self.graph) with self.assertRaisesRegexp(ValueError, none_fields[-1]): graph.replace(**{none_field: None for none_field in none_fields}) @parameterized.named_parameters( ("all fields defined", [],), ("no node state", ["nodes"],), ("no edge...
jmaher/treeherder
treeherder/model/data_cycling/utils.py
Python
mpl-2.0
269
0.003717
def has_valid_explicit_days(func): def wrapper(*args, **kw
args): days = kwargs.get('days') if days is not None: raise ValueError('Cannot override performance data retention parameters.') func
(*args, **kwargs) return wrapper
wagnerand/zamboni
apps/tags/views.py
Python
bsd-3-clause
621
0.00161
from django import http from django.conf
import settings from django.shortcuts import get_object_o
r_404 import jingo from tags.models import Tag def top_cloud(request, num_tags=100): """Display 100 (or so) most used tags""" """TODO (skeen) Need to take request.APP.id into account, first attempts to do so resulted in extreme SQL carnage bug 556135 is open to fix""" top_tags = Tag.objects...
HERA-Team/hera_mc
scripts/stop_connection.py
Python
bsd-2-clause
3,370
0.00089
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2017 the HERA Collaboration # Licensed under the 2-clause BSD license. """ Script to add a general connection to the database. """ from hera_mc import mc, cm_utils, cm_partconnect, cm_handling def query_args(args): """ Gets information...
nput port", default=None) cm_utils.add_date_time_args(parser) args = parser.parse_args() args = query_args(args) # Pre-process some args if args.date is not None: at_date = cm_utils.get_astropytime(args.date, args.time, args.format) c = cm_partconnect.Connections() c.connection( ...
pstream_output_port=args.upport, downstream_part=args.dnpart, down_part_rev=args.dnrev, downstream_input_port=args.dnport, ) db = mc.connect_to_mc_db(args) session = db.sessionmaker() handling = cm_handling.Handling(session) chk = handling.get_specific_connection(c, at_date)...
zusitools/fahrstr_gen
test/test.py
Python
gpl-3.0
7,559
0.004498
#!/usr/bin/env python3 import unittest import os import subprocess import sys import re class TestFahrstrGen(unittest.TestCase): def run_fahrstr_gen(self, st3, args=[]): # return: (retcode, output) env = os.environ.copy() env["ZUSI3_DATAPATH"] = os.getcwd() cmd = [sys.executable, '../fahr...
ertSetEqual(self.get_vergleich_resultat(stderr), set([ "Anfang A1 -> Mitte M1 -> Ende E1: Hauptsignalverknuepfung (KENNLICHTSIGNALHILFSHAUPTSIGNAL.ST3,1) (Signal Anfang A1
an Element 1b) hat unterschiedliche Zeile: (0, False) vs. (0, True)", "Anfang A2 -> Mitte M2 -> Ende E2: Hauptsignalverknuepfung (KENNLICHTSIGNALHILFSHAUPTSIGNAL.ST3,10) (Signal Anfang A2 an Element 7b) hat unterschiedliche Zeile: (0, True) vs. (0, False)", ])) def test_weiche_an_modulgren...
alanfranz/mock
py/mockbuild/backend.py
Python
gpl-2.0
42,429
0.00363
# vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:textwidth=0: # License: GPL2 or later see COPYING # Originally written by Seth Vidal # Sections taken from Mach by Thomas Vander Stichele # Major reorganization and adaptation by Michael Brown # Copyright (C) 2007 Michael E Brown <mebrown@michaels-house....
have SELinux enabled # on the host, we need to do SELinux things, so set the selinux # state variable to true if self.pluginConf['selinux_enable'] == False and mockbuild.util.selinuxEnabled(): self.selinux = True # ============= # 'Public' API # ============= decora...
hooks.append(function) self._hooks[stage] = hooks decorate(traceLog()) def state(self): if not len(self._state): raise mockbuild.exception.StateError, "state called on empty state stack" return self._state[-1] def start(self, state): if state == N...
car3oon/saleor
saleor/dashboard/urls.py
Python
bsd-3-clause
1,052
0
from django.conf.urls import url, include from . import views as core_views from .category.urls import urlpatterns as category_ur
ls from .customer.urls import urlpatterns as customer_urls from .order.urls import urlpatterns as order_urls from .payments.urls import urlpatterns as payments_urls from .product.urls import urlpatterns as product_urls from .discount.urls import urlpatterns as discount_urls from .search.urls import urlpatterns as searc...
as site_urls from .shipping.urls import urlpatterns as shipping_urls urlpatterns = [ url(r'^$', core_views.index, name='index'), url(r'^categories/', include(category_urls)), url(r'^orders/', include(order_urls)), url(r'^products/', include(product_urls)), url(r'^payments/', include(payments_urls...
LLNL/spack
var/spack/repos/builtin/packages/r-stringr/package.py
Python
lgpl-2.1
1,501
0.003997
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RStringr(RPackage): """A consistent, simple and easy to use set of wrappers around the fan
tastic 'stringi' package. All function and argument names (and positions) are consistent, all functions deal with "NA"'s and zero length vectors in the same way, and the output from one function is easy to feed into the input of another.""" homepage = "https://cloud.r-project.org/package=stringr" u...
moneygrid/vertical-exchange
exchange_provider_internal/__openerp__.py
Python
gpl-3.0
774
0
# -*- coding: utf-8 -*- # © <2016> <Moneygrid Project, Lucas Huber> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { 'name': 'Exchange Provider Internal', 'version': '9.0.0.1.x', 'category': 'Exchange', 'summary'
: 'for the internal transaction engine', 'author': 'Lucas Huber, moneygrid Project', 'license': 'LGPL-3', 'website': 'https://github.com/moneygrid/vertical-exchange', 'description': """ Dumy Exchange Provider to use the internal transaction engine """,
'depends': ['base_exchange', 'exchange_provider'], 'data': [ 'views/exchange_provider_view.xml', 'data/internal_data.xml', 'data/account_data.xml', ], 'installable': True, }
satbekmyrza/geopar
tests/test_triangulated_figure.py
Python
mit
5,876
0.00017
import unittest from geopar.triangle_class import Triangle from geopar.triangulated_figure_class import TriangulatedFigure from geopar.angle_class import Angle __author__ = 'ebraude' # URL1: https://docs.google.com/presentation/d/1nddxo9JPaoxz-Colod8qd6Yuj_k7LXhBfO3JlVSYXrE/edit?usp=sharing class TestTriangulatedFi...
own_angles_at(self): self.assertEqual(self.tf1.number_of_unknown_angles_at(4), 0) self.assertEqual(self.tf1.number_of_unknown_angles_at(5), 0) self.assertEqual
(self.tf1.number_of_unknown_angles_at(6), 0) self.tf1.set_angle_by_angle_points(6, 4, 5, Angle.from_str('x')) self.assertEqual(self.tf1.number_of_unknown_angles_at(4), 1) self.tf1.set_angle_by_angle_points(3, 4, 6, Angle.from_str('x')) self.assertEqual(self.tf1.number_of_unknown_angles_a...
pnavarro/neutron
neutron/tests/api/admin/test_shared_network_extension.py
Python
apache-2.0
4,322
0
# Copyright 2015 Hewlett-Packard Development Company, L.P.dsvsv # Copyright 2015 OpenStack Foundation # 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 # # ...
sertEqual(self.shared_network['name'], show_shared_net['name']) self.assertEqual(self.shared_network['id'], show_shared_net['id']) self.assertTrue(show_shared_net['shared']) @test.idempotent_id('e03c92a2-638d-4bfa-b50a-b1f66f087e58') def test_show_shared_networks_attribute(s
elf): # Show a shared network and confirm that # shared network extension attribute is returned. self._show_shared_network(self.admin_client) self._show_shared_network(self.client)
uraxy/imozzle
api/management/commands/fetchall.py
Python
mit
1,532
0.001305
from logging import getLogger import socket import time from django.core.management.base import BaseCommand, CommandError import api.fetch from api.models import Feed logger = getLogger('app_api') # https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/ class Command(BaseCommand): help = '[imoz...
t = time.time() logger.info('begin.') # [Supporting a timeout in feedparser](http://kurtmckee.livejournal.com/32616.html) socket.setdefaulttimeout(5) # seconds try: # first: meta=True feeds
= Feed.objects.filter(disabled_at=None).filter(meta=True) api.fetch.fetch_and_update_by_list(feeds) # next: meta=False feeds = Feed.objects.filter(disabled_at=None).exclude(meta=True) api.fetch.fetch_and_update_by_list(feeds) except: # TODO Error imp...
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/test/re_tests.py
Python
gpl-2.0
31,794
0.001447
#!/usr/bin/env python3 # -*- mode: python -*- # Re test suite and benchmark suite v1.5 # The 3 possible outcomes for each pattern [SUCCEED, FAIL, SYNTAX_ERROR] = range(3) # Benchmark suite (needs expansion) # # The benchmark suite does not test correctness, just speed. The # first element of each tuple is the regex...
or the # string 'Error' if the group index was out of range; # also "groups", the return value of m.group() (a tuple). # 4: The expected result of evaluating the expression. # If the two don't match, an error is reported. # # If the regex isn't expected to work, the latter two e...
Unterminated group identifier ('(?P<1>a)', '', SYNTAX_ERROR), # Begins with a digit ('(?P<!>a)', '', SYNTAX_ERROR), # Begins with an illegal char ('(?P<foo!>a)', '', SYNTAX_ERROR), # Begins with an illegal char # Same tests, for the ?P= form ('(?P<foo_123>a)(?P=foo_123', 'aa', ...
pwnieexpress/raspberry_pwn
src/pentest/sqlmap/lib/utils/sqlalchemy.py
Python
gpl-3.0
2,985
0.00536
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import imp import logging import os import re import sys import warnings _sqlalchemy = None try: f, pathname, desc = imp.find_module("sqlalchemy", sys.path[1:]) _ = i...
dialect: conf.direct = conf.direct.replace(conf.dbms, self.dialect, 1) engine = _sqlalchemy.create_engine(conf.direct, connect_args={'ch
eck_same_thread':False} if self.dialect == "sqlite" else {}) self.connector = engine.connect() except SqlmapFilePathException: raise except Exception, msg: raise SqlmapConnectionException("SQLAlchemy connection issue ('%s')" % msg[0]) ...
atul-bhouraskar/django
tests/decorators/tests.py
Python
bsd-3-clause
15,914
0.000251
from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotA...
iews.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) ...
sult) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), ...
fin/froide
froide/foirequestfollower/tasks.py
Python
mit
1,029
0.000972
from django.utils import translation from django.conf import settings from froide.celery import app as celery_app from froide.foirequest.models import FoiRequest from .models import FoiRequestFollower from .utils import run_batch_update @celery_app.task def update_followers(request_id, update_message, template=None...
t = FoiRequest.objects.get(id=request_id) except FoiRequest.DoesNotExist: return followers = FoiRequestFollower.objects.filter(request=foirequest, confirmed=True) for follower in followers:
FoiRequestFollower.objects.send_update( follower.user or follower.email, [ { "request": foirequest, "unfollow_link": follower.get_unfollow_link(), "events": [update_message], } ], ...
wwj718/murp-edx
common/lib/xmodule/xmodule/modulestore/xml_exporter.py
Python
agpl-3.0
10,085
0.002776
""" Methods for exporting course data to XML """ import logging import lxml.etree from xblock.fields import Scope from xmodule.contentstore.content import StaticContent from xmodule.exceptions import NotFoundError from xmodule.modulestore import EdxJSONEncoder, ModuleStoreEnum from xmodule.modulestore.inheritance impo...
cannot load draft modules draft_verticals = modulestore.get_items( course_key, category='vertical', revision=ModuleStoreEnum.RevisionOption.draft_only ) if len(draft_verticals) > 0: draft_course_dir = export_fs.makeopendir(DRAFT_DIR) for draft_vertical in draft_verti...
ion=ModuleStoreEnum.RevisionOption.draft_preferred ) # Don't try to export orphaned items. if parent_loc is not None: logging.debug('parent_loc = {0}'.format(parent_loc)) if parent_loc.category in DIRECT_ONLY_CATEGORIES: draft_verti...
chrislit/abydos
tests/distance/test_distance_kuhns_vii.py
Python
gpl-3.0
7,292
0
# Copyright 2019-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 versio...
self.assertAlmostEqual( self.cmp_no_d.corr('Niall', 'Nigel'), -0.1666666667 ) self.assertAlmostEqual( self.cmp_no_d.corr('Colin', 'Coiln'), -0.1666666667 ) self.assertAlmostEqual( self.cmp_no_d.corr('Coiln', 'Colin'), -0.1666666667 ) se...
CGATTAG'), -0.0817253648 ) if __name__ == '__main__': unittest.main()
uozuAho/mnist-ocr
src/knn_binary.py
Python
mit
1,150
0.00087
""" kNN digit classifier, converting images to binary before training and classification. Should (or should allow for) reduction in kNN object size. """ import cv2 from utils import classifier as cs from utils import knn from utils import mnist class KnnBinary(knn.KnnDigitClassifier): def train(self, i...
ge in images: yield self.preprocess(image) if __name__ == '__main__': NUM_TRAINS = 100 NUM_TESTS = 100 runner = cs.ClassifierRunner(KnnBinary()) runner.train(mnist.traini
ng_images(NUM_TRAINS), mnist.training_labels(NUM_TRAINS)) runner.run(mnist.test_images(NUM_TESTS), mnist.test_labels(NUM_TESTS)) print(runner.get_report_str())
rit-sailing/website
files/admin.py
Python
mit
357
0.005602
from django.contrib import admin from .models import File, Folder class ItemAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): self.exclude = ("slug", ) form = sup
er(ItemAdmin, self).get_form(
request, obj, **kwargs) return form admin.site.register(File, ItemAdmin) admin.site.register(Folder, ItemAdmin)
pauljohnleonard/pod-world
CI_2014/ATTIC/CartWithPendulum/brainDemo.py
Python
gpl-2.0
524
0.080153
"""Demo shows how to use the brain module. """ import brain # 3
input 2 hidden 2 outputs guess=[ [[1, 2, 3, 0],[3, 4, 5, -1]] , [[8,9,2],[-4,-5,-6]] ] net=brain.FeedForwardBrain(weight=guess) # apply an input out=net.ffwd([.1,.2,-.3]) print out guess=[ [[1, 2, 3, 0],[3, 4, 5, -1]] , [[-4,-5,-6],[8,9,2]] ] net.setWeights(guess) print net.ffwd([.1,.2,-.3]...
.0) print net.weight
KaiSzuttor/espresso
testsuite/python/constraint_shape_based.py
Python
gpl-3.0
36,175
0.001216
# Copyright (C) 2010-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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 v...
1) * 2. - 1 pos = self.pos_on_surface( theta, v, semiaxes[0], semiaxes[1], semiaxes[1]) system.part[0].pos = pos system.integrator.run(recalc_forces=True, steps=0) energy = system.analysis.energy() self.assertAlmostEqua...
[3.61, 2.23] e = espressomd.shapes.Ellipsoid( a=semiaxes[0], b=semiaxes[1], center=3 * [self.box_l / 2.], direction=+1) constraint_e = espressomd.constraints.ShapeBasedConstraint( shape=e, particle_type=1, penetrable=True) const1 = sys...
MJWherry/Greggg-Python
Sensors/SonarController.py
Python
mit
8,550
0.003041
import logging import os import sys import time import RPi.GPIO as GPIO from Utilities.SettingsManager import SettingsManager from termcolor import colored from Utilities.SleepableThread import SleepableThread class SonarController(SleepableThread): # region Variables SC = SettingsManager(settin...
nterval = float(self.SC.get_setting_value('update_time_interval')) self.front_left_sonar_pin = int(self.SC.get_setting_value('front_left_sonar_pin')) self.front_middle_sonar_pin = int(self.SC.get_setting_value('front_middle_sonar_pin')) self.front_right_sonar_pin = i
nt(self.SC.get_setting_value('front_right_sonar_pin')) self.middle_back_sonar_pin = int(self.SC.get_setting_value('middle_back_sonar_pin')) self.max_cpu_iterations = int(self.SC.get_setting_value('max_cpu_iterations')) try: GPIO.setmode(GPIO.BOARD) logging.info('(SON...
Arnukk/IEEE-XTREME-8.0-Problems
IEEEXTREME/rano.py
Python
mit
1,429
0.002099
import sys try: data = map(int, sys.stdin.readline().split()) except ValueError: sys.stdout.write("NO" + '\n') exit() if not data: sys.stdout.write("NO" + '\n') exit() if len(data) != 2: sys.stdout.write("NO" + '\n') exit() if data[0] < 1 or data[0] > 1000: sys.stdout.write("NO" + '\...
exit() constraints = [] try: for i in range(data[1]): constraints.append(map(int, sys.stdin.readline().split())) if sum(1 for number in constraints[i] if number > data[0] or number < 1) > 0: sys.stdout.write("NO" + '\n') exit() except ValueError:
sys.stdout.write("NO" + '\n') exit() studyplan = [] try: studyplan = map(int, sys.stdin.readline().split()) if sum(1 for number in studyplan if number > data[0] or number < 1) > 0: sys.stdout.write("NO" + '\n') exit() except ValueError: sys.stdout.write("NO" + '\n') exit...
cbitstech/Purple-Robot-Django
management/commands/extractors/builtin_lightprobe.py
Python
gpl-3.0
7,242
0.003866
# pylint: disable=line-too-long import datetime import psycopg2 import pytz CREATE_PROBE_TABLE_SQL = 'CREATE TABLE builtin_lightprobe(id SERIAL PRIMARY KEY, user_id TEXT, guid TEXT, timestamp DOUBLE PRECISION, utc_logged TIMESTAMP, sensor_vendor TEXT, sensor_name TEXT, sensor_power DOUBLE PRECISION, sensor_type BIGIN...
' + \ 'utc_logged, ' + \ 'sensor_vendor, ' + \
'sensor_name, ' + \ 'sensor_power, ' + \ 'sensor_type, ' + \ 'sensor_version, ' + \ ...
zguns/KMClib
python/unittest/KMCLibTest/CoreComponents/KMCControlParametersTest.py
Python
gpl-3.0
4,818
0.005189
""" Module for testing the KMCControlParameters class. """ # Copyright (c) 2012-2013 Mikael Leetmaa # # This file is part of the KMCLib project distributed under the terms of the # GNU General Public License version 3, see <http://www.gnu.org/licenses/>. # import unittest from KMCLib.Exceptions.Error import Erro...
EVICE) # Wrong value. self.assertRaises( Error, lambda : KMCControlParameters(rng_type='ABC')) # Wrong type. self.assertRaises( Error, lambda : KMCControlParameters(rng
_type=123)) def testConstructionFail(self): """ Make sure we can not give invalid paramtes on construction. """ # Negative values. self.assertRaises( Error, lambda : KMCControlParameters(number_of_steps=-1, ...
mbohlool/client-python
kubernetes/test/test_v1_self_subject_access_review.py
Python
apache-2.0
1,037
0.004822
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://git
hub.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_self_subject_access_review import
V1SelfSubjectAccessReview class TestV1SelfSubjectAccessReview(unittest.TestCase): """ V1SelfSubjectAccessReview unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1SelfSubjectAccessReview(self): """ Test V1SelfSubjectAccessReview """ ...
stormi/tsunami
src/secondaires/navigation/equipage/ordres/virer.py
Python
bsd-3-clause
3,807
0.000526
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
""" cle = "virer" etats_autorises = ("tenir_gouvernail", ) def __init__(self, matelot, navire, direction=0): Ordre.__init__(self, matelot, navire, direction) self.direction = direction def executer(self): """Exécute l'ordre : vire sur bâbord.""" navire = self.navi...
personnage = matelot.personnage salle = personnage.salle direction = self.direction nav_direction = navire.direction.direction if not hasattr(salle, "gouvernail") or salle.gouvernail is None: return gouvernail = salle.gouvernail if gouvernail.tenu is no...
llange/human_curl
debug.py
Python
bsd-3-clause
736
0.001359
#!/usr/bin/env python # -*- coding: utf-8 -*- """ human_curl.debug ~~~~~~~~~~~~~~~~~~~~~~~~~~ Debuggging tests
for human_curl :copyright: (c) 2011 by Alexandr Lispython ([email protected]). :license: BSD, see LICENSE for more details. """ import logging from .tests import * logger = logging.getLogger("human_curl") logger.setLevel(logging.DEBUG) # Add the log message handle
r to the logger # LOG_FILENAME = os.path.join(os.path.dirname(__file__), "debug.log") # handler = logging.handlers.FileHandler(LOG_FILENAME) handler = logging.StreamHandler() formatter = logging.Formatter("%(levelname)s %(asctime)s %(module)s [%(lineno)d] %(process)d %(thread)d | %(message)s ") handler.setFormatter(f...
strahlex/machinekit
configs/ARM/BeagleBone/MendelMax-CRAMPS/cramps.py
Python
lgpl-2.1
5,005
0.000999
from machinekit import hal from machinekit import rtapi as rt from machinekit import config as c from fdm.config import base def hardware_read(): hal.addf('hpg.capture-position', 'servo-thread') hal.addf('bb_gpio.read', 'servo-thread') def hardware_write(): hal.addf('hpg.update', 'servo-thread') ha...
hal.Pin('bb_gpio.p8.in-09').link('limit-1-max') # Y hal.Pin('bb_gpio.p9.in-13').link('limit-2-home') # Z hal.Pin('bb_gpio.p9.in-11').link('limit-2-max') # Z # probe ... # Adjust as needed for your switch polarity hal.Pin('bb_gpio.p8.in-08.invert').set(True) hal.Pin('bb_gpio.p8.in-07.in...
al.Pin('bb_gpio.p9.in-11.invert').set(True) # ADC hal.Pin('temp.ch-04.value').link('hbp-temp-meas') hal.Pin('temp.ch-05.value').link('e0-temp-meas') hal.Pin('temp.ch-02.value').link('e1-temp-meas') hal.Pin('temp.ch-03.value').link('e2-temp-meas') # Stepper hal.Pin('hpg.stepgen.00.steppin')...
curbyourlitter/curbyourlitter-alley
curbyourlitter_alley/canrequests/mailinglist.py
Python
gpl-3.0
232
0
from django.conf
import settings import mailchimp_subscribe def subscribe(email_address): mailchimp_subscribe.subscribe(settings.MAILCHIMP_API_KEY, settings.MAIL
CHIMP_LIST_ID, email_address)
phase-dev/phase
libmproxy/stateobject.py
Python
gpl-3.0
2,608
0.002684
class StateObject(object): def _get_state(self): raise NotImplementedError # pragma: nocover def _load_state(self, state): raise NotImplementedError # pragma: nocover @classmethod def _from_state(cls, state): raise NotImplementedError # pragma: nocover # Usually, thi...
def __eq__(self, other): try:
return self._get_state() == other._get_state() except AttributeError: # we may compare with something that's not a StateObject return False class SimpleStateObject(StateObject): """ A StateObject with opionated conventions that tries to keep everything DRY. Simply put, you agree on...
BT-aestebanez/l10n-switzerland
l10n_ch_base_bank/tests/test_create_invoice.py
Python
agpl-3.0
4,816
0
# -*- coding: utf-8 -*- # © 2015 Yannick Vaucher (Camptocamp SA) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests import common from openerp import exceptions class TestCreateInvoice(common.TransactionCase): def test_emit_invoice_with_bvr_reference(self): self.inv_v...
self.assertEqual(invoice.reference_type, 'bvr') def test_emit_invoice_with_bvr_reference_15_pos(self): self.inv_values.update({ 'partner_id': self.partner.id, 'type': 'out_invoice' }) invoice = self.env['account.invoice'].new(self.inv_values) invoice._
onchange_partner_id() self.assertEqual(invoice.partner_bank_id, self.bank_acc) self.assertNotEqual(invoice.reference_type, 'bvr') invoice.reference = '132000000000004' invoice.reference_type = 'bvr' # set manually bvr reference type # and save self.env['account.invoice...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/numpy/numarray/ufuncs.py
Python
agpl-3.0
1,358
0
__all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide', 'equal', 'exp', 'fabs', 'floor', 'floor_divide', 'fmod', 'greater', 'gre...
equal, exp, fa
bs, floor, floor_divide, fmod, greater, greater_equal, \ hypot, isnan, less, less_equal, log, log10, logical_and, \ logical_not, logical_or, logical_xor, left_shift as lshift, \ maximum, minimum, negative as minus, multiply, negative, \ not_equal, power, product, remainder, right_shift as rshift, si...
SteveJM/sulley
unit_tests/blocks.py
Python
gpl-2.0
7,438
0.008067
from sulley import * def run (): groups_and_num_test_cases() dependencies() repeaters() return_current_mutant() exhaustion() # clear out the requests. blocks.REQUESTS = {} blocks.CURRENT = None #########################################################################################...
################################################################################### def return_current_mutant (): s_initializ
e("RETURN CURRENT MUTANT TEST 1") s_dword(0xdeadbeef, name="boss hog") s_string("bloodhound gang", name="vagina") if s_block_start("BLOCK1"): s_string("foo", name="foo") s_string("bar", name="bar") s_dword(0x20) s_block_end() s_dword(0xdead) s_dword(0x0fed) s_stri...
larsbergstrom/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/webkit.py
Python
mpl-2.0
3,966
0.000252
from .base import Browser, ExecutorBrowser, require_arg from .base import get_timeout_multiplier # noqa: F401 from ..executors import executor_kwargs as base_executor_kwargs from ..executors.executorwebdriver import (WebDriverTestharnessExecutor, # noqa: F401 WebDriverRefTe...
t_multiplier"} def check_args(**kwargs): require_arg(kwargs, "binary") require_arg(kwargs, "webdriver_binary") require_arg(kwargs, "webkit_port") def browser_kwargs(test_type, run_info_data, config, **kwargs): return {"binary": kwargs["binary"], "webdriver_binary": kwargs["webdriver_bina...
ver_args")} def capabilities_for_port(server_config, **kwargs): port_name = kwargs["webkit_port"] if port_name in ["gtk", "wpe"]: port_key_map = {"gtk": "webkitgtk"} browser_options_port = port_key_map.get(port_name, port_name) browser_options_key = "%s:browserOptions" % browser_option...
sophilabs/pyconuy-site
pyconuy2012/background/models.py
Python
mit
815
0.002454
from django.db import models from pyconuy2012.settings import LANGUAGES class Background(models.Model): title = models.CharField(max_length=40) description = models.TextField() place = models.CharField(max_length=20) author = models.CharField(max_length=30, null=True, blank=True) language = models...
gth=2, choices=LANGUAGES) order = models.IntegerField(default=0) source = models.URLField(null=True, blank=True) image = models.ImageField(upload_to="backgrounds") latitude = models.DecimalField(decimal_places=6, max_digits=8) longitude = models.DecimalField(decimal_places=6, max
_digits=8) tag = models.CharField(max_length=50) box_css_class = models.CharField(max_length=20, default='std-box') def __unicode__(self): return self.title
dhuang/incubator-airflow
airflow/www/decorators.py
Python
apache-2.0
3,563
0.000842
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
e request: %s", execution_date_value ) pass
session.add(log) return f(*args, **kwargs) return cast(T, wrapper) def gzipped(f: T) -> T: """Decorator to make a view compressed""" @functools.wraps(f) def view_func(*args, **kwargs): @after_this_request def zipper(response): accept_encoding = requ...
annttu/sikteeri
membership/decorators.py
Python
mit
1,735
0.001729
# encoding: utf-8 """ decorators.py """ from django.contrib.auth import authenticate from django.http import HttpResponse, HttpResponseForbidden from django.conf import settings from membership.utils import get_client_ip from sikteeri.iptools import IpRangeList import base64 def trusted_host_required(view_func):...
s not None: if user.is_active: return view_func(request, *args, **kwargs) response = HttpResponse("Authorization Required", status=401) response['WWW-Auth
enticate'] = 'Basic realm="Secure Area"' return response return _auth def main(): pass if __name__ == '__main__': main()
SeanXP/Nao-Robot
python/language/set_English.py
Python
gpl-2.0
753
0.018545
#! /usr/bin/env python #-*- coding: utf-8 -*- ################################################################# # Copyright (C) 2015 Sean Guo. All rights reserved. # # > File Name: < set_English.py > # > Author: < Sean Guo > # > Mail: <
[email protected] > # > Created Time: < 2015/03/30 > # > Last Changed: # > Description: #########################################
######################## from naoqi import ALProxy robot_ip = "192.168.1.100" robot_port = 9559 # default port : 9559 tts = ALProxy("ALTextToSpeech", robot_ip, robot_port) tts.setLanguage("English") tts.say("Hello, world! I am Nao robot!") # 切换语言包需要较长时间,故尽量不要在程序运行时切换;
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/boto/regioninfo.py
Python
agpl-3.0
6,214
0.000322
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2010, Eucalyptus Systems, Inc. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without res...
object pointing to the endpoint associated with this region. You may pass any of the arguments accepted by the connection class's constructor as keyword arguments and they will be passed along to the c
onnection object. :rtype: Connection object :return: The connection to this regions endpoint """ if self.connection_cls: return self.connection_cls(region=self, **kw_params)
jeffrey4l/nova
nova/tests/unit/api/openstack/compute/contrib/test_migrations.py
Python
apache-2.0
5,239
0
# 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 agreed to in...
ific language governing permissions and limitations # under the License. import datetime from oslotest import moxstubout from nova.api.openstack.compute.contrib import migrations as migrations_v2 from nova.api.openstack.compute.plugins.v3 import migrations as migrations_v21 from nova import context from nova impo...
'id': 1234, 'source_node': 'node1', 'dest_node': 'node2', 'source_compute': 'compute1', 'dest_compute': 'compute2', 'dest_host': '1.2.3.4', 'status': 'Done', 'instance_uuid': 'instance_id_123', 'old_instance_type_id': 1, 'new_instance_type_id': 2, ...
frivoal/presto-testo
wpt/websockets/autobahn/oberstet-Autobahn-643d2ee/lib/python/autobahn/case/case4_2_5.py
Python
bsd-3-clause
1,648
0.027913
############################################################################### ## ## Copyright 2011 Tavendo GmbH ## ## 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 ## ## ht...
rol <b>Opcode = 15</b> and non-empty payload, then send Ping.""" EXPECTATION = """Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.""" def onOpen(self): payload = "Hello, world!" self.expected[Cas
e.OK] = [("message", payload, False)] self.expected[Case.NON_STRICT] = [] self.expectedClose = {"closedByMe":False,"closeCode":[self.p.CLOSE_STATUS_CODE_PROTOCOL_ERROR],"requireClean":False} self.p.sendFrame(opcode = 1, payload = payload, chopsize = 1) self.p.sendFrame(opcode = 15, payload =...
lhm30/PIDGINv2
predict_enriched.py
Python
mit
11,872
0.032177
#Author : Lewis Mervin [email protected] #Supervisor : Dr. A. Bender #All rights reserved 2016 #Protein Target Prediction Tool trained on SARs from PubChem (Mined 21/06/16) and ChEMBL21 #Molecular Descriptors : 2048bit Morgan Binary Fingerprints (Rdkit) - ECFP4 #Dependencies : rdkit, sklearn, numpy #libraries from rdkit...
ep = '\\' else: sep = '/' return_dict1 = dict() return_dict2 = dict() pathway_info = [l.split('\t') for l in open(os.path.dirname(os.path.abspath(__file
__)) + sep + 'biosystems.txt').read().splitlines()] for l in pathway_info: try: return_dict1[l[0]].append(l[1]) except KeyError: return_dict1[l[0]] = [l[1]] return_dict2[l[1]] = l[2:] return return_dict1, return_dict2 #get pre-calculated bg hits from PubChem def getBGhits(threshold): if os.name == 'nt':...
mozilla/peekaboo
peekaboo/locations/urls.py
Python
mpl-2.0
242
0
from django.conf.urls import patterns, url from . import views urlpatterns = patterns( '', url(r'^$', views.home, name='home'), url(r'^(?P<pk>\d+)/edit/$', views.edit, name=
'edit
'), url(r'^new/$', views.new, name='new'), )
osmiyaki/openacademy
__openerp__.py
Python
gpl-3.0
972
0.001029
# -*- coding: utf-8 -*- { 'name': "openacademy", 'summary': """M
anage trainings""", 'description': """ Open Academy module for managing trainings: - training courses - training sessions - attendees registration """, 'author': "Your Company", 'website': "http://www.yourcompany.com", # Categories can be used to filter...
category': 'Uncategorized', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'templates.xml', 'views/openacademy.xml', 'views/partner.xml', 'views/session...
monikagrabowska/osf.io
api_tests/nodes/views/test_node_contributors_detail.py
Python
apache-2.0
38,769
0.00294
# -*- coding: utf-8 -*- from nose.tools import * # flake8: noqa from website.models import NodeLog from website.project.model import Auth from website.util import permissions from api.base.settings.defaults import API_BASE from website.util import disconnected_from_listeners from website.project.signals import contr...
last_position = len(self.contributors) - 1 @staticmethod def _get_contributor_user_id(contributor): return contributor['embeds']['users']['data']['id'] def test_initial_order(self): res = self.app.get('/{}nodes/{}/contributors/'.format(API_BASE, self.project._id), auth=self.user_one.auth) ...
al(res.status_code, 200) contributor_list = res.json['data'] found_contributors = False for i in range(0, len(self.contributors)): assert_equal(self.contributors[i]._id, self._get_contributor_user_id(contributor_list[i])) assert_equal(i, contributor_list[i]['attributes'][...
sassoftware/rmake
rmake_test/functional_test/compattest.py
Python
apache-2.0
1,882
0.001063
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w
riting, 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 la
nguage governing permissions and # limitations under the License. # from rmake_test import rmakehelp from rmake import compat from conary import constants class CompatTest(rmakehelp.RmakeHelper): def testCompatCheck(self): cv = compat.ConaryVersion('1.0.29') assert(not cv.supportsCloneCallback()...
SamuelYvon/radish
radish/terrain.py
Python
mit
346
0
# -*- coding: utf-8 -*- """ Terrain module providing step overlapping data containers """ import threading world = threading.local() # pylint: disable=invalid
-name def pick(func): """ Picks the given function and add it to the world object """ setattr(world, func.__name__,
func) return func world.pick = pick
enthought/etsproxy
enthought/enable/primitives/polygon.py
Python
bsd-3-clause
94
0
# proxy module from __future__ import absolute_import from enable.primitives
.pol
ygon import *
leonjza/filesmudge
filesmudge/populate.py
Python
mit
1,009
0
import shelve import os # Many more at: # http://www.garykessler.net/library/file_sigs.html # http://www.garykessler.net/library/magic.html smudges = { 'jpg': { 'offset': 0, 'magic': '\xFF\xD8\xFF' }, 'png': { 'offset': 0, 'magic': '\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' ...
'magic': '\x4D\x5A' }, 'tar': { 'offset': 257, 'magic': '\x75\
x73\x74\x61\x72\x20\x20\x00' }, '3gp': { 'offset': 4, 'magic': '\x66\x74\x79\x70\x33\x67' } } def populate_smudge_db(): db_path = os.path.join( os.path.dirname(__file__), 'smudge') db = shelve.open(db_path) db.clear() db.update(smudges) db.close() print('S...
madhadron/seqlabd
seqlab/subcommands/place.py
Python
gpl-3.0
2,140
0.008411
"""Put an AB1 file into the proper location in the file hierarchy.""" import logging import seqlab.config import seqlab.place import os import oursql log = logging.getLogger(__name__) def build_parser(parser): parser.add_argument('file', type=str, help='Path to the file to place') parser.add_argument(...
connect to MDX database') parser.add_argument('-p','--pass
word', help='Password to connect to MDX database') parser.add_argument('-d','--database', help='Database name of MDX database') parser.add_argument('-t','--target', help='Base path where files should be placed') parser.add_argument('-c','--config', default='/etc/seqlab.conf', ...
unho/pootle
pootle/apps/pootle_store/migrations/0030_remove_extra_indeces.py
Python
gpl-3.0
1,311
0.003051
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-02 15:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pootle_store', '0029_set_unit_creation_revision'), ] ...
ld_stores', to='pootle_app.Directory'), ), migrations.AlterField( model_name='store', name='translation_project', field=models.ForeignKey(db_index=False, editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='stores', to='pootle_translationproject....
anslationProject'), ), migrations.AlterField( model_name='unit', name='store', field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Store'), ), migrations.AlterIndexTogether( name='unit', ...
khosrow/metpx
pxStats/lib/StatsDateLib.py
Python
gpl-2.0
32,661
0.039619
""" ############################################################################## ## ## ## @name : StatsDateLib.py ## ## @license : MetPX Copyright (C) 2004-2006 Environment Canada ## MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file ## named COPYING in the root of the s...
days = { "Mon": _("Mon"), "Tue": _("Tue"), "Wed": _("Wed"), "Thu": _("Thu"),\ "Fri": _("Fri"),"Sat": _("Sat"),"Sun": _("Sun"), "Monday": _("Monday"),\ "Tuesday": _("Tuesday"), "Wednesday": _("Wednesday
"), "Thursday": _("Thursday"),\ "Friday": _("Friday"),"Saturday": _("Saturday"),"Sunday":_("Sunday") } day = time.strftime( "%a", time.gmtime( timeInEpochFormat ) )
tnotstar/talgostar
classics/hello/hello.py
Python
apache-2.0
77
0
#!/usr/bin/env python # -*- cod
ing: utf-8 -*-
print("Hello, world!") # EOF
nerow/solutions
cc150-python/Chapter-1-Arrays-and-Strings/1.6.py
Python
lgpl-3.0
969
0.039216
''' 1.6 Given an image represented by an NxN matrix, where each pixel in th
e image is 4 bytes, write a method to rotate the image by 90 degrees Can you do this in place? ''' def demo(matrix): N = len(matrix) if N == 0: return matrix # up <===> down for i in range(0, N / 2) : for j in range(N): matrix[i][j], matrix[N - 1 - i][j] = matrix[N -1 - i][j], matrix[i][j] # l...
or i in range(N): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return matrix import unittest class MyTestCases(unittest.TestCase): def test_mycase(self): self.demo = demo self.assertEqual(self.demo([]), []) self.assertEqual(self.demo([[1]])...
fuzzyray/pynet_test
subprocess_ex1.py
Python
apache-2.0
663
0.015083
#!/usr/bin/env python # Subprocess ex1 # --------------- # # Use subprocess to check the config files in ~/CFGS
into git # # Assumes 'git init' is done manually. # ----------- # cd ~/CFGS # git init # # # Commands to be done using subprocess. # ---------- # git add *.cfg # git commit -m "Add configs" # # # You will also need to change dir into the ~/CFGS dir # --------- #
os.chdir(CFGS_DIR) # # # You can use 'git log' to verify your commits. You probably # will need to manually change one of the config files (so that # git will have something to check in). def main(): return 0 if __name__ == '__main__': import sys sys.exit(main())
xray/xray
xarray/plot/utils.py
Python
apache-2.0
26,251
0.000533
import itertools import textwrap import warnings from datetime import datetime from inspect import getfullargspec from typing import Any, Iterable, Mapping, Tuple, Union import numpy as np import pandas as pd from ..core.options import OPTIONS from ..core.utils import is_scalar try: import nc_time_axis # noqa: ...
happens when mpl doesn't like a colormap, try seaborn try: from seaborn import color_palette pal = color_palette(cmap, n_colors=n_colors) except (ValueError, ImportError): # or maybe we just got a single color as a string cmap = Li...
return pal # _determine_cmap_params is adapted from Seaborn: # https://github.com/mwaskom/seaborn/blob/v0.6/seaborn/matrix.py#L158 # Used under the terms of Seaborn's license, see licenses/SEABORN_LICENSE. def _determine_cmap_params( plot_data, vmin=None, vmax=None, cmap=None, center=None, r...
supersaiyanmode/HomePiServer
messaging/queues.py
Python
mit
6,344
0.000315
import json from collections import defaultdict from threading import Lock from jsonschema import validate, ValidationError from weavelib.exceptions import AuthenticationFailed, Unauthorized from weavelib.exceptions import SchemaValidationFailed from .messaging_utils import get_required_field from .authorizers impor...
mat( self.channel_info.request_schema, msg.task, self) raise SchemaValidationFailed(msg) def check_auth(self, op, headers): authorizer = self.channel_info.authorizers.get(op, AllowAllAuthorizer()) # headers.get("AUTH") == ApplicationRegistry.get_app_info().
app_info = headers.get("AUTH", {}) default_app_url = object() app_url = app_info.get("app_url", default_app_url) res = authorizer.authorize(app_url, op, self.channel_info.channel_name) if not res: if app_url is default_app_url: raise AuthenticationFail...
Arlefreak/ApiArlefreak
about/migrations/0002_remove_entry_notes.py
Python
mit
377
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-18 22:59 from __future__ import unicode_literals from django.db import migrat
ions class Migration(migrations.Migration): dependencies = [ ('about', '0001_initial'), ] operations = [ migrations.RemoveF
ield( model_name='entry', name='notes', ), ]
MORZorg/sol
sources/virtual machine/interface.py
Python
gpl-2.0
12,388
0
#!/usr/bin/env python3 import struct from collections import deque from PyQt5 import QtCore, QtWidgets, uic from settings import DEBUG class ByteDeque: def __init__(self, byteData): if type(byteData) is ByteDeque: self.data = byteData.data self.start = byteData.start els...
itle("SOL {}".format("Input" if editable else "Output")) # Remove, Create, Replace self.ui.gridLayout.removeWidget(self.ui.widgetSchema) self.ui.widgetSchema.close() self.ui.widgetSchema = \ DataDialog.r
esolveSchema(schema, editable=editable) self.ui.gridLayout.addWidget(self.ui.widgetSchema, 0, 0, 1, 1) self.ui.gridLayout.update() @staticmethod def resolveSchema(schema, nesting=None, editable=True): """ Transforms a string schema into a widget (or series of nested widg...
adit-chandra/tensorflow
tensorflow/python/training/server_lib_same_variables_clear_test.py
Python
apache-2.0
2,744
0.00328
# Copyright 2017 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...
lEqual([[4]], sess_1.run(v2)) self.assertAllEqual([[4]], sess_2.run(v2)) # Resets target. sessions abort. Use sess_2 to verify. session.Session.reset(server.target) with self.assertRaises(errors_impl.AbortedError): self.assertAllEqual([[4]], sess_2.run(v2)) # Connects to the same target. Dev...
rors_impl.FailedPreconditionError): sess_2.run(v2) # Reinitializes the variables. sess_2.run(variables.global_variables_initializer()) self.assertAllEqual([[4]], sess_2.run(v2)) sess_2.close() if __name__ == "__main__": test.main()
rafelbennasar/pathway-displayer
examples/example5/pdr/settings.py
Python
gpl-2.0
1,408
0.00071
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'i$9evryhjz*1um&a3%^1bw9cmfu
5p2crgn+4j)ta)v#&t@!-t^' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'compressor', ) STATICFILES_FINDERS = ( 'd...
esFinder', 'compressor.finders.CompressorFinder', ) ROOT_URLCONF = 'pdr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.t...
DarkShadow0/Content-Based-Image-Retrieval
abhi/color_kmeans.py
Python
mit
1,211
0.012386
# USAGE # python color_kmeans.py --image images/jp.png --clusters 3 # import the necessary packages from sklearn.cluster import KMeans import matplotlib.pyplot as plt import argparse import utils import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "-...
image to be a list of pixels image = image.reshape((image.shape[0] * image.shape[1], 3)) # cluster the pixel intensities clt = KMea
ns(n_clusters = args["clusters"]) clt.fit(image) # build a histogram of clusters and then create a figure # representing the number of pixels labeled to each color hist = utils.centroid_histogram(clt) bar = utils.plot_colors(hist, clt.cluster_centers_) # show our color bart plt.figure() plt.axis("off") plt.imshow(bar...
learningequality/kolibri
kolibri/core/public/api.py
Python
mit
12,019
0.002246
import datetime import gzip import io import json import time from django.db.models import Q from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http import HttpResponseNotFound from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from djang...
m_integer_mask from kolibri.core.device.models import SyncQueue from kolibri.core.device.models import UserSyncStatus from kolibri.core.device.utils import allow_peer_unlisted_channel_import from kolibri.core.public.constants.user_sync_options import DELAYED_SYNC from kolibri.core.public.constants.user_sync_options imp...
.user_sync_options import MAX_CONCURRENT_SYNCS from kolibri.core.public.constants.user_sync_options import STALE_QUEUE_TIME from kolibri.utils.conf import OPTIONS class InfoViewSet(viewsets.ViewSet): """ An equivalent endpoint in studio which allows kolibri devices to know if this device can serve content...
jbedorf/tensorflow
tensorflow/contrib/slim/python/slim/evaluation.py
Python
apache-2.0
11,795
0.002035
# 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...
k` objects to pass during the evaluation. Returns: The value of `final_op` or `None` if `final_op` is `None`. """ if summary_op == _USE_DEFAULT: summary_op = summary.merge_all() all_hooks = [evaluation.StopAfterNEvalsHook(num_evals),] if summary_op is not None: all_hooks.append(evaluation...
_dir=logdir, summary_op=summary_op, feed_dict=summary_op_feed_dict)) if hooks is not None: all_hooks.extend(hooks) saver = None if variables_to_restore is not None: saver = tf_saver.Saver(variables_to_restore) return evaluation.evaluate_once( checkpoint_path, master=master, scaffold=...
mattvonrocketstein/smash
smashlib/ipy3x/nbconvert/writers/stdout.py
Python
mit
1,101
0.006358
""" Contains Stdout writer """ #-------------------------------------------------------------------
---------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------...
from IPython.utils import io from .base import WriterBase #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class StdoutWriter(WriterBase): """Consumes output from nbconvert export...() method...
mitschabaude/nanopores
nanopores/geometries/P_geo/py4geo.py
Python
mit
1,164
0.006014
""" python script that generates mesh for Howorka geometry """ import numpy from importlib import import_module import nanopores.py4gmsh.basic import nanopores.py4gmsh.extra from nanopores.py4gmsh import * from warnings import warn import os from nanopores import INSTALLDIR def get_geo(**params): """ writes a...
"
geo_code": geo_code, } return geo_dict # ----- if __name__ == '__main__': print(get_geo()) print('\n - This is the sample code for the geo file')
christianurich/VIBe2UrbanSim
3rdparty/opus/src/psrc_parcel/estimation/dppcm_specification.py
Python
gpl-2.0
3,072
0.019206
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE all_variables = [] specification = {} specification = { #"_definition_": all_variables, -2:{ "equation_ids":(1, 2), # 1:accepted; 2:una...
ion_cost":("beta1_acqcost",0), #"urbansim_parcel.development_project_proposal.demolition_cost":("beta1_demcost",0), #"urbansim_parcel.development_project_proposal.construction_cost":("beta1_concost",0), #"urbansim_parcel.development_project_proposal.total_investment":("beta1_totc
ost",0), "urbansim_parcel.development_project_proposal.expected_rate_of_return_on_investment":("beta1_roi",0), #"constant+0.0132":(0, "beta2_asc"), #"person.disaggregate(household.persons)":("beta1_hhsize", 0), #"person.disaggregate(household.children > 0)":("beta1_haschild", 0),...
ravyg/algorithms
python/1_twoSum.py
Python
gpl-3.0
331
0.003021
c
lass Solution(object): def twoSum(self, nums, target): lookup = {} for i, num in enumerate(nums): if target - num in lookup: return [lookup[target - num], i] lookup[num] = i return [] if __name__ == '__main__': print Solution().twoSum((0, 2,
7, 11, 15), 9)
karllessard/tensorflow
tensorflow/python/ops/distributions/gamma.py
Python
apache-2.0
12,328
0.003164
# 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...
from tensorflow.python.ops.distributions import kullback_leibler from tensorflow.python.ops.distributions import util as distribution_util from tensorfl
ow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export __all__ = [ "Gamma", "GammaWithSoftplusConcentrationRate", ] @tf_export(v1=["distributions.Gamma"]) class Gamma(distribution.Distribution): """Gamma distribution. The Gamma distribution is defined over positive rea...
rbalda/neural_ocr
env/lib/python2.7/site-packages/pybrain/rl/learners/directsearch/rwr.py
Python
mit
9,259
0.006696
__author__ = 'Tom Schaul, [email protected] and Daan Wiertra, [email protected]' from scipy import zeros, array, mean, randn, exp, dot, argmax from pybrain.datasets import ReinforcementDataSet, ImportanceDataSet, SequentialDataSet from pybrain.supervised import BackpropTrainer from pybrain.utilities import drawIndex from pybr...
if self.valueMomentum == None: self.valueMomentum = self.momentum if self.supervisedPlotting: from pylab import ion ion() # adaptive temperature: self.tau = 1. # prepare the datasets to be used self.weig
htedDs = ImportanceDataSet(self.task.outdim, self.task.indim) self.rawDs = ReinforcementDataSet(self.task.outdim, self.task.indim) self.valueDs = SequentialDataSet(self.task.outdim, 1) # prepare the supervised trainers self.bp = BackpropTrainer(self.net, self.weightedDs, self.le...
ychab/mymoney-server
mymoney/schedulers/migrations/0001_initial.py
Python
bsd-3-clause
3,119
0.004809
# Generated by Django 2.1.1 on 2018-09-08 20:47 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('tags', '0001_initial'), ('accounts', '0001_initial'), ] operations = [ ...
('last_action', models.DateTimeField(editable=False, help_text='Last time the scheduled bank transaction has been cloned.', null=True)), ('state', models.CharField(choices=[('waiting', 'Waiting'), ('finished', 'Finished'), ('failed', 'Failed')], default='waiting', editable=False, help_text='State o...
o.db.models.deletion.CASCADE, related_name='schedulers', to='accounts.Account')), ('tag', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='schedulers', to='tags.Tag', verbose_name='Tag')), ], options={ 'db_table'...
ojengwa/sympy
sympy/simplify/cse_main.py
Python
bsd-3-clause
14,930
0.000402
""" Tools for doing common subexpression elimination. """ from __future__ import print_function, division import difflib from sympy.core import Basic, Mul, Add, Pow, sympify, Tuple from sympy.core.singleton import S from sympy.core.basic import preorder_traversal from sympy.core.function import _coeff_isneg from symp...
for k in xrange(j + 1, len(func_args)): if not com_args.difference(func_args[k]): diff_k = func_args[k].difference(com_args) func_args[k] = di
ff_k | set([com_func]) opt_subs[funcs[k]] = Func(Func(*diff_k), com_func, evaluate=False) # split muls into commutative comutative_muls = set() for
djo938/apdu_builder
apdu/readers/proxnroll.py
Python
gpl-3.0
18,825
0.021673
#!/usr/bin/python # -*- coding: utf-8 -*- #Copyright (C) 2014 Jonathan Delvaux <[email protected]> #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 #any later...
during the transfer", #TODO give a hint, maybe
slow down the process or increase timeout in transmit 0x02: "CRC error in card's answer", 0x04: "Card authentication failed", 0x05: "Parity error in card's answer", 0x06: "Invalid card response opcode", 0x07: "Bad anti-collision sequence", ...
PaddlePaddle/cloud
k8s/raw_job/prepare_data.py
Python
apache-2.0
670
0
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "L
icense"); # 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT ...
addle paddle.dataset.mnist.train()
stuartsan/prisonstudies
scraper/scraper/pipelines.py
Python
mit
506
0.001976
# -*- coding: ut
f-8 -*- from countrycode_lookup import lookup # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class ScraperPipeline(object): def process_item(self, item, spider): if not item['name'] in l...
else: item['country_code'] = lookup[item['name']] return item
stkyle/serengeti
serengeti/taxii-client.py
Python
mit
5,591
0.001073
# -*- coding: utf-8 -*- """ Test Script for debugging DHS TAXII Connection. """ import sys import argparse import requests import datetime import random from dateutil.tz import tzutc import libtaxii.messages_11 as taxii_messages from libtaxii.messages_11 import SubscriptionInformation from libtaxii.messages_11 import C...
b = taxii_messages.InboxMessage(message_id=message_id, extended_headers=None, subscription_information=subscription_info, record_count=RecordCount(
1, partial_count=False), content_blocks=[content_block]) data = ib.to_xml() headers = kwargs.pop('headers', HTTP_HEADERS) resp = requests.post(url, headers=headers, data=data, **kwargs) return resp.text def disco...
edx/edxanalytics
src/edxanalytics/prototypemodules/common.py
Python
agpl-3.0
1,629
0.014733
## TODO: This belongs somewhere else. ## ## * We need a way to construct a common library, especially to ## inspect events and provide higher-level operations ## * We need a better way to internally call queries. import logging log=logging.getLogger(__name__) def query_results(query): from django.db import co...
/td
><td>{1}</td></tr>".format(query_data['course_id'][i],query_data['count'][i]) html_string+="</table>" return html_string def get_db_and_fs_cron(f): ### HACK """ Gets the correct fs and db for a given input function f - a function signature fs - A filesystem object db - A mongo database coll...
plotly/python-api
packages/python/plotly/plotly/validators/box/marker/line/_color.py
Python
mit
496
0.002016
impor
t _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="color", parent_name="box.marker.line", **kwargs): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ar...
)
shodimaggio/SaivDr
appendix/torch_nsolt/nsoltChannelConcatenation2dLayer.py
Python
bsd-2-clause
1,751
0.012448
import torch import torch.nn as nn class NsoltChannelConcatenation2dLayer(nn.Module): """ NSOLTCHANNELCONCATENATION2DLAYER 2コンポーネント入力(nComponents=2のみサポート): nSamples x nRows x nCols x (nChsTotal-1) nSamples x nRows x nCols 1コンポーネント出力(nComponents=1のみサポート): ...
u.ac.jp/ """ def __init__(self, name=''): super(NsoltChannelConcatenation2dLayer, self).__init__() self.name = name self.description = "Channel concatenation" #self.type = '' #self.input_names = [ 'ac', 'dc' ] def forward(self,Xac,Xdc): """ F...
layer - Layer to forward propagate through X1, X2 - Input data (2 components) Outputs: Z - Outputs of layer forward function """ # Layer forward function for prediction goes here. if Xdc.dim() == 3: ...
ngageoint/scale
scale/job/messages/create_jobs.py
Python
apache-2.0
15,742
0.002859
"""Defines a command message that creates job models""" from __future__ import unicode_literals import logging from collections import namedtuple from django.db import transaction from data.data.json.data_v6 import convert_data_to_v6_json, DataV6 from data.data.exceptions import InvalidData from job.exceptions impor...
e_rev_num = json_dict['job_type_rev_num'] message.input_data = DataV6(json_dict['input_data']).get_data() elif message.create_jobs_type == RECIPE_TYPE: m
essage.recipe_id = json_dict['recipe_id'] if 'root_recipe_id' in json_dict: message.root_recipe_id = json_dict['root_recipe_id'] if 'superseded_recipe_id' in json_dict: message.superseded_recipe_id = json_dict['superseded_recipe_id'] if 'batch_id' in j...
IIITA-Framework/Py-interpreter
main.py
Python
mit
3,754
0.006127
import json import os import urllib data = {} # Initialising an empty Dictionary print("Chose the language of your preference :") print("1 NodeJs") print("2 php") print("3 Python") print("Enter the number to proceed"), # Storing a {'language':'value'} pair in the Dictionary readInt = int(input()) if(readInt == 1) : ...
file: json.dump(data,outfile,sort_keys=False,indent=4) # Initialise the dependencies key data['dependencies'] = {} # Add dependencies the user selects t
o package.json print("Do you wish to install dependencies for the selected language (Recommended): Y/n"), readStr = raw_input() if(readStr.lower() == 'y') : # Create a node_modules folder in the directory dir_path = os.path.dirname(os.path.realpath(__file__)) fullfoldername = os.path.join(dir_path, './node...
sasha-gitg/python-aiplatform
google/cloud/aiplatform/v1beta1/schema/trainingjob/definition_v1beta1/__init__.py
Python
apache-2.0
3,599
0.001389
# -*- coding: utf-8 -*- # Copyright 2020 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...
tSentimentInputs from .types.automl_time_series_forecasting import AutoMlForecasting from .types.automl_time_series_forecasting import AutoMlForecastingInputs from .types.automl_time_series_forecasting import AutoMlForecastingMetadata from .types.automl_video_action_recognition import AutoMlVideoActionRecognition from ...
ation import AutoMlVideoClassification from .types.automl_video_classification import AutoMlVideoClassificationInputs from .types.automl_video_object_tracking import AutoMlVideoObjectTracking from .types.automl_video_object_tracking import AutoMlVideoObjectTrackingInputs from .types.export_evaluated_data_items_config i...
aaiijmrtt/JUCSE
Compilers/parser.py
Python
mit
6,776
0.029368
_first = dict() _follow = dict() _table = dict() _endsymbol = '$' _emptysymbol = '#' # function to remove left recursion from a subgrammar def recursion(grammar): section = grammar[0][0] nonrecursivegrammar = [[item for item in rule] + [section + 'bar'] for rule in grammar if rule[0] != rule[1]] recursivegrammar = ...
= expression: temporary = temporary.union(follow(rule[0], grammar, terminals, startsymbol
)) _follow[expression] = temporary return _follow[expression] # function to create parsing table def table(grammar, terminals, startsymbol): for rule in grammar: if rule[0] not in _table: _table[rule[0]] = dict() for terminal in terminals: _table[rule[0]][terminal] = set() _table[rule[0]][_endsymbol]...
nkgilley/home-assistant
tests/components/homematicip_cloud/test_light.py
Python
apache-2.0
8,930
0.000224
"""Tests for HomematicIP Cloud light.""" from homematicip.base.enums import RGBColorState from homeassistant.components.homematicip_cloud import DOMAIN as HMIPC_DOMAIN from homeassistant.components.homematicip_cloud.light import ( ATTR_CURRENT_POWER_W, ATTR_TODAY_ENERGY_KWH, ) from homeassistant.components.lig...
aul
t_mock_hap_factory.async_get_mock_hap( test_devices=["Treppe"] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_OFF service_call_counter = len(hmip_device.mock_calls) # Send all color v...
adusca/treeherder
treeherder/credentials/views.py
Python
mpl-2.0
1,507
0.000664
from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse_lazy from django.utils.decorators import method_decorator from django.views.generic import (DetailView, ListView) from django.views.generic.edit import (CreateView, ...
rder_by('-created') class CredentialsCreate(LoginRequiredMixin, CreateView): model = Credentials form_class = CredentialsForm success_url = reverse_lazy('credentials-list') def form_valid(self, form): form.instance.owner = self.request.user return super(CredentialsCreate, self).form_v...
dentials.objects.filter(owner=self.request.user) class CredentialsDelete(LoginRequiredMixin, DeleteView): model = Credentials success_url = reverse_lazy('credentials-list')
jojanper/draalcore
draalcore/auth/sites/fb_oauth.py
Python
mit
2,606
0.001919
#!/usr/bin/env python # -*- coding: utf-8 -*- """Facebook OAuth interface.""" # System imports import json import logging try: from urllib import quote_plus except ImportError: from urllib.parse import quote_plus import oauth2 as oauth from django.conf import settings # Project imports from .base_auth import...
response['status'] == '200': # Get profile info from Facebook base_url = '{}?access_token={}&fields=id,first_name,last_name,email' access_token = json.loads(content)['access_token'] request_url = base_url.format(FACEBOOK_CHECK_AUTH, access_toke
n) response, content = client.request(request_url, 'GET') if response['status'] == '200': user_data = json.loads(content) # Authenticate user logger.debug(user_data) user = self.set_user(user_data) return self.authe...
Grumbel/scatterbackup
scatterbackup/units.py
Python
gpl-3.0
3,221
0.00031
# ScatterBackup - A chaotic backup solution # Copyright (C) 2015 Ingo Ruhnke <[email protected]> # # 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 ...
0 ** 6: return "{:.2f}TB".format(count / 1000**5) elif count < 1000 ** 7: return "{:.2f}EB".format(count / 1000**8) elif count < 1000 ** 8: return "{:.2f}ZB".format(count / 1000**9) else: # count < 1000 ** 9 return "{:.2f}YB".format(count / 1000**10) def bytes2human_binary...
ount) elif count < 1024 ** 2: return "{:.2f}KiB".format(count / 1024**1) elif count < 1024 ** 3: return "{:.2f}MiB".format(count / 1024**2) elif count < 1024 ** 4: return "{:.2f}GiB".format(count / 1024**3) elif count < 1024 ** 5: return "{:.2f}TiB".format(count / 1024**4...
apollo-ng/governess
server/tests/test_range_overlap.py
Python
gpl-3.0
432
0.023148
from ranges import range_overlap def test_no_overlap(): assert range_overlap([ (0.0, 1.0), (5.0, 6.0)
]) == None def test_length_zero_overlap(): assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == None def test_single_range(): assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0) def test_negative_range(): assert range_overlap([ (0.0, 1.0), (0.0, 2.0),
(-1.0, 1.0) ]) == (0.0, 1.0)
antoinecarme/pyaf
tests/artificial/transf_Fisher/trend_PolyTrend/cycle_30/ar_/test_artificial_32_Fisher_PolyTrend_30__100.py
Python
bsd-3-clause
262
0.087786
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_lengt
h = 30, transform = "Fisher", sigma
= 0.0, exog_count = 100, ar_order = 0);
Gr1N/wuffi
setup.py
Python
mit
1,554
0
# -*- coding: utf-8 -*- from io import open from setuptools import setup, find_packages setup( name='wuffi', version='0.0.0', description='TBD', long_description=open('README.md', encoding='utf-8').read(), author='Nikita Grishko', author_email='[email protected]', url='https://g...
se, classifiers=( 'Development Status :: 1 - Planning', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming
Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', ) )