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
ahtn/keyplus
host-software/keyplus/keycodes/lang_map/French0.py
Python
mit
2,191
0.00046
# Copyright 2018 [email protected] # Licensed under the MIT license (http://opensource.org/licenses/MIT) from hid_keycodes import * lang = 'French' country = 'Belgium, Luxembourg' scancode_map = { KC_0: ('à', '0', '}', '', '', ''), KC_1: ('&', '1', '|', '', '', ''), KC_2: ('é', '2', '@', '', '', ''), KC_...
, '', '', '', ''), KC_E: ('e', 'E', '€', '', '', ''), KC_F: ('f', 'F', '', '', '', ''), KC_G: ('g', 'G', '', '', '', ''), KC_H:
('h', 'H', '', '', '', ''), KC_I: ('i', 'I', '', '', '', ''), KC_J: ('j', 'J', '', '', '', ''), KC_K: ('k', 'K', '', '', '', ''), KC_L: ('l', 'L', '', '', '', ''), KC_M: (',', '?', '', '', '', ''), KC_N: ('n', 'N', '', '', '', ''), KC_O: ('o', 'O', '', '', '', ''), KC_P: ('p', 'P', '', '...
Microvellum/Fluid-Designer
win64-vc/2.78/Python/bin/2.78/scripts/addons/object_edit_linked.py
Python
gpl-3.0
10,814
0.002312
# ***** 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 distribute...
he # GNU General Public License for more details. # # You should
have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ***** END GPL LICENCE BLOCK ***** bl_info = { "name": "Edit Linked Library", "author": "Jason van Gumster (F...
edmorley/django
django/core/files/locks.py
Python
bsd-3-clause
3,512
0.000285
""" Portable file locking utilities. Based partially on an example by Jonathan Feignberg in the Python Cookbook [1] (licensed under the Python Software License) and a ctypes port by Anatoly Techtonik for Roundup [2] (license [3]). [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 [2] http://sourceforg...
APPED] UnlockFileEx = windll.kernel32.UnlockFileEx UnlockFileEx.restype = BOOL UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED] def lock(f, flags): hfile = msvcrt.get_osfhandle(_fd(f)) overlapped = OVERLAPPED() ret = LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, ...
e, 0, 0, 0xFFFF0000, byref(overlapped)) return bool(ret) else: try: import fcntl LOCK_SH = fcntl.LOCK_SH # shared lock LOCK_NB = fcntl.LOCK_NB # non-blocking LOCK_EX = fcntl.LOCK_EX except (ImportError, AttributeError): # File locking is not supported. L...
endavis/bastproxy
plugins/core/events.py
Python
gpl-2.0
13,653
0.007691
""" This plugin handles events. You can register/unregister with events, raise events ## Using ### Registering an event from a plugin * ```self.api('events.register')(eventname, function)``` ### Unregistering an event * ```self.api('events.unregister')(eventname, function)``` ### Raising an event * ```self.api(...
parser) parser = argp.ArgumentParser(add_help=False, description='raise an event') parser.add_argument('event',
help='the event to raise', default='', nargs='?') self.api('commands.add')('raise', self.cmd_raise, parser=parser) self.api('events.register')('plugin_unloaded', self.pluginunloaded, prio=10) ...
lamdnhan/osf.io
website/project/views/comment.py
Python
apache-2.0
8,811
0.000454
# -*- coding: utf-8 -*- import collections import httplib as http import pytz from flask import request from modularodm import Q from framework.exceptions import HTTPError from framework.auth.decorators import must_be_logged_in from framework.auth.utils import privacy_info_handle from framework.forms.utils import san...
h) @must_be_logged_in @must_be_contributor_or_public def delete_comment(**kwargs): auth = kwargs['auth'] comment = kwargs_to_comment(kwargs, owner=True) comment.delete(auth=a
uth, save=True) return {} @must_be_logged_in @must_be_contributor_or_public def undelete_comment(**kwargs): auth = kwargs['auth'] comment = kwargs_to_comment(kwargs, owner=True) comment.undelete(auth=auth, save=True) return {} @must_be_logged_in @must_be_contributor_or_public def update_comme...
egrigg9000/taskbuster_boilerplate
taskbuster/wsgi.py
Python
mit
397
0
""" WSGI config for taskbuster 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.8/ho
wto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJ
ANGO_SETTINGS_MODULE", "taskbuster.settings") application = get_wsgi_application()
prophile/jacquard
setup.py
Python
mit
4,910
0.001018
from setuptools import setup, find_packages import os import sys # This monstrous hack is to support /etc generation for the Debian package # with fpm. if sys.argv[1] == 'install' and os.environ.get('JACQUARD_DEBIAN_HACK'): def debian_etc_hack(root): import pathlib root_path = pathlib.Path(root) ...
ar-overrides = jacquard.users.commands:OverrideClear', 'runserver = jacquard.service.commands:RunServer', 'launch = jacquard.experiments.commands:Launch', 'conclude = jacquard.experiments.commands:Conclude', 'load-experiment = jacquard.experiments.commands:Load', ...
ommands:SettingsUnderActiveExperiments', 'bugpoint = jacquard.commands_dev:Bugpoint', ), 'jacquard.commands.list': ( 'experiments = jacquard.experiments.commands:ListExperiments', ), 'jacquard.commands.show': ( 'user = jacquard.users.commands:Show', ...
procangroup/edx-platform
lms/djangoapps/ccx/utils.py
Python
agpl-3.0
16,422
0.001705
""" CCX Enrollment operations for use by Coach APIs. Does not include any access control, be sure to check access before calling. """ import datetime import logging from contextlib import contextmanager from smtplib import SMTPException import pytz from django.contrib.auth.models import User from django.core.exceptio...
hat might happen. if ccxs.exists(): return ccxs[0] return None def get_ccx_by_ccx_id(course, coach, ccx_id): """ Finds a CCX of given coach on given master course. Arguments: course (CourseDescriptor): Master course coach (User): Coach to ccx ccx_id (long): Id of c...
ccx (CustomCourseForEdX): Instance of CCX. """ try: ccx = CustomCourseForEdX.objects.get( id=ccx_id, course_id=course.id, coach=coach ) except CustomCourseForEdX.DoesNotExist: return None return ccx def get_valid_student_with_email(identi...
jorisvandenbossche/2015-EuroScipy-pandas-tutorial
snippets/07 - Case study - air quality data64.py
Python
bsd-2-clause
110
0.009091
df2011 =
data['2011'].dropna() df2011.groupby(df2011.index.week)[['BETN029', 'BETR801']].quantile(0.95).plo
t()
pybursa/homeworks
a_berezovsky/hw2/task08.py
Python
gpl-2.0
745
0.001653
# coding=utf-8 """ Задание 8: Двууровневый кортеж. (бонусное) УСЛОВИЕ: Фраг
мент кода, который принимает кортеж любых чисел и модифицирует его в кортеж кортежей по два элемента (парами). Пример: (1,4,8,6,3,7,1) >> ((1,4),(8,6),(3,7),(1,)) """ def task08(input_data): return_data = [] for index in xrange(0, len(input_data), 2): try: return_data.append((input_data[in...
8((1, 4, 8, 6, 3, 7, 1))
googleapis/python-bigquery-sqlalchemy
sqlalchemy_bigquery/base.py
Python
mit
38,084
0.000814
# Copyright (c) 2017 The sqlalchemy-bigquery Authors # # 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, mer...
r substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE...
amcat/amcat
api/rest/viewsets/sentence.py
Python
agpl-3.0
2,276
0.002197
###########################
##################################
############## # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # # #...
joshzarrabi/e-mission-server
emission/core/wrapper/tour_model.py
Python
bsd-3-clause
318
0.018868
import logging import emission.core.wrapper.wrapperbase as ecwb class TourModel(ecwb.WrapperBase): props = {"user_id" : ecwb.WrapperBase.Access.WORM, # user_id of the E-Missions user the graph represnts }
geojson = [] enums = {} nullable = [] def _populateDependencies(self): pass
gloaec/bamboo
tests/__init__.py
Python
gpl-3.0
2,708
0
# -*- coding: utf-8 -*- """ Unit Tests ~~~~~~~~~~ Define TestCase as base class for unit tests. Ref: http://packages.python.org/Flask-Testing/ """ from flask.ext.testing import TestCase as Base, Twill from bambooapp import create_app from bambooapp.user import User, UserDetail, ADMIN, USER, ACTIVE fr...
10, url=u'http://demo.example.com', deposit=100.00, location=u'Hangzhou', bio=u'admin Guy is ... hmm ... just a demo guy.')) admin = User( name=u'admin', email=u'[email protected]',
password=u'123456', role_code=ADMIN, status_code=ACTIVE, user_detail=UserDetail( sex_code=MALE, age=10, url=u'http://admin.example.com', deposit=100.00, loc...
PeterPetrik/QGIS
tests/src/python/test_qgscheckablecombobox.py
Python
gpl-2.0
1,824
0
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsCheckableComboBox .. note:: 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. "...
self.assertEqual(w.separator(), '|') w.setDefaultText('Select items...') self.assertEqual(w.defaultText(), 'Select items...') w.addItems(['One', 'Two', 'Three']) w.setCheckedItems(
['Two']) self.assertEqual(len(w.checkedItems()), 1) self.assertEqual(w.checkedItems(), ['Two']) w.setCheckedItems(['Three']) self.assertEqual(len(w.checkedItems()), 2) self.assertEqual(w.checkedItems(), ['Two', 'Three']) w.setItemCheckState(2, Qt.Unchecked) self....
slavpetroff/sweetshop
backend/django/apps/testimonials/apps.py
Python
mit
99
0
from django.apps import AppConfig class TestimonialsConfi
g(AppConfig):
name = 'testimonials'
privateLittleVaginalTeasingMogicSchool/Fall-of-Cinnamon-Twig
Demo-Kazeshima-Python/card.py
Python
gpl-3.0
2,152
0.014405
# [email protected] # 03.13.2017 UTC # A simple relization of idea. from math import pow as power class Hero: 'Class of Hero car
d. Dinstinct hero has fixed Chuang, Zhi and Fu properties' Name = '' Chuang = 0 Zhi = 0 Fu = 0 MaxFanNum = 1 # The number of fans is HP BaseAtk = 1 BaseDef = 1 BaseRep = 1 # Reputation is Mana. If a hero wants to use magic attack, typically an evil and dispicable behavior, it will consum...
= 0 # unit of CyberAge is 3 months def __init__(self, initCyberAge = 0, genChuang, genZhi, genFu, name = ''): self.Chuang = genChuang self.Zhi = genZhi self.Fu = genFu self.Name = name CA = self.CyberAge self.MaxFanNum = CA*genFu*1000 + CA*genZhi*750 + CA*genChu...
kinow-io/kinow-python-sdk
test/test_customer_group_video_stats_list_response.py
Python
apache-2.0
939
0.003195
# coding: utf-8 """ Server API Reference for Server API (REST/Json) OpenAPI spec version: 2.
0.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import abso
lute_import import os import sys import unittest import kinow_client from kinow_client.rest import ApiException from kinow_client.models.customer_group_video_stats_list_response import CustomerGroupVideoStatsListResponse class TestCustomerGroupVideoStatsListResponse(unittest.TestCase): """ CustomerGroupVideoSta...
Mirantis/pumphouse
pumphouse/tasks/user.py
Python
apache-2.0
4,857
0
# Copyright (c) 2014 Mirantis 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 writing, ...
mat(user_id) user_retrieve = "{}-retrieve".format(user_binding) user_ensure = "{}-ensure".format(user_binding) fl
ow = linear_flow.Flow("migrate-user-{}".format(user_id)) flow.add(RetrieveUser(context.src_cloud, name=user_binding, provides=user_binding, rebind=[user_retrieve])) if tenant_id is not None: tenant_ensure = "tenant-{}-ensure"....
spatialfrog/soil_tools
qgis/qgis_progressing_framework_scripts/src/2_calculate_cmp_soil_table_column.py
Python
gpl-3.0
3,985
0.011292
""" purpose: process the cmp table for single column calculation and csv output notes: user must select shapefile column that defines the slc ids. thses are used for processing if no polygons selected than all polygons processed input: slc shapefile field defining the slc ids cmp table column for processing output: ...
actual table name tableName = utils.getQgisTableLayerFilePathInfo(cmp_soil_table, pathKey="table") # warn user process may take several minutes message = "Calculating column %s may take several minutes" % (
calculationColumnName) utils.communicateWithUserInQgis(message,messageExistanceDuration=10) headers, results = db.calculateField(slcIds, dbSlcKey=option_soil_cmp_table_slc_id_column, tableName=tableName, columnName=calculationColumnName, dbPercentKey=option_soil_cmp_table_percent_column) outCsvFilePath = io.writeC...
OCA/stock-logistics-warehouse
account_move_line_product/__manifest__.py
Python
agpl-3.0
560
0
# Copyright 2019 ForgeFlow
S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Move Line Product", "version": "14.0.1.0.0", "summary": "Displays the product in the journal entries and items", "author": "ForgeFlow, Odoo Community Association (OCA)", "websit...
"data": ["views/account_move_line_view.xml"], "installable": True, }
ChileanVirtualObservatory/acalib
setup.py
Python
gpl-3.0
2,129
0.014091
from setuptools import setup, find_packages from setuptools.command.install import install from shutil import copyfile import os import glob import sys import subprocess def check_build(): good_commands = ('develop', 'sdist', 'build', 'build_ext', 'build_py', 'build_clib', 'build_scripts', '...
description = "Advanced Computing for Astronomy Library", url = "https://github.com/ChileanVirtualObservatory/ACALIB", author = "CSRG", author_email = '[email protected]',
classifiers = [ 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Astronomy', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6' ], zip_safe = False, packages = find_packages(), ...
log2timeline/plaso
tests/parsers/winevt.py
Python
apache-2.0
2,807
0.002494
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Windows EventLog (EVT) parser.""" import unittest from plaso.lib import definitions from plaso.parsers import winevt from tests.parsers import test_lib class WinEvtParserTest(test_lib.ParserTestCase): """Tests for the Windows EventLog (EVT) parser."...
c0000388)" expected_string2 = ( '"The system detected a possible attempt to compromise security. ' 'Please ensure that you can contact the server that authenticated you.' '\r\n (0xc0000388)"') expected_event_values = { 'computer_name': 'WKS-WINXP32BIT', 'date_time': '20...
cord', 'event_category': 3, 'event_identifier': 40961, 'event_type': 2, 'record_number': 1392, 'severity': 2, 'source_name': 'LSASRV', 'strings': ['cifs/CONTROLLER', expected_string2], 'timestamp_desc': definitions.TIME_DESCRIPTION_WRITTEN} self.Check...
galihmelon/sendgrid-python
sendgrid/helpers/mail/subscription_tracking.py
Python
mit
1,603
0.000624
class SubscriptionTracking(object): def __init__(self, enable=None, text=None, html=None, substitution_tag=None): self._enable = None self._text = None self._html = None self._substitution_tag = None if enable is not None: self.enable = enable if text is...
= text if html is not None: self.html = html if substitution_tag is not None: self.substitution_tag = substitution_tag @property def ena
ble(self): return self._enable @enable.setter def enable(self, value): self._enable = value @property def text(self): return self._text @text.setter def text(self, value): self._text = value @property def html(self): return self._html @htm...
bruxr/Sirius2
sirius/services/sentry.py
Python
mit
1,881
0.002127
import os import json from google.appengine.api import urlfetch from sirius.errors import APIError API_BASE = 'https://app.getsentry.com/api/0' class SentryError(APIError): """Raised when an error is received from Sentry.""" def create_project(name): """Creates a project in Sentry. This assumes that sen...
ient key for a project. Arguments: slug -- project slug Returns client's secret DSN key """ org = os.environ['SENTRY_ORG'] headers = { 'Authorization': 'Basic ' + os.environ['SENTRY_KEY'], 'Con
tent-Type': 'application/json' } payload = json.dumps({'name': 'Default'}) url = '{0}/projects/{1}/{2}/keys/'.format(API_BASE, org, slug) result = urlfetch.fetch( url=url, payload=payload, method=urlfetch.POST, headers=headers ) response = json.loads(result.conte...
openvstorage/openvstorage-flocker-driver
openvstorage_flocker_plugin/__init__.py
Python
apache-2.0
1,409
0.00071
# Copyright 2015 iNuron NV # # Licensed under the Open vStorage Modified Apache License (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.openvstorage.org/license # # 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 CONDITIO...
cense for the specific language governing permissions and # limitations under the License. from flocker.node import BackendDescription, DeployerType from openvstorage_flocker_plugin.openvstorage_blockdevice import ( openvstorage_from_configuration ) __author__ = "Chrysostomos Nanakos" __copyright__ = "Copyright 20...
wevote/WebAppPublic
apis_v1/documentation_source/organizations_followed_retrieve_doc.py
Python
bsd-3-clause
3,459
0.002024
# apis_v1/documentation_source/organizations_followed_retrieve_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def organizations_followed_retrieve_doc_template_values(url_root): """ Show documentation about organizationsFollowedRetrieve """ required_query_parameter_list = [ ...
te": string (website address),\n' \ ' "organization_twitter_handle": string (twitter address),\n' \ ' "twitter_followers_count": integer,\n' \ ' "organization_email": string,\n' \ ' "organization_facebook": string,\n' \ ...
ame': 'organizationsFollowedRetrieve', 'api_slug': 'organizationsFollowedRetrieve', 'api_introduction': "", 'try_now_link': 'apis_v1:organizationsFollowedRetrieveView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_p...
earlysaints/database
datasets/nauvoo_deeds/persons2quad.py
Python
gpl-2.0
892
0.005605
from xml.dom import minidom import codecs inxml = minidom.parse(r'm_persons.xml') outcsv = codecs.open(r'person_quads.csv', 'w', 'utf-8') outcsv.write('id,assert_type,subject,predicate,object\r\n') i=1 for person in inxml.getElementsByTagName('personk'): pid = 'I'+person.getElementsByTagName('PERSON_ID')[0].childN...
'+pid+',common name,|'+pname+'|\r\n') outcsv.write(str(i+1)+',property,'+pid+',entity type,person\r\n') pcontentel = person.getElementsByTagName('CONTENT') if pcontentel: pcontent = pcontentel[0].childNodes[0].data pcontent.replace('&lt;','<') pcontent = "<br />".join(pcontent.split(...
sh() outcsv.close()
Simulmedia/pyembedpg
pyembedpg.py
Python
apache-2.0
10,244
0.003221
# # Copyright 2015 Simulmedia, 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 wr...
on(self): """ Return the latest version on the Postgres FTP server :return: latest version installed locally on the Postgres FTP server """ response = requests.get(PyEmbedPg.DOWNLOAD_BASE_URL) last_version_match = list(re.finditer('>v(?P<version>[^<]+)<', response
.content.decode()))[-1] return last_version_match.group('version') def check_version_present(self): """ Check if the version is present in the cache :return: True if the version has already been downloaded and build, False otherwise """ return os.path.exists(self._ve...
jsmesami/naovoce
src/gallery/migrations/0002_image_author.py
Python
bsd-3-clause
598
0.001672
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('gallery', '0001_initial'), ] ope...
grations.AddField( model_name='image', name='author', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, blank=True, null=True, verbose_name='author', r
elated_name='images', on_delete=models.CASCADE), ), ]
vorburger/mcedit2
src/mcedit2/editortools/brush/__init__.py
Python
bsd-3-clause
8,331
0.00168
""" brush """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.command import SimplePerformCommand from mcedit2.editortools.brush.masklevel import FakeBrushSection from mcedit2.editort...
iconName = "brush" maxBrushSize = 512 def __init__(self, editorSession, *args, **kwargs): super(BrushTool, self).__init__(editorSession, *args, **kwargs) self.toolWidget = load_ui("editortools/brush.ui") self.brushMode = None self.brushLoader = None BrushModeSetting.c...
Changed) self.cursorWorldScene = None self.cursorNode = TranslateNode() self.toolWidget.xSpinSlider.setMinimum(1) self.toolWidget.ySpinSlider.setMinimum(1) self.toolWidget.zSpinSlider.setMinimum(1) self.toolWidget.xSpinSlider.valueChanged.connect(self.setX) sel...
moraleslazaro/cockpit
pkg/storaged/luksmeta-monitor-hack.py
Python
lgpl-2.1
5,420
0.010148
#! /usr/bin/python3 # This simulates the org.freedesktop.UDisks.Encrypted.Slots property # et al for versions of UDisks that don't have them yet. import sys import json import subprocess import re import base64 import signal import atexit import os def b64_decode(data): # The data we get doesn't seem to have any...
if slot not in slots: s
lots[slot] = entry if in_luks2_token_section: match = re.match(b" ([0-9]+): clevis$", line) if match: try: token = subprocess.check_output([ "cryptsetup", "token", "export", dev, "--token-id", match.group(1) ], ...
lekshmideepu/nest-simulator
testsuite/pytests/test_connect_all_to_all.py
Python
gpl-2.0
6,019
0
# -*- coding: utf-8 -*- # # test_connect_all_to_all.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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...
M = hf.get_weighted_connectivity_matrix( self.pop1, self.pop2, 'receptor') M = hf.gather_data(M) if M is not None: M = M.flatten() frequencies = scipy.stats.itemfreq(M) self.assertTrue(np.array_equal(frequencies[:, 0], np.arange( 1, n_rpo...
self.assertGreater(p, self.pval) def suite(): suite = unittest.TestLoader().loadTestsFromTestCase(TestAllToAll) return suite def run(): runner = unittest.TextTestRunner(verbosity=2) runner.run(suite()) if __name__ == '__main__': run()
sclc/NAEF
src/chebyshev_basis_cacg.py
Python
gpl-3.0
13,294
0.010832
"""CBCG method """ from chebyshev_polynomial import ChebyshevPolynomial from gerschgorin_circle_theorem import GerschgorinCircleTheoremEigenvalueEstimator import numpy as np from scipy.sparse import linalg class CBCG(): """ """ def
__init__(self): pass def cbcg_solver(self, mat, rhs, init_x, step_val, tol, maxiter): gerschgorin_estimator = GerschgorinCircleTheoremEigenvalueEstimator() max_eigenvalue, min_eigenvalue = gerschgorin_estimator.csr_mat_extreme_eigenvalue_estimation(mat) chebyshev_basis_generator = ...
yshevPolynomial() op_A = linalg.aslinearoperator(mat) v_r = rhs - op_A(init_x) v_x = init_x.copy() s_normb = np.linalg.norm(rhs) residual_ratio_hist = [np.linalg.norm(v_r)/s_normb] for itercounter in range(1, maxiter+1): m_chebyshev_basis = \ ...
yuriyarhipov/FeatureRequestApp
models.py
Python
mit
1,068
0
from flask_sqlalchemy import SQLAlchemy db = SQLAl
chemy() class Client(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) def __init__(self, name): self.name = name def __repr__(self): return '<Client %r>' % self.name class Area(db.Model): i
d = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) def __init__(self, name): self.name = name def __repr__(self): return '<Area %r>' % self.name class Feature(db.Model): id = db.Column(db.Integer, primary_key=True) description = db.Column(db.Text) cli...
ShaguptaS/python
bigml/tests/create_batch_prediction_steps.py
Python
apache-2.0
8,511
0.004582
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2012, 2015 BigML # # 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 requ...
= HTTP_CREATED world.location = resource['location'] world.batch_centroid = resource['object'] world.batch_centroids.append(resource['resource']) #@step(r'I create a batch anomaly score$') def i_create_a_batch_prediction_with_anomaly(step): dataset = world.dataset.get('resource') anomaly = world.an...
on = resource['location'] world.batch_anomaly_score = resource['object'] world.batch_anomaly_scores.append(resource['resource']) #@step(r'I create a source from the batch prediction$') def i_create_a_source_from_batch_prediction(step): ba
AstroMatt/esa-subjective-time-perception
backend/api_v2/migrations/0009_trial_is_valid.py
Python
mit
496
0.002016
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-
02-21 21:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api_v2', '0008_auto_20170101_0105'), ] operations = [ migrations.AddField( model_name='trial', name='is_valid', ...
lBooleanField(db_index=True, default=None, verbose_name='Is Valid?'), ), ]
ajyoon/brown
examples/feldman_projections_2/score.py
Python
gpl-3.0
5,802
0.000862
from typing import Union from brown import constants from brown.core import brown from brown.core.music_font import MusicFont from brown.core.object_group import ObjectGroup from brown.core.path import Path from brown.core.pen import Pen from brown.core.pen_pattern import PenPattern from brown.core.staff import Staff ...
truments) else None ) drawing = False for measure_num in range(self.measure_count + 1): if Score._divider_visible( instrument_above, instrument_below, measure_num ): if not drawing: curren...
(measure_num), GridUnit(0)) drawing = True else: if drawing: current_path.line_to(Measure(measure_num), GridUnit(0)) drawing = False def draw_bar_lines(self): for measure_num in range(self.measure_co...
tomvansteijn/xsb
xsboringen/scripts/xsb.py
Python
gpl-3.0
1,552
0.005799
# -*- coding: utf-8 -*- # Royal HaskoningDHV from xsboringen.scripts.write_csv import write_csv from xsboringen.scripts.write_shape import write_shape from xsboringen.scripts.plot import plot_cross_section import click import yaml from collections import ChainMap import log
ging import os log = logging.getLogger(os.path.basename(__file__)) @click.command() @click.argument('function', type=click.Choice(['write_csv', 'write_shape', 'plot']), ) @click.argument('inputfile', ) @click.option('--logging', 'level', type=click.Choice(['warning', 'info', 'debug']), default='i...
# function arguments from input file with open(inputfile) as y: kwargs = yaml.load(y) # read default config scripts_folder = os.path.dirname(os.path.realpath(__file__)) defaultconfigfile = os.path.join(os.path.dirname(scripts_folder), 'defaultconfig.yaml') with open(defaultconfigfi...
keedio/sahara
sahara/service/edp/spark/engine.py
Python
apache-2.0
8,343
0
# Copyright (c) 2014 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 ...
raise_when_error=False) if ret == 0: # We had some effect, check the status return self._get_job_status_from_remote(r, pid, job_execution) def get_job_...
_execution): pid, instance = self._get_instance_if_running(job_execution) if instance is not None: with remote.get_remote(instance) as r: return self._get_job_status_from_remote(r, pid, job_execution) def _job_script(self): path = "service/edp/resources/launch_co...
frascoweb/frasco-upload
frasco_upload/backends.py
Python
mit
1,658
0.000603
from frasco import current_app, url_for from flask import safe_join import os upload_backends = {} def file_upload_backend(cls): upload_backends[cls.name] = cls return cls class StorageBackend(object): def __init__(self, options): self.options = options def save(self, file, filename): ...
url_for(self, filename, **kwargs): raise NotImplementedError def delete(self, filename): raise NotImplementedError @file_upload_backend class LocalStorageBackend(StorageBackend): name = 'local' def save(self, file, filename): filename = safe_join(self.options["upload_dir"], filen...
root_path, filename) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) file.save(filename) def url_for(self, filename, **kwargs): return url_for("static_upload", filename=filename, **kwargs) def delete(self, filename): ...
telefonicaid/murano
murano/tests/functional/engine/base.py
Python
apache-2.0
12,267
0
# Copyright (c) 2014 Mirantis, 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...
nvironment_name, post_body) self.deployment_success_check(env, 80) def test_deploy_postgresql(self): post_body = { "instance": { "flavor": "m1.medium", "image": self.linux, "assignFloatingIp": True, "?": { ...
"testMurano" }, "name": "teMurano", "database": "test_db", "username": "test_usr", "password": "test_pass", "?": { "type": "io.murano.databases.PostgreSql", "id": str(uuid.uuid4()) } } e...
HaroldMills/Vesper
vesper/util/tests/test_yaml_utils.py
Python
mit
1,582
0.008217
from vesper.tests.test_case import TestCase import vesper.util.yaml_utils as yaml_utils class YamlUtilsTests(TestCase): def test_dump_and_load(self): x = {'x': 1, 'y': [1, 2, 3], 'z': {'one': 1}} s = yaml_utils.dump(x) y = yaml_utils.load(s) self.assertEqual(x, y) ...
" x = yaml_utils.load('12:34:56') self.assertEqual(x, '12:34:56') # def test_numpy_scalar_dump(self): # # """ # This test shows that you can't dump a NumPy scalar, since the # dumper doesn't know how to represent its type. Perhaps we could ...
ort numpy as np # x = np.arange(3) # s = yaml_utils.dump(x[1]) # self.assertEqual(s, '1')
diogocs1/comps
web/addons/account_budget/wizard/account_budget_crossovered_summary_report.py
Python
apache-2.0
2,191
0.000913
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
is program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class
account_budget_crossvered_summary_report(osv.osv_memory): """ This wizard provides the crossovered budget summary report' """ _name = 'account.budget.crossvered.summary.report' _description = 'Account Budget crossvered summary report' _columns = { 'date_from': fields.date('Start of peri...
obeattie/sqlalchemy
test/base/test_except.py
Python
mit
5,046
0.014665
"""Tests exceptions and DB-API exception wrapping.""" from sqlalchemy import exc as sa_exceptions from sqlalchemy.test import TestBase # Py3K #StandardError = BaseException # Py2K from exceptions import StandardError, KeyboardInterrupt, SystemExit # end Py2K class Error(StandardError): """This class will be old-s...
s.DBAPIError, e: self.assert_(True) self.assert_('Error in str() of DB-API' in e.args[0]) def test_db_error_noncompliant_dbapi(self): try:
raise sa_exceptions.DBAPIError.instance( '', [], OutOfSpec()) except sa_exceptions.DBAPIError, e: self.assert_(e.__class__ is sa_exceptions.DBAPIError) except OutOfSpec: self.assert_(False) # Make sure the DatabaseError recognition logic is lim...
gboone/wedding.harmsboone.org
posts/models.py
Python
mit
597
0.025126
from django.db import models from django.core.urlresolvers import reverse class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=255) descript
ion = models.CharField(max_length=255) content = models.TextField() published = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) content_id = models.CharField(max_length=64) class Meta: ordering = ['-created']
def __unicode__(self): return u'%s' % self.title def get_absolute_url(self): return reverse('mysite.views.post', args=[self.slug])
FedoraScientific/salome-hexablock
src/TEST_PY/test_v6/monica.py
Python
lgpl-2.1
5,353
0.034
# !/bin/python # -*- coding: latin-1 -*- # Copyright (C) 2009-2014 CEA/DEN, EDF R&D # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your opt...
]) tabquad[0]. setColor (5) cible . setColor (5) save_vtk () va1 = tabquad[0].getVertex (0) va2 = tabquad[0].getVertex (1) vb1 = cible.nearestVertex (va1) vb2 = cible.nearestVertex (va2) doc.setLevel (1) doc.joinQuadsUni (tabquad, cible, va1, vb1, va2, vb2, 1) hexabloc
k.what () save_vtk () return doc.setLevel (1) for nv in range (8) : ier = doc.mergeVertices (tabv0[nv], tabv1[nv]) print "ier = ", ier save_vtk () # ======================================================= test_monica def test_monica () : orig = doc.addVertex (0,0,0) ...
ActiveState/code
recipes/Python/577863_Context_manager_prevent_calling_code_catching/recipe-577863.py
Python
mit
195
0.010256
from
contextlib impor
t contextmanager @contextmanager def failnow(): try: yield except Exception: import sys sys.excepthook(*sys.exc_info()) sys.exit(1)
ianstalk/Flexget
flexget/components/sites/sites/newtorrents.py
Python
mit
5,069
0.001381
import re from urllib.parse import quote from loguru import logger from flexget import plugin from flexget.components.sites.urlrewriting import UrlRewritingError from flexget.components.sites.utils import normalize_unicode, torrent_availability from flexget.entry import Entry from flexget.event import event from flex...
['urlrewriter', 'search'],
api_ver=2)
isb-cgc/ISB-CGC-Webapp
bq_data_access/v2/seqpeek/seqpeek_view.py
Python
apache-2.0
7,709
0.001686
# # Copyright 2015-2019, Institute for Systems Biology # # 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 ...
e_label': hugo_symbol, 'tracks': track_data,
'protein': protein_data } # Pre-processing # - Sort mutations by chromosomal coordinate for track in plot_data['tracks']: track['mutations'] = sort_track_mutations(track['mutations']) # Annotations # - Add label, possibly human readable # - Add type ...
pallamidessi/mvrptw
gen/protobuf/vehicleType_pb2.py
Python
mit
1,823
0.006583
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: vehicleType.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message a...
type=None), _descriptor.EnumValueDescriptor( name='Taxi', index=3, number=3, options=None, type=None), ], containing_type=None, options=None, serialized_start=21, serialized_end=80, ) _sym_db.RegisterEnumDescriptor(_TYPEOFVEHICLE) TypeOfVehicle = enu
m_type_wrapper.EnumTypeWrapper(_TYPEOFVEHICLE) VSL = 0 TPMR = 1 Ambulance = 2 Taxi = 3 DESCRIPTOR.enum_types_by_name['TypeOfVehicle'] = _TYPEOFVEHICLE # @@protoc_insertion_point(module_scope)
mikesun/xen-cow-checkpointing
tools/python/scripts/xapi.py
Python
gpl-2.0
29,258
0.011484
#!/usr/bin/python #============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distribu...
============================================= imp
ort sys import time import re import os sys.path.append('/usr/lib/python') from xen.util.xmlrpclib2 import ServerProxy from optparse import * from pprint import pprint from types import DictType from getpass import getpass # Get default values from the environment SERVER_URI = os.environ.get('XAPI_SERVER_URI', 'http:...
apple/coremltools
coremltools/converters/sklearn/_converter.py
Python
bsd-3-clause
5,804
0.000517
# Copyright (c) 2017, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from coremltools import __version__ as ct_version from coremltools.models import _METADATA_VERSION, _MET...
Returns ------- model:MLModel Returns an MLModel instance representing a Core ML model. Examples -------- .. sourcecode:: python >>> from sklearn.linear_model import LinearRegression >>> import pandas as pd # Load data >>> data = pd.read_csv('houses.csv...
a[["bedroom", "bath", "size"]], data["price"]) # Convert and save the scikit-learn model >>> import coremltools >>> coreml_model = coremltools.converters.sklearn.convert(model, ["bedroom", "bath", "size"], ...
plotly/python-api
packages/python/plotly/plotly/validators/mesh3d/colorbar/_lenmode.py
Python
mit
523
0.001912
import _plotly_utils.basevalidators cla
ss LenmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="lenmode", parent_name="mesh3d.colorbar", **kwargs): super(LenmodeValidator, self).__init__( plotly_name=plotly_name, parent_name
=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), role=kwargs.pop("role", "info"), values=kwargs.pop("values", ["fraction", "pixels"]), **kwargs )
kfelzenbergs/smartalarm-api
smartalarm/manage.py
Python
gpl-3.0
808
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smartalarm.settings")
try:
from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django exce...
hallvors/mobilewebcompat
preproc/webcompat_data_exporter.py
Python
mpl-2.0
6,094
0.001477
#!/usr/bin/env python2.7 # encoding: utf-8 ''' extract_id_title.py Created by Hallvord R. M. Steen on 2014-10-25. Modified by Karl Mozilla Public License, version 2.0 see LICENSE Dumps data from webcompat.com bug tracker by default creates one CSV file (webcompatdata.csv) and one JSON file (webcompatdata-bzlike.json)...
os/webcompat/web-bugs" VERBOSE = True # Seconds. Loading searches c
an be slow socket.setdefaulttimeout(240) def get_remote_file(url, req_json=False): print('Getting '+url) req = urllib2.Request(url) req.add_header('User-agent', 'AreWeCompatibleYetBot') if req_json: req.add_header('Accept', 'application/vnd.github.v3+json') bzresponse = urllib2.urlopen(req...
mozman/ezdxf
integration_tests/test_recover.py
Python
mit
4,960
0
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import os import pytest import random from ezdxf import recover from ezdxf.audit import AuditError from ezdxf.lldxf.tagger import tag_compiler, ascii_tags_loader BASEDIR = os.path.dirname(__file__) DATADIR = "data" RECOVER1 = "recover01.dxf" RECOVER2 = "rec...
ssert tags[:100] == tags[:100] def test_rebuild_sections(tags01): tool = recover.Recover() sections = tool.rebuild_sections(tags01) expected = sum(int(tag == (0, "SECTION")) for tag in tags01) orphans = sections.pop(
) assert len(sections) == expected assert len(orphans) == 4 def test_build_section_dict(tags01): tool = recover.Recover() sections = tool.rebuild_sections(tags01) tool.load_section_dict(sections) assert len(tool.section_dict) == 2 header = tool.section_dict["HEADER"][0] assert len(head...
SCIP-Interfaces/PySCIPOpt
examples/finished/gcp_fixed_k.py
Python
mit
2,648
0.018505
##@file gcp_fixed_k.py #@brief solve the graph coloring problem with fixed-k model """ Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012 """ from pyscipopt import Model, quicksum, multidict def gcp_fixed_k(V,E,K): """gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph Parameters...
isection and fixed-k model Parameters: - V: set/list of nodes in the graph - E: set/list of edges in the graph Returns tuple with number of colors used, and dictionary mapping colors to vertices """
LB = 0 UB = len(V) color = {} while UB-LB > 1: K = int((UB+LB) / 2) gcp = gcp_fixed_k(V,E,K) # gcp.Params.OutputFlag = 0 # silent mode #gcp.Params.Cutoff = .1 gcp.setObjlimit(0.1) gcp.optimize() status = gcp.getStatus() if status == "optimal": ...
flightcom/freqtrade
freqtrade/plugins/pairlist/VolatilityFilter.py
Python
gpl-3.0
4,749
0.002948
""" Volatility pairlist filter """ import logging import sys from copy import deepcopy from typing import Any, Dict, List, Optional import arrow import numpy as np from cachetools.ttl import TTLCache from pandas import DataFrame from freqtrade.exceptions import OperationalException from freqtrade.misc import plural f...
, 1440) self._pair_cache: TTLCache = TTLCache(maxsize=1000, ttl=self._refresh_period) if self._days < 1:
raise OperationalException("VolatilityFilter requires lookback_days to be >= 1") if self._days > exchange.ohlcv_candle_limit('1d'): raise OperationalException("VolatilityFilter requires lookback_days to not " "exceed exchange max request size " ...
NaturalGIS/QGIS
tests/src/python/test_qgssymbollayerutils.py
Python
gpl-2.0
7,685
0
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsSymbolLayerUtils. .. note:: 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. "...
e(string) self.assertEqual(s2, s) s = QSizeF(1.5, 2.5) string = QgsSymbolLayerUtils.encodeSize(s) s2 = QgsSymbolLayerUtils.decodeSize(string) self.assertEqual(s2, s) # bad string s2 = QgsSymbolLayerUtils.decodeSize('') self.assertEqual(s2, QSizeF(0, 0)) ...
f): s2, ok = QgsSymbolLayerUtils.toSize(None) self.assertFalse(ok) s2, ok = QgsSymbolLayerUtils.toSize(4) self.assertFalse(ok) s2, ok = QgsSymbolLayerUtils.toSize('4') self.assertFalse(ok) # arrays s2, ok = QgsSymbolLayerUtils.toSize([4]) self.a...
belokop-an/agenda-tools
code/MaKaC/webinterface/common/regFilters.py
Python
gpl-2.0
13,066
0.020435
from datetime import datetime import MaKaC.common.filters as filters from MaKaC.webinterface.common.countries import CountryHolder # -------------- FILTERING ------------------ class AccommFilterField( filters.FilterField ): """Contains the filtering criteria for the track of a contribution. Inher...
, EventFilterField.getId():EventFilterField} #------------- SORTING -------------------- class RegistrantSortin
gField(filters.SortingField): def getSpecialId(self): try: if self._specialId: pass except AttributeError, e: return self._id return self._specialId class NameSF(RegistrantSortingField): _id="Name" def compare( self, r1, r2 ): """ ...
BoxLib-Codes/wdmerger
analysis/vol-wd.py
Python
mit
2,763
0.0076
#!/usr/bin/env python import matplotlib matplotlib.use('agg') import sys import yt import numpy as np from yt.visualization.volume_rendering.api import \ Scene, \ VolumeSource # this is for the wdconvect problem def doit(plotfile): ds = yt.load(plotfile) ds.periodicity = (True, True, True) f...
"t = {:.3f} s".format(float(ds.current_time.d)), dict(horizontalalignment="left")], [(0.5,0.95), "Castro simulation of merging white dwarfs (0.6 $M_\odot$ + 0.9 $M_\odot$)", ...
huntxu/neutron
neutron/services/auto_allocate/db.py
Python
apache-2.0
17,330
0.000404
# Copyright 2015-2016 Hewlett Packard Enterprise Development Company, LP # # 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/li...
logy(context, tenant_id) if topology: subnets = self.core_plugin.get_subnets( context, filters={'network_id': [topology['network_id']]}) self._cleanup( context, network_id=topology['network_id'], router_id=topology['router_i...
ns its network UUID.""" try: subnets = self._provision_tenant_private_network( context, tenant_id) network_id = subnets[0]['network_id'] router = self._provision_external_connectivity( context, default_external_network, subnets, tenant_id) ...
jia-kai/pynojo
pynojo/mp/session.py
Python
gpl-3.0
7,080
0.004802
# -*- encoding: utf-8 -*- # $File: session.py # $Date: Sun Mar 04 19:27:38 2012 +0800 # # Copyright (C) 2012 the pynojo development team <see AUTHORS file> # # Contributors to this file: # PWX <[email protected]> # # This file is part of pynojo # # pynojo is free software: you can redistribute it and/or modify #...
equestTimeout = None # default request timeout def writeline(self, msg): ''' Send a line of message to the socket. Nothing will be returned, but if the re
mote socket has closed, Session._disconnected will be called. :param msg: Message body. :type msg: UTF-8 string. ''' if (self._sck is None): return False ret = False try: self._sck.sendall(msg + '\n') ret = True ...
PisiLinuxNew/kaptan
kaptan/libkaptan/ui_welcome.py
Python
gpl-3.0
2,425
0.0033
# Copyright 2016 Metehan Özbek <[email protected]> # 2020 Erdem Ersoy <[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 ...
# MA 02110-1301, USA. from PyQt5.QtWidgets import QW
izardPage, QLabel, QHBoxLayout, QVBoxLayout, QSpacerItem, QSizePolicy from PyQt5.QtGui import QPixmap from PyQt5.QtCore import Qt class WelcomeWidget(QWizardPage): def __init__(self, parent=None): super().__init__(parent) self.setSubTitle(self.tr("<h2>Welcome to Pisi Linux!</h2>")) vlayou...
mrtnrdl/.macdots
scripts/bin/platform-tools/systrace/catapult/devil/devil/android/logcat_monitor_test.py
Python
unlicense
8,737
0.004922
#!/usr/bin/env python # Copyright 2015 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. # pylint: disable=protected-access import itertools import threading import unittest from devil import devil_env from devil.android i...
Wrapper('0123456789abcdef') test_adb.Logcat = mock.Mock(return_value=(l for l in raw_logcat)) test_log = logcat_monitor.LogcatMonitor(test_adb, clear=False) return test_log class LogcatMonitorTest(unittest.TestCase): _TEST_THREADTIME_LOGCAT_DATA = [ '01-01 01:02:03.456 7890 0987 V LogcatMonitorTest: ...
ogcat monitor test message 1', '01-01 01:02:03.457 8901 1098 D LogcatMonitorTest: ' 'debug logcat monitor test message 2', '01-01 01:02:03.458 9012 2109 I LogcatMonitorTest: ' 'info logcat monitor test message 3', '01-01 01:02:03.459 0123 3210 W LogcatMonitorTest: ' ...
wenzheli/python_new
com/uva/learning/gibbs_sampler.py
Python
gpl-3.0
6,875
0.0112
from com.uva.learning.learner import Learner from sets import Set import math import random import numpy as np import copy from com.uva.sample_latent_vars import sample_z_ab_from_edge import cProfile, pstats, StringIO import time from com.uva.core_utils import gibbs_sampler from array import * class GibbsSampler(Learn...
start = time.time() while itr < self._max_iteration: """ pr = cProfile.Profile() pr.enable() """ print "iteration: " + str(itr) self._process() self._update() ppx = self._cal_perplexity_held_out() ...
len(self._avg_log) ppx = (1-1.0/(itr-300)) * self._avg_log[size-1] + 1.0/(itr-300) * ppx self._avg_log.append(ppx) else: self._avg_log.append(ppx) self._timing.append(time.time()-start) if itr % 50 == 0: ...
hakanardo/pyvx
setup.py
Python
mit
1,768
0.001131
from distutils.core import setup, Command from pyvx import __version__ import sys class PyTestCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import pytest errno = pytest.main() sys.exit(er...
description='OpenVX python support', long_description=''' PyVX is a set of python bindings for `OpenVX`_. `OpenVX`_ is a standard for expressing computer vision processing algorithms as a graph of function nodes. This graph is verified once and can then be processed (executed) multiple times. PyVX allows these gr...
ts the use of multiple `OpenVX`_ backends, both C and python backends. It also used to contain a code generating `OpenVX`_ backend written it python, but it will be moved to a package of it's own (curently it lives on the try1 branch of pyvx). Further details are provided in the `Documentation`_ .. _`OpenVX`: https:/...
justinbot/timecard
timecard/admin/views.py
Python
mit
885
0.00226
from datetime import datetime from flask import Blueprint, render_template from flask_cas import login_required from timecard.api import current_period_start from timecard.models import config, admin_required admin_views = Blueprint('admin', __name__, url_prefix='/admin', template_folder='templates') @admin_views....
f admin_users_page(): return render_template( 'admin_users.html', initial_date=datetime.now().isoformat(), # now, in server's time zone initial_period_start=current_period_start().isoformat(), period_duration=config['period_duration'], lock_date=config['lock_date'], ) ...
def admin_settings_page(): return render_template( 'admin_settings.html' )
google/clusterfuzz
src/clusterfuzz/_internal/tests/appengine/handlers/testcase_detail/remove_issue_test.py
Python
apache-2.0
2,010
0.001493
# 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, ...
'datastore') class HandlerTest(unittest.TestCase): """Test Handler.""" def setUp(self): test_helpers.patch(self, [ 'handlers.testcase_detail.show.get_testcase_detail', 'libs.auth.get_current_user', 'libs.auth.is_current_use
r_admin', ]) self.mock.is_current_user_admin.return_value = True self.mock.get_testcase_detail.return_value = {'testcase': 'yes'} self.mock.get_current_user().email = '[email protected]' flaskapp = flask.Flask('testflask') flaskapp.add_url_rule('/', view_func=remove_issue.Handler.as_view('/')) ...
kavdev/dj-stripe
djstripe/contrib/rest_framework/permissions.py
Python
mit
861
0.01626
""" .. module:: dj-stripe.contrib.rest_framework.permissions. :synopsis: dj-stripe - Permissions to be used with the dj-stripe REST API. .. moduleauthor:: @kavdev, @pydanny
""" from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission
): """A permission to be used when wanting to permit users with active subscriptions.""" def has_permission(self, request, view): """ Check if the subscriber has an active subscription. Returns false if: * a subscriber isn't passed through the request See ``utils.subscriber_has_active_subscription`` for...
vialectrum/vialectrum
electrum_ltc/gui/qt/locktimeedit.py
Python
mit
5,781
0.001557
# Copyright (C) 2020 The Electrum developers # Distributed under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php import time from datetime import datetime from typing import Optional, Any from PyQt5.QtCore import Qt, QDateTime from PyQt5.QtGui import...
ime): self.editor.set_locktime(prev_locktime) self.editor.setVisible(True) self.editor.set
Enabled(True) self.editor = option_index_to_editor_map[default_index] self.combo.currentIndexChanged.connect(on_current_index_changed) self.combo.setCurrentIndex(default_index) on_current_index_changed(default_index) hbox.addWidget(self.combo) for w in self.editors: ...
joharei/QtChordii
settings/settings.py
Python
gpl-3.0
2,286
0.000875
# coding: utf-8 # Copyright (C) 2013-2016 Johan Reitan # # This file is part of QtChordii. # # QtChordii 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 you
r option) any later version. # # QtChordii 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 Gen...
ICATION_NAME = 'QtChordii' group_main_window = 'MainWindow' key_size = 'size' key_pos = 'pos' key_is_full_screen = 'is_full_screen' key_splitter_sizes = 'splitter_sizes' group_project_settings = 'ProjectSettings' key_project_file = 'project_file' def set_up_settings(): QCoreApplication.setOrganizationName(APPLIC...
TuSimple/simpledet
config/resnet_v1b/tridentnet_r152v1bc4_c5_2x.py
Python
apache-2.0
9,529
0.003883
from models.tridentnet.builder import TridentFasterRcnn as Detector from models.tridentnet.builder_v2 import TridentResNetV1bC4 as Backbone from models.tridentnet.builder import TridentRpnHead as RpnHead from models.tridentnet.builder import process_branch_outputs, process_branch_rpn_outputs from symbol.builder import ...
else: process_output = lambda x, y: x process_rpn_output = lambda x, y: process_branch_rpn_outputs(x, Trident.num_branch) class model: prefix = "experiments/{}/checkpoint".format(General.name) epoch = OptimizeParam.schedule.end_epoch class nms: ...
nnotations/instances_minival2014.json" # data processing class NormParam: mean = tuple(i * 255 for i in (0.485, 0.456, 0.406)) # RGB order std = tuple(i * 255 for i in (0.229, 0.224, 0.225)) class ResizeParam: short = 800 long = 1200 if is_train else 2000 class PadPar...
takinbo/rapidsms-borno
apps/bednets/tests.py
Python
lgpl-3.0
18,579
0.007159
from rapidsms.tests.scripted import TestScript from apps.form.models import * from apps.reporters.models import * import apps.reporters.app as reporter_app import apps.supply.app as supply_app import apps.form.app as form_app import apps.default.app as default_app from app import App from django.core.management.command...
at KANO State. # this one should be a duplicate test_reg_dup > llin register 20 dl duplicate user test_reg_dup < Hello again duplicate! You are already registered as a Distribution point
team leader at KANO State. # but all of these should create a new registration test_reg_dup > llin register 20 dl duplicate user withanothername test_reg_dup < Hello duplicate! You are now registered as Distribution point team leader at KANO State. test_reg_dup > llin registe...
citrix-openstack-build/tempest
tempest/api/compute/admin/test_flavors_access.py
Python
apache-2.0
5,575
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 NEC Corporation. # 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 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 lan...
st.api import compute from tempest.api.compute import base from tempest.common.utils.data_utils import rand_int_id from tempest.common.utils.data_utils import rand_name from tempest import exceptions from tempest.test import attr class FlavorsAccessTestJSON(base.BaseComputeAdminTest): """ Tests Flavor Access...
redhat-openstack/ironic
ironic/tests/drivers/test_ipmitool.py
Python
apache-2.0
85,048
0
# 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 ...
mock_support): mock_support.return_value = True ipmi.TMP_DIR_CHECKED = True ipmi.VendorPassthru() mock_support.assert_called_with(mock.ANY) self.assertEqu
al(0, mock_check_dir.call_count) @mock.patch.object(ipmi, '_is_option_supported', autospec=True) @mock.patch.object(utils, 'check_dir', autospec=True) def test_console_init_calls(self, mock_check_dir, mock_support): mock_support.return_value = True ipmi.TMP_DIR_CHECKED = None ipmi.I...
mikalstill/nova
nova/tests/unit/api/openstack/compute/test_server_metadata.py
Python
apache-2.0
31,012
0.000161
# Copyright 2011 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
as server_metadata_v21 from nova.compute import vm_states import nova.db.api from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes CONF = cfg.CONF def return_create_instance_metadata_max(context, server_id, metadata, delete): return stub_max_server_metadata() def re...
inst.metadata = stub_server_metadata() inst.obj_reset_changes() def return_server_metadata(context, server_id): if not isinstance(server_id, six.string_types) or not len(server_id) == 36: msg = 'id %s must be a uuid in return server metadata' % server_id raise Exception(msg) return stub...
beallej/event-detection
WebApp/EventDetectionWeb.py
Python
mit
2,619
0.006491
import sys; import os sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.pa
th.abspath('.')) from flask import Flask, render_template, request, redirect import subprocess from Utils import subprocess_helpers from Ut
ils.DataSource import * app = Flask(__name__) dataSource = DataSource() def launch_preprocessors(): process = subprocess.Popen( subprocess_helpers.python_path + " Daemons/QueryProcessorDaemon.py && " + subprocess_helpers.python_path + " Daemons/ArticleProcessorDaemon.py", executable=subprocess_he...
KiChjang/servo
tests/wpt/web-platform-tests/tools/wptserve/wptserve/config.py
Python
mpl-2.0
11,668
0.0012
import copy import logging import os from collections import defaultdict from collections.abc import Mapping from . import sslutils from .utils import get_port _renamed_props = { "host": "browser_host", "bind_hostname": "bind_address", "external_host": "server_host", "host_ip": "server_host", } def...
mains", ""), ("domains_set",), ("all_domains_set",) ]: target = result for part in key[:-1]: target = target[part] value = target[key[-1]] if isinstance(value, dict): target[key[-1]] = {k:v for (k,v) i
n value.items() if not k.startswith("op")} else: target[key[-1]] = [x for x in value if not x.startswith("op")] return result def json_types(obj): if isinstance(obj, dict): return {key: json_types(value) for key, value in obj.items()} if (isinstance(obj, str) or ...
Haynie-Research-and-Development/jarvis
deps/lib/python3.4/site-packages/pywink/devices/robot.py
Python
gpl-2.0
782
0
from pywink.devices.base import WinkDevice class WinkRobot(WinkDevice): """ Represents a Wink robot. """ def __init__(self, device_state_as_json, api_interface):
super(WinkRobot, self).__init__(device_state_as_json, api_interface) self._available = True self._capability = "fired" self._unit = None def state(self): return self._last_reading.get(self.capability(), False) def available(self): """ Robots are virtual ther...
re they don't have a connection status always return True. """ return self._available def unit(self): # Robots are a boolean sensor, they have no unit. return self._unit def capability(self): return self._capability
Perkville/django-tastypie
tests/profilingtests/urls.py
Python
bsd-3-clause
252
0
from django.conf.urls import include, url from tastypie.api import Api from .resources import NoteResourc
e, UserResource api = Api() api.register(NoteResource()) api.register(UserResource())
urlpatterns = [ url(r'^api/', include(api.urls)), ]
suqinhuang/tp-qemu
qemu/tests/cpu_device_hotplug.py
Python
gpl-2.0
4,072
0.000246
import logging import re import time from autotest.client.shared import error from virttest import utils_misc @error.context_aware def run(test, params, env): """ Runs vCPU hotplug tests based on CPU device: """ def hotplug(vm, current_cpus, total_cpus, vcpu_threads): for cpu in range(curre...
step=5.0, text="retry later"): raise error
.TestFail("CPU quantity mismatch cmd after hotplug !") error.context("rebooting the vm and check CPU quantity !", logging.info) session = vm.reboot() if not utils_misc.check_if_vm_vcpu_match(total_cpus, vm): raise error.TestFail("CPU quantity mismatch cmd after ...
Juanlu001/CBC.Solve
cbc/common/utils.py
Python
gpl-3.0
1,493
0.008707
"This module provides a set of common utility functions." __author__ = "Anders Logg" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from math import ceil from numpy import linspace from dolfin import PeriodicBC, warning def ...
"Check if boundary conditions are periodic" return all(isinstance(bc, PeriodicBC) for bc in bcs) def missing_function(function): "Write an informative error message when function has not been overloaded" error("The function %s() has not been specified. Please provide a specification of this function.") de...
step. Note that the time step may be adjusted so that it matches the given end time.""" # Compute range ds = dt n = ceil(T / dt) t_range = linspace(0, T, n + 1)[1:] dt = t_range[0] # Warn about changing time step if ds != dt: warning("Changing time step from %g to %g" ...
ShaperTools/openhtf
openhtf/core/test_descriptor.py
Python
apache-2.0
18,718
0.006037
# Copyright 2014 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 agre...
ss UnrecognizedTestUidError(Exception): """Raised when information is requested about an unknown Test UID.""" class InvalidTestPhaseError(Exception): """Raised when an invalid method is decorated.""" class InvalidTestStateError(Exception): """Raised when an operation is attempted in an invalid state.""" def...
h this as a parent: >>> parser = argparse.ArgumentParser( 'My args title', parents=[openhtf.create_arg_parser()]) >>> parser.parse_args() Args: add_help: boolean option passed through to arg parser. Returns: an `argparse.ArgumentParser` """ parser = argparse.ArgumentParser( 'Open...
amolborcar/learnpythonthehardway
ex28.py
Python
mit
231
0.004329
''' 1. True y 2. False y 3. False y 4. True y 5
. True y 6. False n 7. False y 8. True y 9. False y 10.
False y 11. True y 12. False y 13. True y 14. False y 15. False y 16. True n 17. True y 18. True y 19. False y 20. False y '''
team23/django_backend
django_backend/templatetags/django_backend_query_tags.py
Python
bsd-3-clause
4,480
0.001116
from django import template from django.utils.datastructures import MultiValueDict from django.utils.html import conditional_escape as escape from django.utils.encoding import smart_unicode, smart_str from django.template.base import token_kwargs import urllib register = template.Library() class QueryStringNode(temp...
:] variables = MultiValueDict() extends = None varname = None variable
s_finished = False try: i = 0 num_values = len(values) while i < num_values: if values[i] == 'extends': variables_finished = True extends = parser.compile_filter(values[i + 1]) i += 2 continue if values[i...
CDSherrill/psi4
tests/pytests/test_mp2.py
Python
lgpl-3.0
21,931
0.010214
import pytest from .utils import * import psi4 pytestmark = [pytest.mark.quick, pytest.mark.mp2] _ref_h2o_ccpvdz = { 'df': { 'HF TOTAL ENERGY': -76.0167614256151865, 'MP2 SAME-SPIN CORRELATION ENERGY': -0.0527406422061238, 'MP2 OPPOSITE-SPIN CORRELATION ENERGY'...
assert compare_values(ref_bl
ock[pv], obj.variable(pv), 5, pv) if any((x in inp['options'] for x in ['os_scale', 'ss_scale', 'mp2_os_scale', 'mp2_ss_scale'])): assert compare_values(ref_custom_corl, obj.variable('CUSTOM SCS-MP2 CORRELATION ENERGY'), 5, 'custom scsmp2 corl') assert...
faylau/oVirt3.3WebAPITest
src/TestData/DataCenter/ITC01010401_UpdateUninitializedDC.py
Python
apache-2.0
1,565
0.004496
#encoding:utf-8 __authors__ = ['"Liu Fei" <[email protected]>'] __version__ = "V0.1" ''' # ChangeLog: #---------------------------------------------------------------------
------------ # Version Date Desc
Author #--------------------------------------------------------------------------------- # V0.1 2014/10/24 初始版本 Liu Fei #--------------------------------------------------------------------------------- ''' '''------------...
OpenGenus/cosmos
scripts/global-metadata.py
Python
gpl-3.0
1,198
0
import json import pathlib import collections avoid_extensions = [ "", # ".md", # ".png", # ".csv", # ".class", # ".data", # ".in", # ".jpeg", # ".jpg", # ".out", # ".textclipping", # ".properties", # ".txt", # ".sbt", ] avoid_dirs = ["project", "test", "img",
"image", "images"] global_metadata = collections.defaultdict(dict) original_paths = collections.defaultdict(str) for path in pathlib.Path(__file__).parents[1].glob( "scripts/metadata/code/**/**/*"): if (path.suffix and not any(elem in list(path.parts)
for elem in avoid_dirs) and path.suffix.lower() not in avoid_extensions): original_paths[path.parts[-2]] = "/".join(path.parts[:-2]) for algo in original_paths: filename = pathlib.Path("{}/{}/data.json".format(original_paths[algo], algo)) ...
x007007007/pyScreenBrightness
src/pyScreenBrightness/base.py
Python
mit
1,127
0.002662
# -*- coding:utf-8 -*- import abc import platform from UserList import UserList class Monitor(object): @abc.abstractmethod def current(self): pass @abc.abstractmethod def percent(self, range): pass @abc.abstractmethod def reset(self): pass @abc.abstractmethod ...
in(self): pass class Monitors(UserList): @abc.abstractmethod def percent(self, range): pass @abc.abstractmethod def reset(self): pass @abc.abstractmethod def max(self): pass @abc.abstractmethod def min(self): pass def get_monitors(): ...
tors() elif platform.system() == "Darwin": from .driver_mac import MacMonitors return MacMonitors() elif platform.system() == "Linux": from .driver_linux import LinuxMonitors return LinuxMonitors() else: raise OSError()
roadhead/satchmo
satchmo/payment/modules/protx/views.py
Python
bsd-3-clause
3,443
0.009875
"""Protx checkout custom views""" from django.utils.translation import ugettext as _ from satchmo.configuration
import config_get_group from satchmo.payment.views import payship, confirm import logging log = logging.getLogger('protx.
views') def pay_ship_info(request): return payship.credit_pay_ship_info(request, config_get_group('PAYMENT_PROTX'), template="checkout/protx/pay_ship.html") def confirm_info(request, template='checkout/protx/confirm.html', extra_context={}): payment_module = config_get_group('PAYMENT_PROTX') contr...
our-city-app/oca-backend
src/rogerthat/bizz/jobs/__init__.py
Python
apache-2.0
17,649
0.00289
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
bUserProfile from rogerthat.models.jobs import JobOffer, JobMatchingCriteria, JobMatchingCriteriaNotifications, JobMatch, \ JobMatchStatus, JobNotificationSchedule, JobOfferSourceType from rogerthat.rpc import users from rogerthat.rpc.models import RpcCAPI
Call, RpcException from rogerthat.rpc.rpc import mapping, logError, CAPI_KEYWORD_ARG_PRIORITY, \ PRIORITY_HIGH from rogerthat.service.api.messaging import add_chat_members from rogerthat.to.jobs import GetJobsResponseTO, JobOfferTO, NewJobsResponseTO, \ NewJobsRequestTO, SaveJobsCriteriaResponseTO, GetJobsCrite...
anupkdas-nus/global_synapses
pyNN-dispackgaes/nest/standardmodels/synapses.py
Python
gpl-3.0
7,616
0.003283
""" Synapse Dynamics classes for nest :copyright: Copyright 2006-2016 by the PyNN team, see AUTHORS. :license: CeCILL, see LICENSE for details. """ import nest from pyNN.standardmodels import synapses, build_translations from pyNN.nest.synapses import NESTSynapseMixin import logging from ..conversion import make_sl...
med to be dendr
itic.") # could perhaps support axonal delays using parrot neurons? super(STDPMechanism, self).__init__(timing_dependence, weight_dependence, voltage_dependence, dendritic_delay_fraction, weight, delay) def _get...
pinballwizard/phone
manage.py
Python
lgpl-3.0
248
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "phone.settings")
from django.core.management import execute_from_command_l
ine execute_from_command_line(sys.argv)
missionpinball/mpf_mc
mpfmc/tests/test_Assets.py
Python
mit
13,153
0.000228
import time from mpfmc.tests.MpfMcTestCase import MpfMcTestCase class TestAssets(MpfMcTestCase): def get_machine_path(self): return 'tests/machine_files/assets_and_image' def get_config_file(self): return 'test_asset_loading.yaml' def test_machine_wide_asset_loading(self): # te...
_name'].unloading
) self.assertTrue(self.mc.images['image_13_new_name'].loaded) self.assertFalse(self.mc.images['image_13_new_name'].loading) self.assertFalse(self.mc.images['image_13_new_name'].unloading) # Make sure the ones that should not have loaded on startup didn't load self.assertFalse(s...
MonicaHsu/truvaluation
venv/lib/python2.7/uuid.py
Python
mit
21,828
0.00197
r"""UUID objects (universally unique identifiers) according to RFC 4122. This module provides immutable UUID objects (class UUID) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. If all you want is a unique ID, you should probably call uuid1() ...
raise ValueError('badly formed hexadecimal
UUID string') int = long(hex, 16) if bytes_le is not None: if len(bytes_le) != 16: raise ValueError('bytes_le is not a 16-char string') bytes = (bytes_le[3] + bytes_le[2] + bytes_le[1] + bytes_le[0] + bytes_le[5] + bytes_le[4] + bytes_le[...
XKNX/xknx
xknx/devices/cover.py
Python
mit
13,841
0.000506
""" Module for managing a cover via KNX. It provides functionality for * moving cover up/down or to a specific position * reading the current state from KNX bus. * Cover will also predict the current position. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Iterator from...
name, device_updated_cb) # self.after_update for position changes is called after updating the # travelcalculator (in process_group_write and set_*) - angle changes # are updated from RemoteValue objects self.updown = RemoteValueUpDown( xknx, group_address_long, ...
ep = RemoteValueStep( xknx, group_address_short, device_name=self.name, after_update_cb=self.after_update, invert=invert_position, ) self.stop_ = RemoteValueSwitch( xknx, group_address=group_address_stop, sy...
JulyJ/MindBot
mindbot/command/news/canadanews.py
Python
mit
1,352
0.002219
""" This module serves commands to retrieve Canadian News. Powered by http://www.statcan.gc.ca/, shows 4 actual news. Updated daily. """ from requests import get, RequestException, status_codes from ..commandbase import CommandBase
class CanadaStatsCommand(CommandBase): name = '/canadastat' help_text = ' - Daily Articles with Open Canada Statistics reviews.' disable_web_page_preview = 'false' NEWS_TEXT = ('[{response[title]}](http://www.statcan.gc.ca{response[photo]})\n'
'{response[summary]}\n' '{response[date]}, [Read More...](http://www.statcan.gc.ca{response[link]})') def __call__(self, *args, **kwargs): super().__call__(*args, **kwargs) json = self.get_json() if json: for article in json['daily']['article']: ...
SmithChart/twitter-printer
dbConnector.py
Python
gpl-2.0
6,036
0.012922
#!/usr/bin/env python3 import os import sqlite3 import time import random import hashlib import unittest import weakref import os import uuid class WrongDbFileError(Exception): def __init__(self, message): self.message = message class InvalidPubMethodError(Exception): def __init__(self, message): ...
ethod"%pubMethod) c.execute("INSERT INTO wurst(code, valid, used, dateGenerated, pubMethod) VALUES (?,?,?,?,?)",[str(code),volume,0,dateCreate,str(pubMethod)])
self.conn.commit() return code def useCode(self,code): dateUse = int(time.time()) c = self.conn.cursor() c.execute("SELECT wurst.valid,used FROM wurst INNER JOIN pubMethod ON pubMethod.pubMethod = wurst.pubMethod WHERE code == ? and used < wurst.valid and pubMethod.valid != 0",[s...