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 |
|---|---|---|---|---|---|---|---|---|
ivanamihalek/blender | old/bgjob.py | Python | gpl-2.0 | 3,413 | 0.033402 | # This script is an example of how you can run blender from the command line (in background mode with no interface)
# to automate tasks, in this example it creates a text object, camera and light, then renders and/or saves it.
# This example also shows how you can parse command line options to python scripts.
#
# Examp... | lse
if ok:
Blender.Save(save_path, 1)
if rend | er_path:
render= sce.render
render.extensions= True
render.renderPath = render_path
#[Ivana:] don't know how to change the format
#render.setImageType(PNG)
render.sFrame= 1
render.eFrame= 1
render.renderAnim()
import sys # to get command line args
import optparse # to parse options for us and print a ... |
Zentyal/openchange | mapiproxy/services/web/rpcproxy/rpcproxy/channels.py | Python | gpl-3.0 | 23,946 | 0.000752 | # channels.py -- OpenChange RPC-over-HTTP implementation
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2015 Julien Kerihuel <j.kerihuel@openchange.org>
# Wolfgang Sourdeau <wsourdeau@inverse.ca>
# Enrique J. Hernández <ejhernandez@zentyal.com>
#
# This program is free... | connected = True
except socket_error:
self.logger.debug("handling socket.error: %s"
% str(sys.exc_info()))
self.logger.warn("reattempting to connect to OUT"
" channel... (%d/10)" % attempt)
sle... | # identify ourselves as the IN proxy
unix_socket.sendall(INBOUND_PROXY_ID)
# send window_size to 256Kib (max size allowed)
# and conn_timeout (in milliseconds, max size allowed)
unix_socket.sendall(pack("<ll", self.window_size, INBOUND_PROXY_CONN_TIMEOUT))
... |
ZaoLahma/PyCHIP-8 | rom.py | Python | mit | 308 | 0.003247 | #!/usr/bin/env python3
import struct
class Rom(object):
def __init__(s | elf):
self.romData = []
def load(self, path):
file = open(path, 'rb')
while True:
| byte = file.read(1)
if not byte:
break
self.romData.append(ord(byte))
|
sprucedev/DockCI | manage.py | Python | isc | 157 | 0 | #!/usr/bin/env python
import dockci.commands
f | rom dockci.server import APP, app_init, MANAGER
if __name__ == "__main__":
app_init()
MANAG | ER.run()
|
SandyChapman/ramlizer | ramlizer/RamlResponse.py | Python | mit | 907 | 0 | from .decorators import raml_optional, raml_simple_parse, raml_tabbed
from .RamlBody import RamlBody
from .RamlParseable import RamlParseable
class RamlResponse(RamlParseable):
def __init__(self, code, yaml):
s | elf.code = code
super(RamlResponse, self).__init__(yaml)
@raml_optional
@raml_simple_parse
def parse_description(self):
pass
@raml_optional
@raml_simple_parse
def parse_headers(self):
| pass
@raml_optional
def parse_body(self):
self.body = {
body_encoding[0]: RamlBody(body_encoding[0], body_encoding[1])
for body_encoding in self.yaml['body'].items()
}
@raml_tabbed
def __str__(self):
return '''\
[RamlResponse({0.code}):
descriptio... |
DanceCats/CoreCat | corecat/models/project.py | Python | mit | 1,533 | 0 | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic i... | _by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_b... | kwargs.get('project_description', None)
|
awlange/brainsparks | src/calrissian/layers/particle2_dipole.py | Python | mit | 4,517 | 0.000221 | from .layer import Layer
from ..activation import Activation
import numpy as np
class Particle2Dipole(object):
"""
Dipole approximated as 2 coupled charges of equal magnitude, uncoupled
"""
def __init__(self, input_size=0, output_size=0, activation="sigmoid", k_bond=1.0, k_eq=0.1, s=1.0, cut=10.0,
... | rans)
return z.transpose()
def compute_a(self, z):
return self.activation(z)
def compute_da(self, z):
return self.d_activation(z)
def compute_w(self):
w = np.zeros((self.input_size, self.output_size))
for j in range(self.output_size):
dx = self.rx_pos_i... | pos_out[j]
dy = self.ry_pos_inp - self.ry_pos_out[j]
dz = self.rz_pos_inp - self.rz_pos_out[j]
potential = np.exp(-(dx**2 + dy**2 + dz**2))
dx = self.rx_pos_inp - self.rx_neg_out[j]
dy = self.ry_pos_inp - self.ry_neg_out[j]
dz = self.rz_pos_inp - ... |
addition-it-solutions/project-all | addons/document/content_index.py | Python | agpl-3.0 | 6,555 | 0.005034 | # -*- 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... | type.', exc_info=True)
| try:
if fobj:
res = (mime, fobj.indexContent(content,filename,fname or realfname) )
else:
_logger.debug("Have no object, return (%s, None).", mime)
res = (mime, '')
except Exception:
_logger.info("Cannot index file %s (%... |
hlange/LogSoCR | pysc/usi/log/socr_streamhandler/handler.py | Python | agpl-3.0 | 770 | 0.011688 | import logging
import json
import usi
import usi.systemc
class SoCR_StreamHandler(logging.StreamHandler): # Inherit from StreamHandler
def __init__(s | elf, stream=None):
logging.StreamHandler.__init__(self)
def emit(self, record):
if "message_type" in record.__dict__:
record.filename = record.__dict__["message_type"]
if "delta_count" not in record.__dict__:
record.__dict__["delta_count"] = usi.systemc.delta_... |
if "parameters" not in record.__dict__:
record.__dict__["parameters"] = ""
if "time" not in record.__dict__:
record.__dict__["time"] = usi.systemc.simulation_time(usi.systemc.NS)
logging.StreamHandler.emit(self, record)
|
jasco/authomatic | authomatic/providers/oauth1.py | Python | mit | 38,859 | 0 | # -*- coding: utf-8 -*-
"""
|oauth1| Providers
--------------------
Providers which implement the |oauth1|_ protocol.
.. autosummary::
OAuth1
Bitbucket
Flickr
Meetup
Plurk
Twitter
Tumblr
UbuntuOne
Vimeo
Xero
Xing
Yahoo
"""
import abc
import binascii
import datetime
i... | n_secret = parse.quote(token_secret, '')
return parse.quote('&'.join((consumer_secret, token_secret)), '')
class OAuth1(providers.AuthorizationProvider):
"""
Base class for |oauth1|_ providers.
"""
_signature_generator = HMACSHA1SignatureGenerator
PROVIDER_TYPE_ID = 1
REQUEST_TOKEN_... | *args, **kwargs):
"""
Accepts additional keyword arguments:
:param str consumer_key:
The *key* assigned to our application (**consumer**) by
the **provider**.
:param str consumer_secret:
The *secret* assigned to our application (**consumer**) by
... |
Mappy/PyLR | pylr/values.py | Python | apache-2.0 | 3,453 | 0.003475 | # -*- coding: utf-8 -*-
''' Define functions for transforming encoded values
.. moduleauthor:: David Marteau <david.marteau@mappy.com>
'''
from .utils import signum
from .constants import (BIT24FACTOR_REVERSED,
DECA_MICRO_DEG_FACTOR,
BEARING_SECTOR,
... | inates of a reference position.
:param Coords prev: Absolute coordinates of the reference geo point
:param int blon: relative longitude expressed in decamicr | odegrees
:param int blat: relative latitude expressed in decamicrodegrees
:return: Pair of coordinates (in degrees)
:rtype: float
"""
lon = (prev.lon + blon / DECA_MICRO_DEG_FACTOR)
lat = (prev.lat + blat / DECA_MICRO_DEG_FACTOR)
return lon, lat
def bearing_estimate(interval):
... |
PXke/invenio | invenio/modules/search/testsuite/test_search_external_collections_getter.py | Python | gpl-2.0 | 2,766 | 0.007954 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2010, 2011, 2013 CERN.
##
## Invenio 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
## ... | egetter.status is not None
if 'content' in check and is_ok:
is_ok = pagegetter.data.find(check['content']) > 0
check['result'] = is_ok == ('content' in check)
pagegetters = [HTTPAsyncPageGetter(check['url']) for check in checks]
finished_list = async_download(p... | for (finished, check) in zip(finished_list, checks):
if not finished:
check['result'] = 'content' not in check
errors = [check for check in checks if not check['result']]
self.assertEqual(errors, [])
TEST_SUITE = make_test_suite(AsyncDownloadTest,)
if __name__ == "__ma... |
hareevs/pgbarman | tests/test_infofile.py | Python | gpl-3.0 | 19,981 | 0 | # Copyright (C) 2013-2016 2ndQuadrant Italia Srl
#
# This file is part of Barman.
#
# Barman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | ssert dummy.dummy == 14
with pytest.raises(Att | ributeError):
del dummy.dummy
def test_subclass_load(self, tmpdir):
tmp_file = tmpdir.join("test_file")
tmp_file.write('dummy=15\n')
dummy = DummyFieldListFile()
dummy.load(tmp_file.strpath)
assert dummy.dummy == 15
def test_subclass_save(self, tmpdir):
... |
maweigert/biobeam | biobeam/simlsm/sim_dslm.py | Python | bsd-3-clause | 3,286 | 0.025867 | """
mweigert@mpi-cbg.de
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from biobeam.simlsm.simlsm import SimLSM_Base
from six.moves import range
class SimLSM_DSLM(SimLSM_Base):
def _prepare_u0_illum(self, zfoc):
self.u0_illum = self._bpm_illum.u0_be... | sert abs(offset)<= self.u0_illum.shape[0]//2
print("offset", offset)
u0_base = np.roll(self.u0_illum, offset ,axis=0)
#prepare the parallel scheme
max_NA = self.NA_illum if np.isscalar(self.NA_illum) else max(self.NA_illum)
if dx_parallel is None:
dx_parallel = ... | lel)
# the beamlet centers in the simul_xy coordinates
ind_step = int(np.ceil(1.*dx_parallel/bpm.dx))
#make sure its divisible by the grid size dimension
ind_step = [i for i in range(ind_step, bpm.simul_xy[0]+1) if bpm.simul_xy[0]%i==0][0]
if ind_step<=0:
raise Valu... |
yannrouillard/weboob | modules/regionsjob/__init__.py | Python | agpl-3.0 | 805 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af | fero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in th | e 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, s... |
Venturi/cms | env/lib/python2.7/site-packages/aldryn_people/south_migrations/0021_auto_person_groups.py | Python | gpl-2.0 | 15,722 | 0.007696 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding SortedM2M table for field groups on 'Person'
db.create_table(u'... | 'dj | ango.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'aldryn_people.persontranslation': {
'Meta': {'unique_together': "[(u'language_code', u'master')]", 'object_name': 'PersonTranslation', 'db_table': "u'aldryn_people_person_translation'"},
... |
ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/209_Minimum_Size_Subarray_Sum.py | Python | mit | 564 | 0 | class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums | : List[int]
:rtype: int
"""
MAX_INT = 2 ** 31 - 1
if not nums or len(nums) == 0:
return 0
i = j = n_sum = 0
min_len = MAX_INT
while j < len(nums):
n_sum += nums[j]
j += 1
| while n_sum >= s:
min_len = min(min_len, j - i)
n_sum -= nums[i]
i += 1
return min_len if min_len != MAX_INT else 0
|
lukas-hetzenecker/home-assistant | homeassistant/components/google_assistant/logbook.py | Python | apache-2.0 | 992 | 0.002016 | """De | scribe logbook events."""
from homeassistant.core import callback
from .const import DOMAIN, EVENT_COMMAND_RECEIVED, SOURCE_CLOUD
COMMON_COMMAND_PREFIX = "action.devices.commands."
@callback
def async_describe_events(hass, async_describe_event):
"""Describe logbook events."""
@callback
def async_descri... | "command"]
if command.startswith(COMMON_COMMAND_PREFIX):
command = command[len(COMMON_COMMAND_PREFIX) :]
commands.append(command)
message = f"sent command {', '.join(commands)}"
if event.data["source"] != SOURCE_CLOUD:
message += f" (via {event.data['... |
persandstrom/home-assistant | homeassistant/components/device_tracker/locative.py | Python | apache-2.0 | 4,098 | 0 | """
Support for the Locative platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.locative/
"""
import asyncio
from functools import partial
import logging
from homeassistant.const import (
ATTR_LATITUDE, ATTR_LONGITUDE, STATE_NOT... | nused-import
from homeassistant.components.device_tracker import ( # NOQA
DOMAIN, PLATFORM_SCHEMA)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['http']
URL = '/api/locative'
def setup_scanner(hass, config, see, discovery_info=None):
"""Set up an endpoint for the Locative application."""
hass.h... | ee))
return True
class LocativeView(HomeAssistantView):
"""View to handle Locative requests."""
url = URL
name = 'api:locative'
def __init__(self, see):
"""Initialize Locative URL endpoints."""
self.see = see
@asyncio.coroutine
def get(self, request):
"""Locativ... |
nanshihui/PocCollect | middileware/resin/__init__.py | Python | mit | 123 | 0.073171 | KEYWORDS = ['resin', ]
def r | ules(head='',context='',ip='',port='',productname={},keywords=' | ',hackinfo=''):
return False |
lwz7512/logtoeye | dashboard/reportor.py | Python | apache-2.0 | 9,877 | 0.000405 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# format keyshort in sublime text2: ctrl+shift+alt+t
# powered by SublimePythonTidy
__author__ = 'lwz'
from WebElements.Display import Label
from WebElements.Layout import Horizontal
from WebElements.DOM import Div, Img
from uiwiget import CompleteDom, RoundCornerPanel, Cus... | yleFromString('margin-top: 20px;')
page.addChildElement(alert_panel_row)
alert_volume = RoundCornerPanel('Alert Volume Last Day', 220, 120)
volume_label = Label()
volume_label.setProperty('text', '1000') # ???
volume_label.addClass('green-big-label')
alert_volume.addChildElement(volume_label)
... | atistic = RoundCornerPanel(' Alert-1 | Crit-2 | Error-3 | Warn-4 ', 280, 120)
alert_panel_row.addChildElement(alert_statistic)
label_row = Horizontal()
label_row.setStyleFromString('padding-top:16px;padding-left:24px')
alert_statistic.addChildElement(label_row)
alert_label = Label()
alert_label... |
rigetticomputing/pyquil | pyquil/latex/latex_generation.py | Python | apache-2.0 | 1,266 | 0.00158 | ##############################################################################
# Copyright 2016-2019 Rigetti Computing
#
# 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... | #######################################################
import warnings
from typing import Optional
from pyquil.latex._diagram import DiagramSettings
from pyquil.quil import Program
def to_latex(circuit: Program, settings: Optional[DiagramSettings] = None) -> str:
from pyquil.latex._main import to_latex
wa... | .latex_generation.to_latex" has been moved -- please import it'
'as "from pyquil.latex import to_latex going forward"',
FutureWarning,
)
return to_latex(circuit, settings)
|
FrodeSolheim/fs-uae-launcher | fsgamesys/files/installablefiles.py | Python | gpl-2.0 | 36 | 0 | from .types imp | ort Instal | lableFiles
|
dmpetrov/dataversioncontrol | tests/unit/test_prompt.py | Python | apache-2.0 | 339 | 0 | from dvc.prompt import confirm
def test_confirm_in_tty_if_stdin_is_closed(mocker):
mock_input = mocker.patch("dvc.prompt.input", side_effect=EOFError)
mock_isatty = mocker.patch("sys.stdout. | isatty", return_value=True)
ret = confirm( | "message")
mock_isatty.assert_called()
mock_input.assert_called()
assert not ret
|
betrisey/home-assistant | homeassistant/components/climate/ecobee.py | Python | mit | 9,405 | 0 | """
Platform for Ecobee Thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.ecobee/
"""
import logging
from os import path
import voluptuous as vol
from homeassistant.components import ecobee
from homeassistant.components.climate import... | def operation_mode(self):
"""Return current operation ie. heat, cool, idle."""
return self.thermostat['settings']['hvacMode']
@property
def mode(self):
"""Return current mode ie. home, away, sleep."""
retur | n self.thermostat['program']['currentClimateRef']
@property
def fan_min_on_time(self):
"""Return current fan minimum on time."""
return self.thermostat['settings']['fanMinOnTime']
@property
def device_state_attributes(self):
"""Return device specific state attributes."""
... |
ktan2020/legacy-automation | win/Lib/site-packages/sst/__init__.py | Python | mit | 1,057 | 0.000946 | #!/usr/bin/env python
#
# Copyright (c) 2011 Canonical Ltd.
#
# This file is part of: SST (selenium-simple-test)
# https://launchpad.net/selenium-simple-test
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... | e
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__all__ = ['runtests']
__version | __ = '0.2.2'
try:
from .runtests import runtests
except ImportError as e:
# Selenium not installed
# this means we can import the __version__
# for setup.py when we install, without
# *having* to install selenium first
def runtests(*args, **kwargs):
raise e
|
brianhawthorne/maml | maml/test/test_parser.py | Python | gpl-3.0 | 2,468 | 0.002431 | """
This file is part of Maml.
Maml is free software: you can re | distribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Maml is distributed in the | hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Maml. If not, see <htt... |
sotondriver/Lego_classification | src/boxCap.py | Python | mit | 6,567 | 0.014314 | """ Capturing and analyzing the box information
Author: Lyu Yaopengfei
Date: 23-May-2016
"""
import cv2
import threading
import time
from PIL import Image
import Lego.dsOperation as dso
import Lego.imgPreprocessing as imgprep
from Lego.ocr import tesserOcr
capImg = None
resImg = None
stopFlat = 0
lock = ... | esImg,clickCnt)
if(dtrtnFlag is False):
# if detect result is False, set clickFlag 0, re-capturing
clickFlag = 0
exportLog(logFile, 'Detecting fault, re-capturing')
elif(dtrtnFlag is True):
cv2.imshow('filted',filted... | rtLog(logFile, bx1.boxname+'_'+dso.SUF_DEF[clickCnt]+' OCR: '+str(numStr))
dtrtnFlag = None
else:
cv2.putText(showImg,'Do you save this result? Lclick Save, Rclick Discard',(10,250), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,255,255),1)
elif(clickFlag is 2):
export... |
holmes-app/holmes-api | holmes/validators/meta_tags.py | Python | mit | 2,813 | 0.000355 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from holmes.validators.base import Validator
from holmes.utils import _
class MetaTagsValidator(Validator):
@classmethod
def get_violation_definitions(cls):
return {
'absent.metatags': {
'title': _('Meta tags not present'),
... | han %(max_size)s '
'characters. It is best to keep meta descriptions '
'shorter for better indexing on search engines.'
),
'category': _('SEO'),
'generic_description': _(
| 'Validates the size of a description metatag. It is best '
'to keep meta descriptions shorter for better indexing on '
'search engines. This limit is configurable by Holmes '
'Configuration.'
),
'unit': 'number'... |
Shoufu/Scrapy-Openlaw | openlaw/spiders/test_splash.py | Python | mit | 538 | 0.001859 | # -*- coding: utf-8 -* | -
import scrapy
import requests
from PIL import Image
from scrapy_splash import SplashRequest
class OpenLawSpider(scrapy.Spider):
name = 'test_splash'
allowed_domains = ['openlaw.cn']
start_urls = [
'http://openlaw.cn/search/judgement/court?zoneName=%E5%8C%97%E4%BA%AC%E5%B8%82'
]
def star | t_requests(self):
for url in self.start_urls:
yield SplashRequest(url, self.parse)
def parse(self, response):
print 'Parse Response: '
print response.body
|
sassoftware/jobslave | jobslave_test/keytest.py | Python | apache-2.0 | 5,039 | 0.00258 | #
# 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... | JobSlaveHelper.tearDown(self)
def testMissingKey(self):
DummyRepos.findTrove = lambda *args, **kwargs: (('', '', ''),)
d = Dumm | yIso()
csdir = tempfile.mkdtemp()
logFd, logFile = tempfile.mkstemp()
oldErr = os.dup(sys.stderr.fileno())
os.dup2(logFd, sys.stderr.fileno())
os.close(logFd)
ChangeSetFromFile = changeset.ChangeSetFromFile
Trove = trove.Trove
try:
f = open(os... |
renalreg/radar | radar/api/views/nurture_tubes.py | Python | agpl-3.0 | 1,651 | 0.002423 | from flask import jsonify, request
from radar.api.serializers.nurture_tubes import OptionSerializer, SamplesSerializer
from radar.api.views.common import (
PatientObjectDetailView,
PatientObjectListView,
)
from radar.api.views.generics import ListModelView
from radar.database import db
from radar.exceptions im... | model_class = SampleOption
def register_views(app):
app.add_url_rule('/samples', view_func=SamplesListView.as_view('samples_list'))
app.add_url_rule('/samples/<id>', view_func=SamplesDetailView.as_view('samples_detail'))
app.add_url_rule(
'/samples-protocol-options',
view_func=SamplesP... | iew('samples-protocol-options')
)
|
vFense/vFenseAgent-nix | agent/deps/rpm6/Python-2.7.5/bin/smtpd.py | Python | lgpl-3.0 | 18,564 | 0.000431 | #!/home/toppatch/Python-2.7.5/bin/python2.7
"""An RFC 2821 smtp proxy.
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Options:
--nosetuid
-n
This program generally tries to setuid `nobody', unless this flag is
set. The setuid call will fail if this program is not ... | self.push('501 Syntax: NOOP')
else:
self.push('250 Ok')
def smtp_QUIT(self, arg):
# args is ignored
self.push('221 Bye')
self.close_when_done()
# factored
def __getaddr(self, keyword, arg):
address = None
keylen = len(keyword)
if arg[... | if not address:
pass
elif address[0] == '<' and address[-1] == '>' and address != '<>':
# Addresses can be in the form <person@dom.com> but watch out
# for null address, e.g. <>
address = address[1:-1]
return address
def smt... |
jmesteve/openerpseda | openerp/addons/l10n_es_payment_order/wizard/csb_19.py | Python | agpl-3.0 | 13,523 | 0.007848 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2006 ACYSOS S.L. (http://acysos.com) All Rights Reserved.
# Pedro Tarrafeta <pedro@acysos.com>
# Copyright (c) 2008 Pablo Roc... | tributed 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###########################... |
offlinehacker/flumotion | tests/checks.py | Python | gpl-2.0 | 5,092 | 0.002749 | #!/usr/bin/env python
#
# gst-python
# Copyright (C) 2005 Andy Wingo <wingo@pobox.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your op... | Choose a check to check.')
l.show()
b.pack_start(l, False, False, 0)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_NEVER)
sw.set_shadow_ | type(gtk.SHADOW_IN)
sw.show()
b.pack_start(sw, True, True, 6)
tv = gtk.TreeView(make_model())
tv.set_property('can-default', False)
r = gtk.CellRendererText()
r.set_property('xalign', 0.5)
c = gtk.TreeViewColumn('System', r, text=0)
tv.append_column(c)
... |
justincely/classwork | UMD/AST630/HW2/hw2.py | Python | bsd-3-clause | 4,890 | 0.008793 | """Functions and script for problems in HW2
For problem 3:
--------------
class oblate:
provides the mechanics for calulating the desired orbital values from an
initilized object of a given mass, radius, and moments.
function problem_3():
function to output results using the oblate class on given scenarios
... | radius as a factor of the planetary radius
moments | : list, optional
list of the moment coefficients
"""
self.mass = mass
self.radius = radius
self.moments = moments
@property
def n(self):
"""Calculate the body's orbital frequency
"""
const = np.sqrt(G * self.mass / (self.radius**3))... |
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/python/tvm/_ffi/_ctypes/node.py | Python | apache-2.0 | 2,777 | 0.00144 | # pylint: disable=invalid-name, protected-access
# pylint: disable=no-member, missing-docstring, not-callable
from __future__ import absolute_import
import ctypes
from ..base import _LIB, check_call, c_str
from ..node_generic import _set_class_node_base
from .types import TVMValue, TypeCode
from .types import RETURN_S... | ve a special calling convention to call constructor functions.
So the return handle is directly set into the Node object
instead of creating a new Node.
"""
# assign handle firs | t to avoid error raising
self.handle = None
handle = __init_by_constructor__(fconstructor, args)
if not isinstance(handle, NodeHandle):
handle = NodeHandle(handle)
self.handle = handle
_set_class_node_base(NodeBase)
|
PatSunter/SimpleGTFSCreator | route_segs.py | Python | lgpl-3.0 | 52,470 | 0.003774 |
"""A module for handling and accessing both the in-memory, and on-disk,
representation of a set of routes as a set of segments. Where each segment
specifies its start and end stop ids, and other data (see
topology_shapefile_data_model.py for more."""
import sys
import csv
import re
import operator
import itertools
i... | to_return)
| else:
new_status = True
# +1 since we want to start counter at 1
seg_id = len(all_seg_refs)+1
new_seg_ref = Seg_Reference(seg_id, start_stop_id, end_stop_id,
route_dist_on_seg, routes = [route_id])
# Its a new segment, so append to the list of all segments.
... |
cbcunc/primer | primer/__main__.py | Python | gpl-2.0 | 1,218 | 0 | #! /usr/bin/env python
"""
A __main__ namespace for the primer package.
"""
from __future__ import print_function
import sys
import argparse
from time import time
from primer | import prim | es
def main(argv):
"""Call primes when the package is run as a script."""
parser = argparse.ArgumentParser(
prog='primes',
description='Display the first N primes.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('number',
metav... |
JulienMcJay/eclock | windows/kivy/examples/canvas/repeat_texture.py | Python | gpl-2.0 | 827 | 0.001209 | '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.properties import ObjectProperty
from kivy.lang import Builder
kv = '''
FloatLayout:
ca | nvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
Label:
text: '{} (tr | y to resize the window)'.format(root.size)
'''
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().... |
marcdm/bleach | bleach/sanitizer.py | Python | bsd-3-clause | 6,574 | 0.00502 | from __future__ import unicode_literals
import re
from xml.sax.saxutils import escape, unescape
from html5lib.constants import tokenTypes
from html5lib.sanitizer import HTMLSanitizerMixin
from html5lib.tokenizer import HTMLTokenizer
PROTOS = HTMLSanitizerMixin.acceptable_protocols
PROTOS.remove('feed')
class Bleac... | m, encoding=None, parseMeta=True, useChardet=True,
lowercaseElementName=True, lowercaseAttrName=True, **kwargs):
HTMLTokenizer.__init__(self, stream, encoding, parseMeta, | useChardet,
lowercaseElementName, lowercaseAttrName,
**kwargs)
def __iter__(self):
for token in HTMLTokenizer.__iter__(self):
token = self.sanitize_token(token)
if token:
yield token
|
transientskp/tkp | tkp/accessors/lofaraccessor.py | Python | bsd-2-clause | 886 | 0 | from tkp.accessors.dataaccessor import RequiredAttributesMetaclass
class LofarAccessor(object):
__metaclass__ = RequiredAttributesMetaclass
"""
Additional metadata required for processing LOFAR images through QC
checks.
Attributes:
antenna_set (string): Antenna set in use during observati... | TER', 'LBA_SPARSE', 'LBA' or 'HBA'
ncore(int): Number of core stations in use during observation.
nremote(int): Number of remote stations in use during observation.
nintl(int): Number of international stations in use during observation.
subbandwidth(float): Width of a subband in Hz.
... | 'ncore',
'nremote',
'nintl',
'subbandwidth',
'subbands',
]
|
kemaswill/keras | keras/preprocessing/image.py | Python | mit | 25,315 | 0.001659 | '''Fairly basic set of tools for real-time data augmentation on image data.
Can easily be extended to include new transformations,
new preprocessing methods, etc...
'''
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import re
from scipy import linalg
import scipy.ndimag... | hannels.
fill_mode: points outside the boundaries are filled according to the
given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default
is 'nearest'.
cval: value used for points outside the boundaries when fill_mode is
'constant'. Default is 0.
horizont... | whether to randomly flip images horizontally.
vertical_flip: whether to randomly flip images vertically.
rescale: rescaling factor. If None or 0, no rescaling is applied,
otherwise we multiply the data by the value provided (before applying
any other transformation).
dim... |
henryiii/rootpy | rootpy/tree/chain.py | Python | gpl-3.0 | 10,795 | 0.000093 | # Copyright 2012 the rootpy developers
# distributed under the terms of the GNU General Public License
from __future__ import absolute_import
import multiprocessing
import time
from .. import log; log = log[__name__]
from .. import QROOT
from ..io import root_open, DoesNotExist
from ..utils.extras import humanize_byt... | xist in file {1} (skipping)".format(
self._name, filename))
return self._rollover()
if len(self._tree.GetListOfBranches()) == 0:
log.warning("tree with no branches in file {0} (skipping)".format(
filename))
return self._rollover()
i... | re_branches is not None:
self._tree.deactivate(self._ignore_branches, exclusive=False)
if self._buffer is None:
self._tree.create_buffer(self._ignore_unsupported)
self._buffer = self._tree._buffer
else:
self._tree.set_buffer(
self._buffer,
... |
scripnichenko/nova | nova/tests/unit/api/openstack/test_common.py | Python | apache-2.0 | 26,175 | 0.00042 | # Copyright 2010 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... | om nova.tests.unit import utils
NS = "{http://docs.openstack.org/compute/api/v1.1}"
ATOMNS = "{http://www.w3.org/2005/Atom}"
class LimiterTest(test.NoDBTestCase):
"""Unit tests for the `nova.api.openstack.common.limited` method which
takes in a list of items and, depending on the 'offset' and 'limit' GET
... | ete set of the given items.
"""
def setUp(self):
"""Run before each test."""
super(LimiterTest, self).setUp()
self.tiny = range(1)
self.small = range(10)
self.medium = range(1000)
self.large = range(10000)
def test_limiter_offset_zero(self):
# Test o... |
pianomania/infoGAN-pytorch | trainer.py | Python | mit | 4,627 | 0.007348 | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.autograd as autograd
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.utils import save_image
import numpy as np
clas... | )
dataset = dset.MNIST('./dataset', transform=transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset, batch_size=self.batch_size, shuffle=True, num_workers=1)
# fixed random variables
| c = np.linspace(-1, 1, 10).reshape(1, -1)
c = np.repeat(c, 10, 0).reshape(-1, 1)
c1 = np.hstack([c, np.zeros_like(c)])
c2 = np.hstack([np.zeros_like(c), c])
idx = np.arange(10).repeat(10)
one_hot = np.zeros((100, 10))
one_hot[range(100), idx] = 1
fix_noise = torch.Tensor(100, 62).uniform_... |
nkgilley/home-assistant | homeassistant/components/mqtt/__init__.py | Python | apache-2.0 | 44,531 | 0.001011 | """Support for MQTT message handling."""
import asyncio
from functools import partial, wraps
import inspect
from itertools import groupby
import json
import logging
from operator import attrgetter
import os
import ssl
from typing import Any, Callable, List, Optional, Union
import attr
import certifi
import voluptuous ... | C,
CONF_BIRTH_MESSAGE,
CONF_BROKER,
CONF_DISCOVERY,
CONF_QOS,
CONF_RETAIN,
CONF_STATE_TOPIC,
CONF_WILL_MESSAGE,
DEFAULT_DISCOVERY,
DEFAULT_QOS,
DEFAULT_RETAIN,
MQTT_CONNECTED,
MQTT_DISCONNECTED,
PROTOCOL_311,
)
from .debug_info import log_messages
from .discovery impo... | PublishPayloadType
from .subscription import async_subscribe_topics, async_unsubscribe_topics
from .util import _VALID_QOS_SCHEMA, valid_publish_topic, valid_subscribe_topic
_LOGGER = logging.getLogger(__name__)
DOMAIN = "mqtt"
DATA_MQTT = "mqtt"
DATA_MQTT_CONFIG = "mqtt_config"
SERVICE_PUBLISH = "publish"
SERVICE_... |
mufid/berkilau | ws/CSUIBotClass2014/util/plotter2.py | Python | mit | 1,816 | 0.010463 | import matplotlib.pyplot as pl
import numpy as np
import math
from matplotlib.collections import LineCollection
from matplotlib.colors import colorConverter
def plot(X, m, x_star, t, z_t):
fig = pl.figure(figsize=(10,10))
# Draw the grid first
ax = pl.axes()
ax.set_xlim(-4,20)
ax.set_ylim(-4,20)... | r(pl.MultipleLocator(1.0))
ax.yaxis.set_major_locator( | pl.MultipleLocator(5.0))
ax.yaxis.set_minor_locator(pl.MultipleLocator(1.0))
ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')
ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')
ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='... |
kimjinyong/i2nsf-framework | Hackathon-105/jetconf/tests/test_yangson.py | Python | apache-2.0 | 1,077 | 0.001857 | from yangson.datamodel import DataModel
from yangson.instance import Instan | ceRoute
module_dir = "../yang-data/"
yang_library_file = "../yang-data/yang-library-data.json"
with open(yang_library_file) as ylfile:
yl = ylfile.read()
dm = DataModel(yl, [modu | le_dir])
with open("data.json", "rt") as fp:
json_data = dm.from_raw(json.load(fp))
handler_sn = dm.get_data_node("/dns-server:dns-server-state/zone")
handler_generated = [
{
'domain': 'example.com',
'class': 'IN',
'server-role': 'master',
'serial': 2010111201
}
]
cook... |
brain-research/mirage-rl-qprop | examples/nop_cartpole.py | Python | mit | 665 | 0.001504 | from rllab.algos.nop import NOP
from rllab.baselines.zero_baseline import ZeroBaseline
from rllab.envs.box2d.cartpole_env import CartpoleEnv
from rllab.envs.normalized_env import normalize
from rllab.policies.uniform_control_policy import UniformControlPolicy
env = normalize(CartpoleEnv())
policy = UniformControlPoli... | olicy should have two hidden layers, each | with 32 hidden units.
)
baseline = ZeroBaseline(env_spec=env.spec)
algo = NOP(
env=env,
policy=policy,
baseline=baseline,
batch_size=4000,
max_path_length=100,
n_itr=40,
discount=0.99,
step_size=0.01,
)
algo.train()
|
cloudconductor/cloud_conductor_gui | gui_app/api_models/blueprint_histories.py | Python | apache-2.0 | 762 | 0 | from ..utils import ApiUtil
from ..utils.ApiUtil import Url
class BlueprintHistories:
def __init__(self, code, auth_token, blueprint_id):
self.code = code
self.auth_token = auth_token |
self.blueprint_id = blueprint_id
url = Url.blueprintHistoriesList(self.blueprint_id, Url.url)
data = {
'auth_token': self.au | th_token,
}
self.blueprint_histories = ApiUtil.requestGet(url, self.code, data)
def get_blueprint_history(self, id):
for blueprint_history in self:
if blueprint_history['id'] == id:
return blueprint_history
def __iter__(self):
for blueprint_hi... |
SeiryuZ/HemeWeb | src/jobs/__init__.py | Python | lgpl-3.0 | 43 | 0 | default_ | app_config = 'jobs.apps.JobCo | nfig'
|
prataprc/eazytext | eazytext/extension/ttlpygment.py | Python | gpl-3.0 | 3,677 | 0.032363 | # This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
# Copyright (c) 2009 SKR Farms (P) LTD.
# -*- coding: utf-8 -*-
from pygments.lexer import RegexLexer
from pygments.token import *
try :
from tayra.lexer import TTLLexer
except :
... | ( TTLLexer.importas, Generic.Declaration ),
( TTLLexer.inherit, Generic.Declaration ),
( TTLLexer.implement, Generic.Declaration ),
( TTLLexer.use, Generic.Declaration ),
| # Blocks
( TTLLexer.interface, Name.Function ),
( TTLLexer.function, Name.Function ),
( TTLLexer.if_, Keyword ),
( TTLLexer.elif_, Keyword ),
( TTLLexer.else_, Keyword ),
( TTLLexer.for_, Keyword ),
( TTLLe... |
bbirand/python-driver | tests/integration/standard/test_prepared_statements.py | Python | apache-2.0 | 13,413 | 0.001342 | # Copyright 2013-2015 DataStax, 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 writi... | f.test (v) VALUES (?)
""")
self.assertIsInstance(prepared, PreparedStatement)
bound = prepared.bind({'v': 1})
self.assertRaises(Invali | dRequest, session.execute, bound)
cluster.shutdown()
def test_too_many_bind_values(self):
"""
Ensure a ValueError is thrown when attempting to bind too many variables
"""
cluster = Cluster(protocol_version=PROTOCOL_VERSION)
session = cluster.connect()
prep... |
bgris/ODL_bgris | lib/python3.5/site-packages/pylint/pyreverse/diagrams.py | Python | gpl-3.0 | 8,634 | 0.001042 | # Copyright (c) 2004-2016 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""diagram objects
"""
import astroid
from pylint.pyreverse.... | nue
# associations link
for name, values in list(node.instance_attrs_type.items()) + \
list(node.locals_type.items()):
for value in values:
if value is astroid.YES:
continue
if isinsta... | s_obj = self.object_from_node(value)
self.add_relationship(ass_obj, obj, 'association', name)
except KeyError:
continue
class PackageDiagram(ClassDiagram):
"""package diagram handling
"""
TYPE = 'package'
def modules(self):
"... |
SUSE/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/application_gateway_sku.py | Python | mit | 1,696 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ure.mgmt.network.v2016_09_01.models.ApplicationGatewayTier>`
:param capacity: Capacity (instance count) of an application gateway.
:type capacity: int
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': { | 'key': 'tier', 'type': 'str'},
'capacity': {'key': 'capacity', 'type': 'int'},
}
def __init__(self, name=None, tier=None, capacity=None):
self.name = name
self.tier = tier
self.capacity = capacity
|
majestrate/i2p.socket | i2p/test/test_datatypes.py | Python | mit | 8,496 | 0.003296 | from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
from unittest import TestCase
try:
from i2p.crypto import crypto
except ImportError:
crypto = None
from i2p import datatypes
if crypto is not None:
DSA_ELGAMAL_KEY_CERT = b'BQAEAAAAAA=='
DSA_ELG... | tificate(crypto.DSAKey(),
crypto.ElGamalKey())
dest = datatypes.Destination(cert=keycert)
assert dest.enckey.key_type == crypto.EncType.ELGAMAL_2048
assert dest.sigkey.key_type == crypto.SigType.DSA_SHA1
| assert dest.cert.type == datatypes.CertificateType.NULL
keycert = datatypes.KeyCertificate(crypto.ECDSA256Key(),
crypto.ElGamalKey())
dest = datatypes.Destination(cert=keycert)
self._assert_keycert(dest, crypto.EncTy... |
ology/NLTK-Study | Defs.py | Python | artistic-2.0 | 1,971 | 0.006088 | #!/usr/local/bin/python
# -- coding: utf-8 --
#
# Subroutine defs inspired by http://nltk.org/book/
# -- gene at ology dot net not dot com
#
# Import functionality.
from __future__ import division
import nltk
def generate_model(cfdist, word, num=15):
for i in range(num):
print word,
word = cfdist... | for w in text if w.isalpha()])
t = sum([len(w) for w in v])
return t / len(v)
def unusual_words(text):
text_vocab = set(w.lower() for w in text if w.isalpha())
english_vocab = set(w.lower() for w in nltk.corpus.words.words())
unusual = text_vocab.difference(english_vocab)
return sorted(unusual... |
(target, fileid[:4]) # word-target, address-year
for fileid in text.fileids() # inagural address
for w in text.words(fileid) # all words in the address
for target in [target1, target2] # for each word
if w.lower().startswith(target)) # ...that... |
guorendong/iridium-browser-ubuntu | tools/telemetry/telemetry/util/find_dependencies_unittest.py | Python | bsd-3-clause | 2,648 | 0.007931 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import unittest
import zipfile
from telemetry.util impo... | )
if platform.system() == 'Windows':
with zipfile.ZipFile(zip_path, 'r') as zip_file:
zip_file.extractall(temp_dir)
else:
# Use unz | ip instead of Python zipfile to preserve file permissions.
with open(os.devnull, 'w') as dev_null:
subprocess.call(['unzip', zip_path], cwd=temp_dir, stdout=dev_null)
third_party_path = os.path.join(temp_dir, 'telemetry', 'src', 'tools',
'telemetry', 'third_... |
Pseudonick47/sherlock | backend/config.py | Python | gpl-3.0 | 428 | 0.007009 | import os
dir = os.path.dirname(os.path.realpath(__ | file__))
class BaseConfig(object):
SECRET_KEY = "SO_SECURE"
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = True
class TestConfig(object):
SECRET_KEY = "SO_SECURE"
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + di... | '/test.db'
SQLALCHEMY_TRACK_MODIFICATIONS = True |
Code4SA/pa-hotness | instance/config.py | Python | apache-2.0 | 76 | 0.013158 | DE | BUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///../instance/pa-hotness.db | ' |
rohitranjan1991/home-assistant | homeassistant/components/template/__init__.py | Python | mit | 5,547 | 0.000721 | """The template component."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
import logging
from homeassistant import config as conf_util
from homeassistant.const import (
CONF_UNIQUE_ID,
EVENT_HOMEASSISTANT_START,
SERVICE_RELOAD,
)
from homeassistant.core import Co... | lable[[], None] | None = None
@property
def unique_id(self) -> str | None:
"""Return unique ID for the entity."""
return self.config.get("unique_id")
@callback
def async_remove(self):
"""Signal that the entities need to remove themselves."""
if self._unsub_start:
... | nsub_start()
if self._unsub_trigger:
self._unsub_trigger()
async def async_setup(self, hass_config: ConfigType) -> None:
"""Set up the trigger and create entities."""
if self.hass.state == CoreState.running:
await self._attach_triggers()
else:
sel... |
FormAlchemy/formalchemy | formalchemy/templates.py | Python | mit | 4,638 | 0.004743 | # -*- coding: utf-8 -*-
import os
import sys
from formalchemy.i18n import get_translator
from formalchemy import helpers
from formalchemy.helpers import literal
from tempita import Template as _TempitaTemplate
class TempitaTemplate(_TempitaTemplate):
default_encoding = None
try:
from mako.lookup import TemplateL... | ('directories'))
for name in self._templates:
self.templates[name] = self.get_template(name, **kw)
def | get_template(self, name, **kw):
"""return the template object for `name`. Likely to be overridden by engines"""
return None
def get_filename(self, name):
"""return the filename for template `name`"""
for dirname in self.directories + [os.path.dirname(__file__)]:
filename... |
GhostshipSoftware/avaloria | src/tests/test_utils_logger.py | Python | bsd-3-clause | 979 | 0.011236 | import unittest
class TestLogTrace(unittest.TestCase):
def test_log_trace(self):
# self.assertEqual(expected, log_trace(errmsg))
assert True # TODO: implement your test here
class TestLogErrmsg(unittest.TestCase):
def test_log_errmsg(self):
# self.assertEqual(expected, log_errmsg(errms... |
assert True # TODO: implement your test here
class TestLogWarnmsg(unittest.TestCase):
def test_log_warnmsg(self):
# self.assertEqual(expected, log_warnmsg(warnmsg))
assert True # TODO: implement your test here
class TestLogInfomsg(unittest.TestCase):
def test_log_infomsg(self):
... | sertEqual(expected, log_infomsg(infomsg))
assert True # TODO: implement your test here
class TestLogDepmsg(unittest.TestCase):
def test_log_depmsg(self):
# self.assertEqual(expected, log_depmsg(depmsg))
assert True # TODO: implement your test here
if __name__ == '__main__':
unittest.ma... |
irinabov/debian-qpid-dispatch | tests/router_engine_test.py | Python | apache-2.0 | 27,299 | 0.009194 | #
# 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... | /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 language governing permissions and limitations
# under the License.
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import mock ... |
arsenetar/dupeguru | qt/exclude_list_dialog.py | Python | gpl-3.0 | 7,359 | 0.002582 | # This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
import re
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import (
QPushButton,
QLineEdit... | Sheet("background-color: rgb(10, 200, 10);")
self._input_styled = Tru | e
else:
self.reset_input_style()
def reset_input_style(self):
"""Reset regex input line background"""
if self._input_styled:
self.inputLine.setStyleSheet(self.styleSheet())
self._input_styled = False
def reset_table_style(self):
if self._row_... |
five3/wireless-testing-platform | wtp/controller/QueueController.py | Python | gpl-2.0 | 1,894 | 0.00528 | # -*- coding: utf-8 -*-
'''
Created on May 15, 2015
@author: chenchen9
'''
import json
import lazyxml
import tornado.web
from manager.TestcaseManager import TestcaseManager
class QueueController(tornado.web.RequestHandler):
def get(self):
queue_size = TestcaseManager().get_size()
queue_list = Tes... | else:
self.write(devices_info)
else:
self.render('queue.html', info=dicts)
def post(self):
action = self.get_argument('action', None)
if action=='empty':
Testcas | eManager().empty()
elif action=='remove':
uuid = self.get_argument('uuid', None)
if uuid:
TestcaseManager().remove_by_uuid(uuid)
parent_uuid = self.get_argument('parent_uuid', None)
if parent_uuid:
TestcaseManager().remove_by_parent... |
weigj/django-multidb | django/contrib/gis/geos/base.py | Python | bsd-3-clause | 21,337 | 0.003749 | """
This module contains the 'base' GEOSGeometry object -- all GEOS Geometries
inherit from this object.
"""
# Python, ctypes and types dependencies.
import re
from ctypes import addressof, byref, c_double, c_size_t
from types import UnicodeType
# GEOS-related dependencies.
from django.contrib.gis.geos.coordseq impo... | ries, if available. Have to place in
# try/except since this pac | kage may be used outside GeoDjango.
try:
from django.contrib.gis.gdal import OGRGeometry, SpatialReference, GEOJSON
from django.contrib.gis.gdal.geometries import json_regex
HAS_GDAL = True
except:
HAS_GDAL, GEOJSON = False, False
# Regular expression for recognizing HEXEWKB and WKT. A prophylactic me... |
ajaybhatia/archlinux-dotfiles | Scripts/pythonscripts/subprocess_extensions.py | Python | mit | 760 | 0.007895 | #! /usr/bin/env python
"""
Get status and output of any command, capable of handling unicode.
"""
import subprocess
import codecs
| from tempfiles import *
tmp = TempFiles()
def getstatusoutput(cmd):
logname = tmp.getTempFileName()
log = codecs.open(logname, mode="w", encoding="utf-8", errors="replace", buffering=0)
po | pen = subprocess.Popen(cmd, shell=True, stdout=log, stderr=subprocess.STDOUT, universal_newlines=True)
status = popen.wait()
log.close()
log = codecs.open(logname, mode="r", encoding="utf-8", errors="replace")
output = log.read()
log.close()
tmp.remove(logname)
return status, output
def get... |
sqs/freequery | freequery/index/job.py | Python | agpl-3.0 | 1,947 | 0.002054 | from disco.core import Disco, result_iterator
from disco.settings import DiscoSettings
from disco.func import chain_reader
from discodex.objects import DataSet
from freequery.document import docparse
from freequery.document.docset import Docset
from freequery.index.tf_idf import TfIdf
class IndexJob(object):
def... | }
| ds = DataSet(input=results, options=opts)
origname = self.discodex.index(ds)
self.disco.wait(origname) # origname is also the disco job name
self.discodex.clone(origname, self.spec.invindex_name)
|
zfergus2/Wrapping-Textures | tests/energy_tests/energy_test.py | Python | mit | 7,271 | 0.006602 | """
Testing frame work for Wrapping Textures
Written by Zachary Ferguson
"""
from __future__ import print_function
import scipy.sparse
import scipy.sparse.linalg
import numpy
import pdb
from recordclass import recordclass
import includes
import bilerp_energy as energy
import seam_gradient
from seam_intervals impo... | _count))
x = gen_texture()
total += abs(x.T.dot(A.dot(x)).toarray())
print_clear_line()
print("\tExpected total: %.3f\n\tActual total: %.3f" %
(expected, total))
display_results(test_equal_f(float(total), 0.0), format_str = "\t%s\n")
def test_uniform_texture(my_test, A, test_c... | , A.
Optionally provide a number of iterations for the test.
"""
print("Testing %d uniform textures (x^T*A*x):\n" % test_count)
N = my_test.width * my_test.height
test_texture_energy(lambda: (scipy.sparse.csc_matrix(numpy.ones((N, 1))) *
numpy.random.rand()), A, 0.0, test_count = test_co... |
MingfeiPan/leetcode | math/942.py | Python | apache-2.0 | 381 | 0.002625 | class Solution:
def diStringMatch(self, S: 'str') -> 'List[int]':
ret = []
left = 0
right = len(S)
for i in range(0, len(S)):
if S[i | ] == 'I':
ret.append(left)
left += 1
else:
ret.append(right)
right -= 1
ret.append(left)
return | ret
|
uber-common/deck.gl | bindings/pydeck/pydeck/bindings/layer.py | Python | mit | 6,775 | 0.001919 | import uuid
import numpy as np
from ..data_utils import is_pandas_df, has_geo_interface, records_from_geo_interface
from .json_tools import JSONMixin, camel_and_lower
from pydeck.types import Image
from pydeck.exceptions import BinaryTransportException
TYPE_IDENTIFIER = "@@type"
FUNCTION_IDENTIFIER = "@@="
QUOTE_C... | >>> df = pd.read_csv(UK_ACCIDENTS_DATA)
>>> layer = pydeck.Layer(
>>> 'HexagonLayer',
>>> df,
>>> get_position=['lng', 'lat'],
>>> auto_highlight=True,
>>> elevation_scale=50,
>>> pickable=True,
>>> elevat... | # Add any other kwargs to the JSON output
self._kwargs = kwargs.copy()
if kwargs:
for k, v in kwargs.items():
# We assume strings and arrays of strings are identifiers
# ["lng", "lat"] would be converted to '[lng, lat]'
# TODO given that data... |
wizzat/wizzat.py | wizzat/dbtable.py | Python | mit | 13,346 | 0.011389 | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
from future.utils import with_metaclass
import copy
import types
import wizzat.decorators
from wizzat.pghelper import *
from wizzat.util import set_defaults
__all__ = [
'DBTable',
'DBTableError',
'D... | table_name}
where {where_clause}
{for_update} {nowait}
""".format(
table_name = cls.table_name,
where_clause = sql_where_from_params(**kwargs),
for_update = for_update,
nowait = nowait, |
)
return cls.find_by_sql(sql, **kwargs)
@classmethod
def find_by_sql(cls, sql, **bind_params):
for row in iter_results(cls.conn, sql, **bind_params):
yield cls(_is_in_db = True, **row)
def rowlock(self, nowait = False):
"""
Locks a row in the database ... |
pytrainer/pytrainer | plugins/garmintools/garmintools.py | Python | gpl-2.0 | 4,768 | 0.027475 | # -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
# Modified by dgranda
#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) ... | ols dump files yet")
logging.debug("Cannot validate garmintools dump files yet")
return True
'''xslfile = os.path.realpath(self.parent.parent.data_path)+ "/schemas/GarminTr | ainingCenterDatabase_v2.xsd"
from lib.xmlValidation import xmlValidator
validator = xmlValidator()
return validator.validateXSL(filename, xslfile)'''
def inDatabase(self, tree):
#comparing date and start time (sport may have been changed in DB after import)
time = self.detailsFromFile(tree)
try:
sel... |
drinkertea/pywinauto | pywinauto/handleprops.py | Python | bsd-3-clause | 14,767 | 0.002302 | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... | itted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this | list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permissi... |
tinkerinestudio/Tinkerine-Suite | TinkerineSuite/Cura/util/profile2.py | Python | agpl-3.0 | 23,092 | 0.027239 | from __future__ import absolute_import
from __future__ import division
import os, traceback, math, re, zlib, base64, time, sys, platform, glob, string, stat
import cPickle as pickle
if sys.version_info[0] < 3:
import ConfigParser
else:
import configparser as ConfigParser
from Cura.util import resources
from Cura.ut... | '35.0',
'extruder_head_size_height': '80.0',
'model_colour': '#8BC53F',
'model_colour2': '#CB3030',
'model_colour3': '#DDD93C',
'model_colour4': '#4550D3',
}
#########################################################
## Profile and preferences functions
#########################################################
... | Profile functions
def getDefaultProfilePath():
if platform.system() == "Windows":
basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
#If we have a frozen python install, we need to step out of the library.zip
if hasattr(sys, 'frozen'):
basePath = os.path.normpath(os.pa... |
conorsch/securedrop | securedrop/alembic/versions/48a75abc0121_add_seen_tables.py | Python | agpl-3.0 | 1,840 | 0 | """add seen tables
Revision ID: 48a75abc0121
Revises: 35513370ba0d
Create Date: 2020-09-15 22:34:50.116403
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "48a75abc0121"
down_revision = "35513370ba0d"
branch_labels = None
depends_on = None
def upgrade():
... | es",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("message_i | d", sa.Integer(), nullable=False),
sa.Column("journalist_id", sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("message_id", "journalist_id"),
sa.ForeignKeyConstraint(["message_id"], ["submissions.id"]),
sa.ForeignKeyConstraint(["journalist_id"], [... |
whitepyro/debian_server_setup | tornado/netutil.py | Python | gpl-3.0 | 17,330 | 0.000404 | #!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | raise
callback(connection, address)
io_loop.add_handler(sock, accept_handler, IOLoop.READ)
def is_valid_ip(ip):
"""Returns true if the g | iven |
bswartz/cinder | cinder/volume/drivers/huawei/huawei_driver.py | Python | apache-2.0 | 97,319 | 0 | # Copyright (c) 2016 Huawei Technologies Co., Ltd.
# 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
#
# ... | port one replication_devices.
replica_devs = self.huawei_conf.get_replication_devices()
self.replica_dev_conf = replica_devs[0] if replica_devs else {}
def get_local_and_remote_client_conf(self):
if self.active_backend_id:
return self.replica_dev_conf, self.loc_dev_conf
... | common class and login storage system."""
# Set huawei private configuration into Configuration object.
self.huawei_conf.update_config_value()
self.get_local_and_remote_dev_conf()
client_conf, replica_client_conf = (
self.get_local_and_remote_client_conf())
# init ... |
andymckay/zamboni | mkt/ecosystem/urls.py | Python | bsd-3-clause | 4,853 | 0.000824 | from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from . import views
APP_SLUGS = {
'chrono': 'Chrono',
'face_value': 'Face_Value',
'podcasts': 'Podcasts',
'roller': 'Roller',
'webfighter': 'Webfighter',
'generalnotes': 'General_Notes',
'rtcamera | ': 'rtcamera'
}
def redirect_doc(uri, request=None):
view = RedirectView.as_view(
url='https://developer.mozilla.org/docs%s' % uri)
return view(request) if request else view
redirect_patterns = patterns('',
url('^docs/firefox_os_guideline$',
redirect_doc('/Web/Apps/D | esign'),
name='ecosystem.ffos_guideline'),
url('^docs/responsive_design$',
redirect_doc('/Web_Development/Mobile/Responsive_design'),
name='ecosystem.responsive_design'),
url('^docs/patterns$',
redirect_doc('/Web/Apps/Design/Responsive_Navigation_Patterns'),
name='ecosyst... |
konono/equlipse | openstack-install/charm/trusty/charm-keystone/hooks/manager.py | Python | mit | 11,385 | 0 | #!/usr/bin/python
#
# Copyright 2016 Canonical Ltd
#
# 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 agr... | i.users.create(name=name,
passwor | d=password,
email=email,
tenant_id=tenant_id)
def update_password(self, user, password):
self.api.users.update_password(user=user, password=password)
def roles_for_user(self, user_id, tenant_id=None, domain_id=None):
return self.api.r... |
marmyshev/item_title | openlp/plugins/songs/lib/songimport.py | Python | gpl-2.0 | 15,903 | 0.001698 | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# ------------------------------------------------------... | st and add them or refer to them
as necessary
"""
@staticmethod
def isValidSource(import_source):
"""
Override this method to validate the source prior to import.
"""
return True
def __init__(self, manager, **kwargs):
"""
Initialise and create default... | `manager``
An instance of a SongManager, through which all database access is
performed.
"""
self.manager = manager
QtCore.QObject.__init__(self)
if 'filename' in kwargs:
self.import_source = kwargs['filename']
elif 'filenames' in kwargs:
... |
pandas-dev/pandas | pandas/tests/frame/methods/test_tz_localize.py | Python | bsd-3-clause | 2,050 | 0.000488 | import numpy as np
import pytest
from pandas import (
| DataFrame,
Series,
date_range,
)
import pandas._testing as tm
class TestTZLocalize:
# See also:
# test_tz_convert_and_local | ize in test_tz_convert
def test_tz_localize(self, frame_or_series):
rng = date_range("1/1/2011", periods=100, freq="H")
obj = DataFrame({"a": 1}, index=rng)
obj = tm.get_obj(obj, frame_or_series)
result = obj.tz_localize("utc")
expected = DataFrame({"a": 1}, rng.tz_localiz... |
40323155/2016springcd_aG6 | users/a/g6/ag6.py | Python | agpl-3.0 | 14,459 | 0.006189 | from flask import Blueprint, render_template
# 利用 Blueprint建立 ag1, 並且 url 前綴為 /ag1, 並設定 template 存放目錄
ag6 = Blueprint('ag6', __name__, url_prefix='/ag6', template_folder='templates')
# 展示傳回 Brython 程式
@ag6.route('/a40323152')
def task1():
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
... | "tan",
"lineWidth": linewidth })
# 複製 cmbr, 然後命名為 basic1
basic3 = cmbr.dup()
| basic3.rotate(0)
basic3.translate(0, 20)
basic4 = cmbr.dup()
basic4.rotate(0)
basic4.translate(0, 40)
basic5 = cmbr.dup()
basic5.rotate(90)
basic5.translate(0, 40)
basic6 = cmbr.dup()
basic6.rotate(20)
basic6.translate(20, 40)
cmbr.appendPath(basic3)
... |
edudobay/mingus | mingus/containers/Instrument.py | Python | gpl-3.0 | 7,067 | 0.001415 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
================================================================================
mingus - Music theory Python package, Instrument module
Copyright (C) 2008-2009, Bart Spaans
This program is free software: you can redistribute it and/or modify
it under the... | urn False
def notes_in_range(self, notes):
"""An alias for can_play_notes"""
return can_play_notes(notes)
def can_play_notes(self, notes):
"""Will test if the notes lie within the range of the instrument. Returns \
`True` if so, `False` otherwise."""
if hasattr(note | s, 'notes'):
notes = notes.notes
if type(notes) != list:
notes = [notes]
for n in notes:
if not self.note_in_range(n):
return False
return True
def __repr__(self):
"""A string representation of the object"""
return '%s [%s... |
oconnor663/peru | tests/test_runtime.py | Python | mit | 466 | 0 | import os
import peru.runtime as runtime
import shared
class RuntimeTest(shared.PeruTest):
def t | est_find_peru_file(self):
test_dir = shared.create_dir({
'a/find_me': 'junk',
'a/b/c/junk': 'junk',
})
| result = runtime.find_project_file(
os.path.join(test_dir, 'a', 'b', 'c'),
'find_me')
expected = os.path.join(test_dir, 'a', 'find_me')
self.assertEqual(expected, result)
|
kyuhojeong/controllers | controller/modules/svpn/TincanDispatcher.py | Python | mit | 6,334 | 0.000316 | import json
import sys
from controller.framework.ControllerModule import ControllerModule
import controller.framework.ipoplib as ipoplib
class TincanDispatcher(ControllerModule):
def __init__(self, CFxHandle, paramDict):
super(TincanDispatcher, self).__init__()
self.CFxHandle = CFxHandle
... | recipie | nt='Logger',
action='error',
data="Tincan: "
"Unrecognized message "
"received from Tincan")
self.CFxHandle.submitCBT(logCBT... |
ekohl/ganeti | qa/qa_config.py | Python | gpl-2.0 | 3,219 | 0.013669 | #
#
# Copyright (C) 2007, 2011 Google Inc.
#
# 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 distri... | isk-growth"]):
raise qa_error.Error("Config options 'disk' and 'disk-growth' must have"
" the same number of items")
def ge | t(name, default=None):
return cfg.get(name, default)
def TestEnabled(tests):
"""Returns True if the given tests are enabled.
@param tests: a single test, or a list of tests to check
"""
if isinstance(tests, basestring):
tests = [tests]
return compat.all(cfg.get("tests", {}).get(t, True) for t in tes... |
othreecodes/MY-RIDE | broadcast/migrations/0001_initial.py | Python | mit | 1,998 | 0.003504 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-01 19:47
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depen... | el(
name='TextBroadcast',
fields=[
('broadcast_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, | parent_link=True, primary_key=True, serialize=False, to='broadcast.Broadcast')),
('message', models.TextField()),
],
bases=('broadcast.broadcast',),
),
migrations.AddField(
model_name='broadcast',
name='user',
field=models.Forei... |
lud4ik/txAWS | txaws/tests/test_exception.py | Python | mit | 4,188 | 0 | # Copyright (c) 2009 Canonical Ltd <duncan.mcgreggor@canonical.com>
# Licenced under the txaws licence available at /LICENSE in the txaws source.
from twisted.trial.unittest import TestCase
from txaws.exception import AWSError
from txaws.exception import AWSResponseParseError
from txaws.util import XML
REQUEST_ID =... | /parent>"
error = AWSError("<dummy />", 400)
data | = error._node_to_dict(XML(xml))
self.assertEquals(data, {"child1": "text1", "child2": "text2"})
def test_set_request_id(self):
xml = "<a><b /><RequestID>%s</RequestID></a>" % REQUEST_ID
error = AWSError("<dummy />", 400)
error._set_request_id(XML(xml))
self.assertEquals(erro... |
lazytech-org/RIOT | tests/periph_uart/tests/periph_uart_if.py | Python | lgpl-2.1 | 1,079 | 0 | # Copyright (c) 2018 Kevin Weiss, for HAW Hamburg <kevin.wei | ss@haw-hamburg.de>
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
"""@package PyToAPI
This module handles parsing of informatio | n from RIOT periph_uart test.
"""
try:
from riot_pal import DutShell
except ImportError:
raise ImportError('Cannot find riot_pal, try "pip install riot_pal"')
class PeriphUartIf(DutShell):
"""Interface to the node with periph_uart firmware."""
def uart_init(self, dev, baud):
"""Initialize DUT... |
openattic/openattic | backend/volumes/migrations/0002_remove.py | Python | gpl-2.0 | 5,838 | 0.001884 | # -*- coding: utf-8 -*-
"""
* Copyright (c) 2017 SUSE LLC
*
* openATTIC is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2.
*
* This package is distributed in the hope that it will be useful... | License for more details.
"""
# Django 1.7+ is not capable to render a consistent state of executing this migrations. Thus,
# Django is also not capable of generating the SQL statements.
# I'm getting:
#
# > django.db.migrations.state.InvalidBasesError: Cannot resolve bases for [<ModelState: 'vol | umes.GenericDisk'>]
# > This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)
# > in an app with no migrations; see https://docs.djangoproject.com/en/1.8/topics/migrations/#dependencies for more
#
# This is wrong. This migration now uses manual written SQL to perform the same step... |
jkokorian/ODMAnalysis | odmanalysis/scripts/ViewCyclesInteractive.py | Python | gpl-3.0 | 3,813 | 0.012851 | """
Copyright (C) 2014 Delft University of Technology, The Netherlands
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any lat... | odm
import odmanalysis.gui as _gui
from PyQt4 import QtCore as q
from PyQt4 import QtGui as qt
import pyqtgraph as pg
import numpy as _np
class InteractiveCycleViewer(qt.QWidget):
def __init__(self,df,parent=None):
qt.QWidget.__init__(self,parent)
self.setWindowTitle("Interactive Voltage-... | ut(hLayout)
self.cycleSlider = qt.QSlider(q.Qt.Horizontal)
self.cycleSlider.setTickPosition(qt.QSlider.TicksBothSides)
self.cycleSlider.setTickInterval(1)
hLayout.addWidget(self.cycleSlider)
self.cycleNumberLabel = qt.QLabel("cycle 1")
hLayout.addWidget(... |
ofer43211/unisubs | apps/teams/search_indexes.py | Python | agpl-3.0 | 6,266 | 0.001596 | # Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your op... | m_id"] = team_video.team.id if team_video else None
return self.prepare | d_data
@classmethod
def results_for_members(self, team):
base_qs = SearchQuerySet().models(models.TeamVideo)
public = SQ(is_public=True)
mine = SQ(is_public=False, owned_by_team_id=team.pk)
return base_qs.filter(public | mine)
@classmethod
def results(self):
re... |
juju-solutions/charms.reactive | tests/data/reactive/relations/test-alt/provides.py | Python | apache-2.0 | 561 | 0 | from charms.reactive import Endpoint, when
class TestAltProvides(Endpoint):
invocations = []
@when('endpoint.{endpoint_name}.joine | d')
def handle_joined(self):
self.invocations.append('joined: {}'.format(self.endpoint_name))
| @when('endpoint.{endpoint_name}.changed')
def handle_changed(self):
self.invocations.append('changed: {}'.format(self.endpoint_name))
@when('endpoint.{endpoint_name}.changed.foo')
def handle_changed_foo(self):
self.invocations.append('changed.foo: {}'.format(self.endpoint_name))
|
Ledoux/ShareYourSystem | Pythonlogy/ShareYourSystem/Standards/Viewers/Texter/__init__.py | Python | mit | 2,100 | 0.045238 | # -*- coding: utf-8 -*-
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
A Viewer
"""
#<DefineAugmentation>
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Viewers.Viewer"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer"
SYS.s... | e :\n"
self.TextedConsoleStr+=self.ViewedPointDeriveControllerVariable.hdfview(
).HdformatedConsoleStr
#Check
if self.ViewedPointDeriveControllerVariable.PymongoneDatabaseVariable!=None:
#Check
if self.TextingConditionVariable==None:
self.TextingConditionVariable={}
#map
self.TextedC... | =map(
lambda __CollectionTuple:
__CollectionTuple[0]+' : \n'+SYS._str(
list(
__CollectionTuple[1].find(
self.TextingConditionVariable[__CollectionTuple[0]]
if __CollectionTuple[0] in self.TextingConditionVariable
else {},
self.TextingQueryVariable[__CollectionT... |
Byronic94/py-blog | fabfile.py | Python | gpl-2.0 | 5,473 | 0.00676 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yan Yan'
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
env.user = 'michael'
env.sudo_user = 'root'
env.hosts = ['192.168.0.3']
db_user = 'www-data'
db_password = 'www-data'
_TAR_FILE = 'dist-awesome.tar... | p-table --default-character-set=utf8 --quick awesome > %s' % (db_user, db_password, f))
run('tar -czvf %s.tar.gz %s' % (f, f))
get('%s.tar.gz' % f, '%s/backup/' % _current_path())
run('rm -f %s' % f)
run('rm -f %s.tar.gz' % f)
def build():
'''
Build dist package.
'''
inc... | 'templates', 'transwarp', 'favicon.ico', '*.py']
excludes = ['test', '.*', '*.pyc', '*.pyo']
local('rm -f dist/%s' % _TAR_FILE)
with lcd(os.path.join(_current_path(), 'www')):
cmd = ['tar', '--dereference', '-czvf', '../dist/%s' % _TAR_FILE]
cmd.extend(['--exclude=\'%s\'' % ex for ex in exc... |
andrewkaufman/gaffer | python/GafferSceneUI/CameraUI.py | Python | bsd-3-clause | 15,659 | 0.026968 | # -*- coding: utf-8 -*-
##########################################################################
#
# Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# ... | e mode, the aperture has the fixed
dimensions of `1, 1`, and this plug drives the
`focalLength` parameter.
""",
"layout:visibilityActivato | r", "perspectiveModeFOV",
],
"apertureAspectRatio" : [
"description",
"""
The vertical field of view, according to the ratio
`(horizontal FOV) / (vertical FOV)`. A value of 1 would
result in a square aperture, while a value of 1.778 would
result in a 16:9 aperture.
"Aperture" in this sense is equiva... |
aino/django-arrayfields | arrayfields/__init__.py | Python | bsd-3-clause | 70 | 0 | from .field | s import CharArrayField, TextArrayField, IntegerArrayF | ield
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.