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
cerebrus29301/crowncoin
contrib/solveauxpow.py
Python
mit
3,047
0.029865
#!/usr/bin/env python # Copyright (c) 2014-2015 Daniel Kraft # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # CLI to solve an auxpow (or not) in regtest difficulty. import binascii import hashlib import sys def compu...
ckhash) = mineBlock (header, target, ok) # Build the MerkleTx part of the auxpow. auxpow = tx auxpow +=
blockhash auxpow += "00" auxpow += "00" * 4 # Extend to full auxpow. auxpow += "00" auxpow += "00" * 4 auxpow += header return auxpow def mineBlock (header, target, ok): """ Given a block header, update the nonce until it is ok (or not) for the given target. """ data = byte...
ipa-led/airbus_coop
airbus_ssm_core/src/airbus_ssm_core/ssm_on.py
Python
apache-2.0
2,669
0.010491
#!/usr/bin/env python # # Copyright 2015 Airbus # Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA) # # 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 # # ...
if(rospy.get_param("ssm_enable_log", False) == True): file = open(ud.logfile, "a") for log in self._logs: if(log == "outcome"):
file.write(StrTimeStamped() + self._logs[log] + " " +str(outcome)+"\n") elif(log == ""): file.write(StrTimeStamped() + self._logs[log] +"\n") else: file.write(StrTimeStamped() + self._logs[log] + " " +str(ud[log])+"\n") file.cl...
ctrlaltdel/neutrinator
vendor/openstack/tests/unit/cloud/test_volume.py
Python
gpl-3.0
22,754
0
# 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 t...
{'server_id': 'server001', 'device': device_id} ]) with testtools.ExpectedException( openstack.cloud.OpenStackCloudException, "Volume %s already attached to server %s on device %s" % (
volume['id'], server['id'], device_id) ): self.cloud.attach_volume(server, volume) self.assertEqual(0, len(self.adapter.request_history)) def test_detach_volume(self): server = dict(id='server001') volume = dict(id='volume001', attachments=[ ...
juliatem/aiohttp
tests/test_multipart.py
Python
apache-2.0
67,357
0
import asyncio import functools import io import unittest import zlib from unittest import mock import pytest import aiohttp.multipart from aiohttp import helpers, payload from aiohttp.hdrs import (CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_TRANSFER_ENCODING, CONTENT_TYPE) from aiohttp.h...
self.assertEqual(b'Hello, World!', result) result = yield from obj.read_chunk() self.assertEqual(b'', result) self.assertTrue(obj.at_eof()) def test_read_incomplete_body_chunked(self): stream = Stream(b'Hello, Worl
d!\r\n-') obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream) result = b'' with self.assertRaises(AssertionError): for _ in range(4): result += yield from obj.read_chunk(7) self.assertEqual(b'Hello, World!\r\n-', result) def test_read_bounda...
flowersteam/naminggamesal
naminggamesal/ngstrat/beta_decrease.py
Python
agpl-3.0
700
0.02
from .naive import StratNaive import random import numpy as np class BetaDecreaseStrat(StratNaive): def __init__(self
, vu_cfg, time_scale=0.9, **strat_cfg2): StratNaive.__init__(self,vu_cfg=vu_cfg, **strat_cfg2) self.time_scale = time_scale def update_speaker(self, ms, w, mh, voc, mem, bool_succ, context=[]): self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale) return self.voc_update.update_speaker(ms, w,...
mem, bool_succ, context=[]): self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale) return self.voc_update.update_hearer(ms, w, mh, voc, mem, bool_succ, context)
pmquang/python-anyconfig
anyconfig/backend/xml.py
Python
mit
6,370
0
# # Copyright (C) 2011 - 2015 Satoru SATOH <ssato @ redhat.com> # License: MIT # # Some XML modules may be missing and Base.{load,dumps}_impl are not overriden: # pylint: disable=import-error """XML files parser backend, should be available always. .. versionchanged:: 0.1.0 Added XML dump support. - Format to supp...
return tree tree[root.tag] = cls() if root.attrib: tree[root.tag][
attrs] = cls(anyconfig.compat.iteritems(root.attrib)) if root.text and root.text.strip(): tree[root.tag][text] = root.text.strip() if len(root): # It has children. # Note: Configuration item cannot have both attributes and values # (list) at the same time in current implementation: ...
google/tangent
tangent/tangents.py
Python
apache-2.0
6,571
0.008674
# Copyright 2017 Google 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 wri...
least_1d(d[x]) @tangent_(numpy.atleast_2d) def tatleast_2d(z, x): d[z] = numpy.atleast_2d(d[x]) @tangent_(numpy.atleast_3d) def tatleast_3d(z, x): d[z] = numpy.atleast_3d(d[x]) @tangent_(numpy.transpose) def ttranspose(z, x): d[z] = numpy.transpose(d[x]) @tangent_(numpy.sum) def tsum(y, x, axis=None, dtyp...
s, dtype=dtype, keepdims=keepdims) @tangent_(numpy.mean) def tmean( y, x, axis=None, dtype=None, keepdims=False): d[y] = numpy.mean(d[x], axis=axis, dtype=dtype, keepdims=keepdims) @tangent_(numpy.multiply) def tmultiply(z, x, y): d[z] = numpy.multiply(d[x], y) + numpy.multiply(x, d[y]) @tangent_(numpy.ar...
niklasf/python-chess
examples/push_san.py
Python
gpl-3.0
1,996
0
#!/usr/bin/env python3 """Play the immortal game using push_san() from chess.Board().""" import chess import timeit def play_immortal_game() -> None: board = chess.Board() # 1. e4 e5 board.push_san("e4") board.push_san("e5") # 2. f4 exf4 board.push_san("f4") board.push_san("exf4") ...
oard.push_san("Nf6") # 6. Nf3 Qh6 board.push_san("Nf3")
board.push_san("Qh6") # 7. d3 Nh5 board.push_san("d3") board.push_san("Nh5") # 8. Nh4 Qg5 board.push_san("Nh4") board.push_san("Qg5") # 9. Nf5 c6 board.push_san("Nf5") board.push_san("c6") # 10. g4 Nf6 board.push_san("g4") board.push_san("Nf6") # 11. Rg1! cxb...
vinc456/coala
coalib/output/ConsoleInteraction.py
Python
agpl-3.0
30,377
0
try: # This import has side effects and is needed to make input() behave nicely import readline # pylint: disable=unused-import except ImportError: # pragma: no cover pass import os.path from pyprint.ConsolePrinter import ConsolePrinter from coalib.misc.DictUtilities import inverse_dicts from coalib.bea...
le. :param section: The section that will get executed now. """ console_printer.print("Executing section {name}...".format( name=section.name)) def nothing_done(log_printer): """ Will be called after processing a coafile when nothing had to be done, i.e. no s
ection was enabled/targeted. :param log_printer: A LogPrinter object. """ log_printer.warn("No existent section was targeted or enabled. " "Nothing to do.") def acquire_actions_and_apply(console_printer, log_printer, section...
pbfy0/visvis
functions/volshow2.py
Python
bsd-3-clause
2,734
0.008047
# -*- coding: utf-8 -*- # Copyright (C) 2012, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv import numpy as np def volshow2(vol, clim=None, renderStyle=None, cm=None, axesAdjust=True, axes=None): "...
ol.shape[-1] in [1,3,4]: pass else: raise ValueError('volshow expects a 3D image as a numpy array.') # Get centre centre = [int(s/2) for s in vol.shape] # create textures proxy = vv.SliceTextureProxy(axes) for i in range(3): vv.SliceTexture
(proxy, vol, i, centre[i]) # set clim if isinstance(clim,list): clim = tuple(clim) if isinstance(clim, tuple): proxy.SetClim(clim) # set colormap if cm is not None: proxy.colormap = cm # adjust axes if axesAdjust: if axes.daspectAuto is None: ...
mozilla/inventory
vendor-local/src/django-tastytools/tastytools/example/testdata1.py
Python
bsd-3-clause
198
0.020202
from tastytools.test.resources import
ResourceTestData class Test_1_1_TestData(ResourceTestData): resource = "test_1_1" class Test_1_2_TestDat
a(ResourceTestData): resource = "test_1_2"
CarnegieHall/linked-data
scripts/scrape_mbz_instruments.py
Python
mit
1,346
0.005201
# !/usr/local/bin/python3
.4.2 # ----Copyright (c) 2017 Carnegie Hall | The MIT License (MIT)---- # ----For the full license terms, please visit https://github.com/CarnegieHall/linked-data/blob/master/LICENSE---- ##needs further refinement to eliminate non-instrument link results ## Argument[0] is script to run import csv import httplib2 imp...
= httplib2.Http() link = 'https://musicbrainz.org/instruments' uri_root = 'https://musicbrainz.org' resp, html_doc = h.request(link, "GET") soup = BeautifulSoup(html_doc, "lxml") for result in soup.body.select( 'a[href^"/instrument/"]'): label = result.contents[0].string uri = ''.join([uri_root, result.ge...
nuigroup/pymt-widgets
setup.py
Python
lgpl-3.0
7,237
0.004007
import sys import os import shutil from distutils.core import setup from distutils.e
xtension import Extension #check for numpy, which is absolutely required! try: import numpy except: print '#' * 80 print 'PyMT require numpy now. Please install it before running PyMT
setup' print '#' * 80 sys.exit(1) # extract version (simulate doc generation, pymt will be not imported) os.environ['PYMT_DOC_INCLUDE'] = '1' import pymt #extra build commands go in the cmdclass dict {'command-name': CommandClass} #see tools.packaging.{platform}.build.py for custom build commands for port...
alexfalcucc/anaconda
commands/get_lines.py
Python
gpl-3.0
2,206
0
# Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import sublime im
port sublime_plugin from ..anaconda_lib.helpers import get_settings from ..anaconda_lib.helpers import valid_languages from ..anaconda_lib.linting.sublime import ANACONDA class AnacondaGetLines(sublime_plugin.WindowCommand): """Get a quickpanel with all the errors and l
ines ready to jump to them """ def run(self): errors = {} self._harvest_errors(errors, 'ERRORS') self._harvest_errors(errors, 'WARNINGS') self._harvest_errors(errors, 'VIOLATIONS') if len(errors) > 0: self.options = [] for line, error_strings in ...
chenshuo/recipes
python/throughput.py
Python
bsd-3-clause
7,242
0.004557
#!/usr/bin/python3 # A simple program to test TCP throughput, by sending 1GiB data. import socket, sys, time def report(name : str, total_bytes : int, elapsed_seconds : float): mbps = total_bytes / 1e6 / elapsed_seconds print('%s t
ransferred %.3fMB in %.3fs, throughput %.3fMB/s %.3fMbits/s' % (name, total_bytes / 1e6, elapsed_seconds, mbps, mbps
* 8)) def run_server(port : int): server_socket = socket.create_server(('', port)) # Requires Python 3.8 sock, client_addr = server_socket.accept() print('Got client from %s:%d' % client_addr) start = time.time() total = 0 while True: data = sock.recv(65536) if not data: ...
potato/searx
searx/webapp.py
Python
agpl-3.0
30,984
0.002098
#!/usr/bin/env python ''' searx 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 option) any later version. searx is distributed in the hope that it will be use...
lates, get_themes, gen_useragent, dict_subset, prettify_url ) from searx.version impor
t VERSION_STRING from searx.languages import language_codes from searx.search import SearchWithPlugins, get_search_query_from_webapp from searx.query import RawTextQuery from searx.autocomplete import searx_bang, backends as autocomplete_backends from searx.plugins import plugins from searx.preferences import Preferenc...
RedhawkSDR/integration-gnuhawk
components/interleave_cc_1i/tests/test_interleave_cc_1i.py
Python
gpl-3.0
4,075
0.006871
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
parameters # Query of '[]' should return the following set of properties expectedProps = [] expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)) expectedProps.extend(self.getPropertySet(kinds=("allocate",), action=...
.query([]) props = dict((x.id, any.from_any(x.value)) for x in props) # Query may return more than expected, but not less for expectedProp in expectedProps: self.assertEquals(props.has_key(expectedProp.id), True) ######################################################...
fioreinc/ipp-15-16
deprecated/catkin_ws/install/lib/python2.7/dist-packages/loadcell_calibration/srv/_GetFactor.py
Python
gpl-3.0
6,807
0.017335
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from loadcell_calibration/GetFactorRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetFactorRequest(genpy.Message): _md5sum = "36d09b846be0b371c5f190354dd...
aram kwds: use keyword arg
uments corresponding to message field names to set specific fields. """ if args or kwds: super(GetFactorRequest, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.a is None: self.a = 0 if self.b is None: sel...
howie6879/novels-search
owllook/database/redis/redisbase.py
Python
apache-2.0
778
0.002571
#!/usr/bin/env python import asyncio_redis from owllook.config import CONFIG # Token from https://github.com/subyraman/sanic_session class RedisSession: """ A simple wrapper class that allows you to share a connection pool across your application. """ _pool = None async def get_redis_pool(se...
cio_redis.Pool.create( host=str(REDIS_DICT.get('REDIS_ENDPOINT', "localhost")), port=int(REDIS_DICT.get('REDIS_PORT', 6379)), poolsize=int(REDIS_DICT.get('POOLSIZE', 10)), passwor
d=REDIS_DICT.get('REDIS_PASSWORD', None), db=REDIS_DICT.get('SESSION_DB', None) ) return self._pool
turon/openthread
tools/harness-automation/cases/reed_5_2_5.py
Python
bsd-3-clause
1,875
0
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
s may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND ...
ITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSIN...
sassoftware/rmake
rmake/messagebus/envelope.py
Python
apache-2.0
14,277
0.001261
# # 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...
ble self._incomplete = None magiclen = len(self.magic) if data[:magiclen] != self.magic: raise BadMagicError() self.thaw(data[magiclen:]) class PHeader(object): def __init__(self): self.headers = {} self.buf = None def freeze(self):
return str(self) def __getitem__(self, key): return self.headers[key] def __setitem__(self, key, value): if isinstance(value, (list, tuple)): for item in value: if '\n' in str(item): raise ValueError, 'Cannot have newlines in headers.' ...
valandil/msc_thesis
figs/backmatter/sphericalHarmonics.py
Python
gpl-3.0
998
0.014028
# ------------------- Information --------------------- # # Author: Joey Dumont <joey.dumont@gmail.com> # # Date created: October 18th, 2013 # # Date mod. October 18th, 2013 # # Description: We plot the times it took to compute # # sets of Wigner symbols of diff
erent # # sizes. # # -------------
---------------------------------------- # # --------------- Modules Importation ----------------- # from pylab import * from matplotlib.ticker import AutoMinorLocator # ----------------- Data Importation ------------------ # prec = loadtxt("precisionSph.dat") # ------------------ Plotting data -------------------- ...
iuyo5678/xiangyun_front
controller/api/data_process_wrap.py
Python
apache-2.0
1,559
0.00196
#!/usr/bin/env python # -*- coding: utf-8 -*- # Time-stamp: <2016-01-07 19:04:35 Thursday by zhangguhua> ################################################################################ # _ooOoo_ # o8888888o # 88" . "88 # ...
(| -_- |) # O\ = /O # ____/`---'\____ # .' \\| |// `.
# / \\||| z |||// \ # / _||||| -g- |||||- \ # | | \\\ h /// | | # | \_| ''\---/'' | | # \ .-\__ `-` ___/-. / # ___`. .' /--.--\ `. . __ # ...
s6530085/FundSpider
index/parser.py
Python
mit
1,325
0.003891
# -*- coding: utf-8 -*- __author__ = 'study_sun' from lxml import etree from entity import * import sys reload(sys) sys.setdefaultencoding('utf-8') class IndexParser(object): def p
arse_index_list(self, index_list_content): # 编码还是有问题哦 index_list_content = index_list_content.encode('ISO-8859-1').decode('utf-8') parsed_content = etree.HTML(index_list_content, parser=etree.HTMLParser(encoding='utf-8')) trs = parsed_content.xpath('//tbody/tr') indexs = [] ...
th('./td') if len(tds) == 5: index = IndexInfo() code = tds[0].text.strip() if len(code.split('.')) == 2: index.code = code.split('.')[0] index.full_code = code index.name = tds[1].text.strip() ...
AriZuu/micropython
tests/basics/set_iter.py
Python
mit
48
0.041667
s = {1, 2, 3, 4}
l = list(s) l.
sort() print(l)
Hakugin/TimeClock
_dialogs.py
Python
gpl-2.0
19,476
0.005956
# _dialogs.py import wx import _widgets as _wgt from wx.lib.wordwrap import wordwrap __version__ = '1.0.0' import logging log = logging.getLogger('root') class CustomDialog(wx.Dialog): def __init__(self, parent, *arg, **kw): style = (wx.NO_BORDER | wx.CLIP_CHILDREN) self.borderColour = wx.BLACK...
lf, event): evtObj = event.GetEventObject() evtObjBG = evtObj.GetBackgroundColour() dc = wx.PaintDC(evtObj) dc = wx.GCDC(dc) w, h = self.GetSizeTuple() r = 10 dc.SetPen( wx.Pen(self.borderColour,3) ) dc.SetBrush( wx.Brush(evtObjBG)) dc.DrawRectang...
self.CaptureMouse() if not self._dragPos: self._dragPos = event.GetPosition() else: pos = event.GetPosition() displacement = self._dragPos - pos self.SetPosition( self.GetPosition() - displacement ) self.ReleaseMouse() event.Skip() ...
willrp/willbuyer
backend/controller/api/store/product/product.py
Python
mit
1,589
0.003147
import os from flask import current_app as app from flask_restplus import Namespace, Resource from requests import get from backend.util.response.store.product_results import ProductResultsResponse from backend.util.response.error import ErrorResponse from backend.controller import ErrorHandler productNS = Namespace...
f get(self, productid): """Product information.""" try: req = get("%s/api/product/%s" % (self.__url, productid), headers=self.__headers) req.raise_for_status() jsonsend = ProductResultsResponse.marshall_json(req.json()) r
eturn jsonsend except Exception as error: return ErrorHandler(error).handle_error()
skg-net/ansible
lib/ansible/modules/network/panos/panos_security_rule.py
Python
gpl-3.0
19,823
0.001766
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, techbizdev <techbizdev@paloaltonetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version':...
iles: ['any'] action: 'allow' devicegroup: 'Cloud Edge' - name: add a rule to allow HTTP multimedia only from CDNs panos_security_rule: ip_address: '10.5.172.91' username: 'admin' password: 'paloalto' operation: 'add' rule_name: 'HTTP Multimed
ia' description: 'Allow HTTP multimedia only to host at 1.1.1.1' source_zone: ['public'] destination_zone: ['private'] source_ip: ['any'] source_user: ['any'] destination_ip: ['1.1.1.1'] category: ['content-delivery-networks'] application: ['http-video', 'http-audio'] service: ['serv...
aleximplode/Show-Tracker
src/dataclasses.py
Python
mit
23,821
0.0123
from PyQt4.QtCore import QAbstractListModel, QAbstractTableModel, QVariant, Qt, QModelIndex, SIGNAL, pyqtSignal, QDateTime, QString from PyQt4.QtGui import QIcon, QPixmap, QImage, QBrush, QColor from datetime import datetime from exceptions import TypeError clas
s show(object): ''' A representation of a show ''' def __init__(self, name = u'', description = u'', image = u'', id = u'', data = None, actors = [], contentrating = u'', firstaired = datetime.min, genre = [], imdb = u'', network = u'', rating = 0.0, runtime = 0, status = u''): '''...
@type name: str @type description: str @type image: str @type id: str @type data: obj @type actors: list @type contentrating: str @type firstaired: datetime @type genre: list @type imdb: str @type network: str @type ratin...
hunse/codify
codify/test_oclcode.py
Python
mit
1,803
0.001664
from sympy.core import pi, oo, symbols, Function, Rational from sympy.functions import exp, log, sqrt, erf, erfc, gamma, loggamma # from sympy import ccode from oclcode import oclcode x, y, z = symbols('x,y,z') i = symbols('i', integer=True) def asserteq(a, b): if a != b: raise AssertionError("%s != %s"...
))
== "abs(i)" assert oclcode(abs(x)) == "fabs(x)" assert oclcode(log(x)) == "log(x)" assert oclcode(log(x, 2)) == "log2(x)" assert oclcode(log(x, 10)) == "log10(x)" assert oclcode(log(x, 3)) == "log(x)/log(3)" def test_functions_inserted(): assert oclcode(2**x) == "exp2(x)" assert oclcode(10...
epronk/pyfit2
examples/chat/ChatRoom.py
Python
gpl-2.0
901
0.00444
from User import User from Room import Room class ChatRoom(object): def __init__(self): self.users = {} self.rooms = {} def connectUser(self, userName): if self.users.has_key(userName): return False self.users[userName] = User(userName) return True def ...
elf, userName, roomName): user = self.users[userName] self.createRoom(roomName, user) def createRoom(self, roomName, user): if self.rooms.has_key(roomName): raise Exception("Duplicate room name: " + roomName) self.rooms[roomName] = Room(roomName, user, self) def use...
s(self, roomName): room = self.rooms[roomName] return room.occupantCount()
savoirfairelinux/partner-addons
google_partner_address/models/res_partner.py
Python
lgpl-3.0
322
0
# -*- coding: utf
-8 -*- #
© 2017 Savoir-faire Linux # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import api, models class ResPartner(models.Model): _inherit = 'res.partner' @api.onchange('zip') def _onchange_zip(self): self.zip = self.zip.upper() if self.zip else ""
Jimdo/unattended-upgrades
setup.py
Python
gpl-2.0
968
0.012397
#!/usr/bin/env python from distutils.core import setup from DistUt
ilsExtra.command import * import glob import os setup(name='unattended-upgrades', version='0.1', scripts=['unattended-upgrade'], data_files=[ ('../etc/apt/apt.conf.d/', ["data/50unattended-upgrades"]), ('../etc/logrotate.d/', ["data/logrotate...
./usr/share/unattended-upgrades/', ["data/20auto-upgrades", "data/20auto-upgrades-disabled", "unattended-upgrade-shutdown"]), ('../usr/share/man/man8/', ["man/unattended-upgrade.8"]), ('../etc/pm/sleep.d/',...
idegtiarov/ceilometer
ceilometer/tests/unit/network/test_floating_ip.py
Python
apache-2.0
4,313
0
# #!/usr/bin/env python # # Copyright 2016 Sungard Availability Services # Copyright 2016 Red Hat # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); y
ou 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...
g permissions and limitations # under the License. import mock from oslotest import base from oslotest import mockpatch from ceilometer.agent import manager from ceilometer.agent import plugin_base from ceilometer.network import floatingip class _BaseTestFloatingIPPollster(base.BaseTestCase): @mock.patch('ceil...
onehao/opensource
pyml/basic/extension/selfkeyword.py
Python
apache-2.0
3,171
0.02554
#!/usr/bin/python # -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------- Function: 【整理】Python中:self和init__的含义 + 为何要有self和__init__ http://www.crifan.com/summary_the_meaning_of_self_and___init___in_python_and_why_need_them Author: Crifan Verison: 2012-11-27 -...
global name name = "new class global name" class Child(Person): def say(self): #此处,之所以没有像之前一样出现: #AttributeError: Person instance has no attribute 'name' #那是因为,虽然当前的实例self中,没有在__init__中初始化对应的name变量,实例self中没有对应的name变量 #但是由于实例所对应的类Person,有对应的name变量,所以也是可以正常执行代码的 ...
s'%(name); #-> whole global name print "only access Person's name via Person.name=%s"%(Person.name); # -> class global name #def __init__(self): def selfAndInitDemo(): persionInstance = Person("crifan"); persionInstance.sayYourName(); personInstance2 = Person("michael") personI...
fviard/s3cmd
S3/Custom_httplib27.py
Python
gpl-2.0
8,180
0.001834
from __future__ import absolute_import, print_function import os import httplib from httplib import (_CS_REQ_SENT, _CS_REQ_STARTED, CONTINUE, UnknownProtocol,
CannotSendHeader, NO_CONTENT, NOT_MODIFIED, EXPECTATION_FAILED, HTTPMessage, HTTPException) try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from .BaseUtils import encode_to_s3 _METHODS_EXPECTING_BODY = ['PATCH', 'PO
ST', 'PUT'] # Fixed python 2.X httplib to be able to support # Expect: 100-Continue http feature # Inspired by: # http://bugs.python.org/file26357/issue1346874-273.patch def httpresponse_patched_begin(self): """ Re-implemented httplib begin function to not loop over "100 CONTINUE" status replies but to re...
sandspider2234/Logical
routes.py
Python
mit
8,750
0.003314
import random from BinTree import BinTree import flask import flask_login import forms import db app = flask.Flask(__name__) app.config.from_object('config') login_manager = flask_login.LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' class User(flask_login.UserMixin): def __init__(s...
oginForm(prefix='login_form') signup_form = forms.SignupForm(prefix='signup_form') if
signup_form.register.data and signup_form.validate_on_submit(): with db.create_connection() as connection: with connection.cursor() as cursor: sql = "SELECT * FROM users WHERE username=%s OR email=%s" cursor.execute(sql, (signup_form.username.data, signup_form.email....
riklaunim/django-basic-stats
stats/urls.py
Python
mit
578
0.00346
from django.conf.urls import url import stat
s.views urlpatterns = [ url(r'^$', stats.views.stats_home, name='stats-home'), url(r'^entries/$', stats.views.unique_entries, name="stats-unique-entries"), url(r'^refs/$', stats.views.last_referers, name="stats-referers"), url(r'^google/$', stats.views.google_search_keywords, name="stats-google"), ...
rl(r'^mobile_devices/$', stats.views.mobile_devices, name="stats-mobile-devices"), ]
vijeth-aradhya/coala-bears
tests/general/InvalidLinkBearTest.py
Python
agpl-3.0
9,579
0.000104
import io from queue import Queue import requests import requests_mock import unittest import unittest.mock from bears.general.InvalidLinkBear import InvalidLinkBear from coalib.settings.Section import Section def custom_matcher(request): """ Mock the status codes for every request by taking the last three c...
ears svn+http://httpbin.org/status/200@master#egg=coala-bears hg+http://httpbin.org/status/200@master#egg=coala-bears bzr+http://httpbin.org/status/200@master#egg=coala-bears """.spl
itlines() self.assertResult(valid_file=with_at_hash) brokenlink_at = """git+http://httpbin.org/status/404@master svn+http://httpbin.org/status/404@master hg+http://httpbin.org/status/404@master bzr+http://httpbin.org/status/404@master""" for line in brokenlink_at.split...
yuanyelele/solfege
solfege/mainwin.py
Python
gpl-3.0
35,025
0.005054
# vim: set fileencoding=utf-8 : # GNU Solfege - free ear training software # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2011 Tom Cato Amundsen # # 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 F...
k.format_exception(*sys.exc_info()))) if solfege.splash_win: solfege.splash_win.show() self.di
splay_frontpage() def setup_menu(self): self.m_action_groups['Exit'].add_actions([ ('FileMenu', None, _('_File')), ('AppQuit', 'gtk-quit', None, None, None, self.quit_program), ]) self.m_action_groups['NotExit'].add_actions([ ('TheoryMenu', None, _('The_ory')), ...
SmileEric/SEIMS
preprocess/build_db.py
Python
gpl-2.0
4,531
0.0064
#! /usr/bin/env python #coding=utf-8 import sys, os, thread from pymongo import Connection from pymongo.errors import ConnectionFailure from import_parameters import ImportParameters from generate_stream_input import GenerateReachTable from find_sites import FindSites from weights_mongo import GenerateWeightInfo impor...
f stormMode: hydroDBName = hydroDBName + "_storm_cmorph" if stormMode: meteoThiessenList = [thiessenFilePreci] meteoTypeList = ['P'] else:
meteoThiessenList = [thiessenFileMeteo, thiessenFilePreci] meteoTypeList = ['M', 'P'] f.write("20, Finding nearby stations for each sub-basin...\n") f.flush() nSubbasins = FindSites(db, hydroDBName, subbasinFile, meteoThiessenList, meteoTypeList, simuMode) print "Number of sub-basins:", nSubba...
awemulya/fieldsight-kobocat
onadata/apps/logger/south_migrations/0009_auto__add_field_xform_shared_data.py
Python
bsd-2-clause
6,913
0.00839
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'XForm.shared_data' db.add_column('odk_logger_xform', 'shared_data', self.gf('django.db.mod...
kwards(self, orm): # Deleting field 'XForm.shared_data' db.delete_column('odk_logger_xform', 'shared_data') models = { 'auth.group': { 'Meta': {'ob
ject_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permissi...
lubang/calimap
server/domain/alphabet_models.py
Python
apache-2.0
863
0.003476
from sqlalchemy import Column, Integer, String, Float from sqlalchemy.ext.declarative import declarative_base # References #
1. https://github.com/mitsuhiko
/flask-sqlalchemy/issues/98 Base = declarative_base() class Alphabet(Base): __tablename__ = 'alphabet' id = Column(Integer, primary_key=True) alphabet = Column(String(1)) lat = Column(Float) long = Column(Float) zoom = Column(Integer) image_path = Column(String(50)) def __init__(self...
ernestoalarcon/competitiveprogramming
alien-username.py
Python
mit
373
0.008043
#!/bin/python # Solution f
or https://www.h
ackerrank.com/challenges/alien-username import re def is_valid_username(s): pattern = r'^[_\.][0-9]+[a-zA-Z]*_?$' match = re.match(pattern, s) return match n = int(raw_input().strip()) for i in range(n): s = raw_input().strip() if is_valid_username(s): print 'VALID' else: prin...
JanMalte/secondhandshop_server
src/events/migrations/0001_initial.py
Python
mit
2,181
0.000917
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import audit_log.models.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)] operations = [ m...
), ( "modified_date", models.DateTimeField( db_column="date_modified", null=True, blank=True ), ), ("name", models.CharField(db_column="event_name", max_length=255)), ...
g_start_date", models.DateTimeField(db_column="reservation_start_date"), ), ( "booking_end_date", models.DateTimeField(db_column="reservation_end_date"), ), ( "created_by", ...
tidalmelon/twisted-intro
twisted-deferred/defer-8.py
Python
mit
562
0.008897
import sys from twisted.internet.defer import Deferred def got_poem(poem): print poem from twisted.internet i
mport reactor reactor.stop() def poem_failed(err): print >>sys.stderr, 'poem download failed' print >>sys.stderr, 'I am terribly sorry' print >>sys.stderr, 'try again later?' from twisted.internet import reactor reactor.stop() d = Deferred() d.addCallbacks(got_p
oem, poem_failed) from twisted.internet import reactor reactor.callWhenRunning(d.callback, 'Another short poem.') reactor.run() #Another short poem.
davelab6/nototools
nototools/grab_mt_download.py
Python
apache-2.0
4,740
0.009494
#!/usr/bin/python # # Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
This reflects the date of the drop. For each zip of this type we build a root named for the date in the target directory. Most drops contain a two-lev
el tree with the font name and a suffix of either '_hinted or '_unhinted' on the top level, and the relevant data underneath. Our structure just uses 'hinted' or 'unhinted', so we convert, putting these under the root for the zip. Some drops have a single level tree, we examine the fonts to determine if they have hin...
lanhel/ftpysetup
ftpysetup/runtest/unit.py
Python
apache-2.0
1,588
0.001889
#!/usr/bin/env python # -*- coding: UTF-8 -*- #------------------------------------------------------------------------------- """Setuptools command to execute unit tests.""" __author__ = ('Lance Finn Helsten',) __version__ = '0.7.4' __copyright__ = """Copyright (C) 2014 Lance Helsten""" __docformat__ = "reStructuredTe...
://www.apache.org/licenses/LICENSE-2.0 Unless require
d 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 ....
dhilipsiva/talks
assets/2019-11-30/github_pb2.py
Python
mit
6,115
0.004742
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: github.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf impo...
t_type=_REPLY, serialized_options=None, ), ]) _sym_db.RegisterServiceDescriptor(_ACCOUNT) DESCRIPTOR.services_by_name['Account']
= _ACCOUNT _GIST = _descriptor.ServiceDescriptor( name='Gist', full_name='Gist', file=DESCRIPTOR, index=1, serialized_options=None, serialized_start=154, serialized_end=197, methods=[ _descriptor.MethodDescriptor( name='GetPublicGist', full_name='Gist.GetPublicGist', index=0, contai...
googleads/google-ads-python
google/ads/googleads/v9/enums/types/feed_mapping_status.py
Python
apache-2.0
1,148
0.000871
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in
compliance with the License. # You may obtain a copy of the License at # # http://
www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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...
fbradyirl/home-assistant
homeassistant/components/twilio_call/notify.py
Python
apache-2.0
1,891
0
"""Twilio Call platform for notify component.""" import logging import urllib import voluptuous as vol from homeassistant.components.twilio import DATA_TWILIO import homeassistant.helpers.config_validation as cv from homeassistant.components.notify import ( ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationS...
to=target, url=twimlet_url, from_=self.from_number )
except TwilioRestException as exc: _LOGGER.error(exc)
donnell74/CSC-450-Scheduler
tests/structures/test_room.py
Python
mit
628
0.006369
from __future__ import print_function import unittest from genetic.structures import * from genetic import * sample_scheduler = interface.create_scheduler_from_file_test("tests/schedules/morning_class_test.xml") class TestRoom(unittest.TestCase): def s
etUp(self): self.roomMWF = sample_scheduler.weeks[0].days[0].rooms[0] self.roomTR = sample_scheduler.weeks[0].days[1].rooms[0] def tearDown(self): pass def test_init(self): self.assertEqual(len(self
.roomMWF.schedule), 3) self.assertEqual(len(self.roomTR.schedule), 5) if __name__ == "__main__": unittest.main()
DLance96/nativx-survey
survey/personality_analyzer.py
Python
mit
3,410
0.002346
# # https://github.com/watson-developer-cloud/personality-insights-twitter-python/blob/master/twitteranalyzer.py # import sys import os import requests import json import twitter import config def convert_status_to_pi_content_item(s): # My code here return { 'userid': str(s.user.id), 'id': st...
: statuses_portion = twitter_api.GetUserTimeline(screen_name=handle, count=200, max_id=max_id, include_rts=False) statu...
below for next tweet set for status in statuses_portion: statuses.append(status) pi_content_items_array = map(convert_status_to_pi_content_item, statuses) pi_content_items = {'contentItems': pi_content_items_array} r = requests.post(os.environ.get('PI_URL') + '/v2/profile', ...
alejob/mdanalysis
package/setup.py
Python
gpl-2.0
22,845
0.002758
#!/usr/bin/env python # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- http://www.mdanalysis.org # Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the ...
val def get_numpy_include(): # Obtain the numpy include directory. This logic works across numpy # versions. # setuptools forgets to unset numpy's s
etup flag and we get a crippled # version of it unless we do it ourselves. try: # Python 3 renamed the ``__builin__`` module into ``builtins``. # Here we import the python 2 or the python 3 version of the module # with the python 3 name. This could be done with ``six`` but that #...
tobi-weber/levitas
src/levitas/middleware/__init__.py
Python
apache-2.0
22,256
0.004538
# -*- coding: utf-8 -*- # Copyright (C) 2010-2013 Tobias Weber <tobi-weber@gmx.de> # # 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 ...
or(405) def get(self): """ Can be overridden by sub-classes. """ log.error("get method not implemented in %s" % str(self.__class__)) return self.responseError(405) def post(self): """ Can be overridden by sub-classes. """ log.error("post method not implemented in %s" % ...
rridden by sub-classes. """ log.error("delete method not implemented in %s" % str(self.__class__)) return self.responseError(405) def put(self): """ Can be overridden by sub-classes. """ log.error("put method not implemented in %s" % str(self.__class__)) return self.resp...
the-zebulan/CodeWars
tests/beta_tests/test_what_color_is_your_name.py
Python
mit
656
0
import unittest from katas.beta.what_color_is_your_name import string_color class StringColorTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(string_color('Jack'), '79CAE5') def test_equal_2(self): self.assertEqual(string_color('Joshua'), '6A10D6') def test_equal_3(...
ual(string_color('Joshua Smith'), '8F00FB') def test_equal_4(self): self.assertEqual(string_color('Hayden Smith'), '7E00EE') def test_equal_5(self): self.assertEqual(string_color('Mathew Smith'), '8B00F1')
def test_is_none_1(self): self.assertIsNone(string_color('a'))
OS2World/APP-INTERNET-torpak_2
btlaunchmany.py
Python
mit
9,812
0.009682
#!/usr/bin/env python # Written by Michael Janssen (jamuraa at base0 dot net) # originally heavily borrowed code from btlaunchmany.py by Bram Cohen # and btdownloadcurses.py written by Henry 'Pi' James # now not so much. # fmttime and fmtsize stolen from btdownloadcurses. # see LICENSE.txt for license information fr...
dropdir_mainloop(d, params): deadfiles = [] global threads, status while 1: fi
les = listdir(d) # new files for file in files: if file[-len(ext):] == ext: if file not in threads.keys() + deadfiles: threads[file] = {'kill': Event(), 'try': 1} print 'New torrent: %s' % file stdout.flush() ...
eandersson/amqp-storm
amqpstorm/tests/unit/tx_tests.py
Python
mit
4,443
0
from pamqp import specification from amqpstorm.channel import Channel from amqpstorm.tests.utility import FakeConnection from amqpstorm.tests.utility import TestFramework from amqpstorm.tx import Tx class TxTests(TestFramework): def test_tx_select(self): def on_tx_select(*_): channel.rpc.on_f...
ance(tx.select(), dict) self.assertTrue(tx._tx_active) def test_tx_commit(self): def on_tx_commit(*_): channel.rpc.on_frame(specification.Tx.CommitOk()) connection =
FakeConnection(on_write=on_tx_commit) channel = Channel(0, connection, 0.01) channel.set_state(Channel.OPEN) tx = Tx(channel) self.assertIsInstance(tx.commit(), dict) self.assertFalse(tx._tx_active) def test_tx_rollback(self): def on_tx_rollback(*_): cha...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/global_/state/__init__.py
Python
apache-2.0
36,541
0.001204
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
base=RestrictedClassType(
base_type=six.text_type, restriction_dict={ "pattern": "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$" }, ), is_leaf=True, yang_name="router-id", ...
USStateDept/FPA_Core
openspending/views/api_v4/aggregate.py
Python
agpl-3.0
1,586
0.006936
import logging from datetime import datetime import os from flask import request, g, Response, jsonify from openspending.views.api_v4.common import blueprint from openspending.lib.apihelper import DataBrowser_v4, GEO_MAPPING,FORMATOPTS from openspending.lib.jsonexport import to_json from openspending.lib.helpers...
e return False
@blueprint.route("/api/4/slicer/aggregate", methods=["JSON", "GET"]) @api_json_errors @cache.cached(timeout=60, key_prefix=cache_key, unless=xlschecker) def slicer_agg(): d = DataBrowser_v4() return d.get_response() @blueprint.route("/api/4/slicer/model", methods=["JSON", "GET"]) @api_json_errors @cache.cache...
saltstack/salt
tests/pytests/unit/states/test_win_iis.py
Python
apache-2.0
8,811
0.000794
""" :synopsis: Unit Tests for Windows iis Module 'state.win_iis' :platform: Windows .. versionadded:: 2019.2.2 """ import pytest import salt.states.win_iis as win_iis from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {win_iis: {}} def __base_webc...
t": "Settings will be changed.", "result": None, } with patch.dict( win_iis.__salt__, { "win_iis.get_container_setting": MagicMock( side_effect=[old_settings, current_settings, new_settings]
), "win_iis.set_container_setting": MagicMock(return_value=True), }, ), patch.dict(win_iis.__opts__, {"test": True}): actual_ret = win_iis.container_setting( name=name, container=container, settings=settings ) assert expected_ret == actual_ret def test_con...
wwitzel3/awx
awx/main/migrations/_cleanup_deleted.py
Python
apache-2.0
3,184
0.001884
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. # Python import logging # Django from django.db import transaction from django.utils.dateparse import parse_datetime def cleanup_deleted(apps, schema_editor): logger = logging.getLogger('awx.main.migrations.cleanup_deleted') def cleanup_model(model):...
name_field = 'name' name_prefix = '_deleted_' active_field = None n_deleted_items = 0 for field in model._meta.fields: if field.name in ('is_active', 'active'): active_field = field.name
if field.name == 'is_active': # is User model name_field = 'username' name_prefix = '_d_' if not active_field: logger.warning('skipping model %s, no active field', model) return n_deleted_items qs = model.objects.filter(**{ ...
vdods/heisenberg
heisenberg/plot/__main__.py
Python
mit
4,283
0.004203
import ast import heisenberg.library.heisenberg_dynamics_context import heisenberg.library.orbit_plot import heisenberg.option_parser import heisenberg.plot import heisenberg.util import matplotlib import numpy as np import sys # https://github.com/matplotlib/matplotlib/issues/5907 says this should fix "Exceeded cell ...
image is not None: try: options.initial_preimage = np.array(ast.literal_eval(options.init
ial_preimage)) expected_shape = (options.embedding_dimension,) if options.initial_preimage.shape != expected_shape: raise ValueError('--initial-preimage value had the wrong number of components (got {0} but expected {1}).'.format(options.initial_preimage.shape, expected_shape)) optio...
kevthehermit/mollusc
web/templatetags/customtags.py
Python
gpl-3.0
545
0.00367
from django import template from web.common import parse_config config = parse_config() register = template.Library()
# Lets me call dict values with spaces and hypens from a django template @register.filter def get(mapping, key): return mapping.get(key, '') @register.filter def theme(mapping, key): if 'style' in config: style_elements = config['style'] else: # Backwards compat style_elements = {'...
Shouqun/node-gn
tools/depot_tools/recipes/recipe_modules/git/examples/full.py
Python
mit
5,612
0.009622
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'git', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/raw_io', 'r...
code=1)) yield ( api.test('count-objects_with_bad_output') + api.step_data( 'count-objects', stdout=api.raw_io.output(api.git.count_objects_output('xxx')))) yield ( api.test('count-objects_with_bad_output_fails_build') + api.step_data(
'count-objects', stdout=api.raw_io.output(api.git.count_objects_output('xxx'))) + api.properties(count_objects_can_fail_build=True)) yield ( api.test('cat-file_test') + api.step_data('git cat-file abcdef12345:TestFile', stdout=api.raw_io.output('TestOutput')) + ...
infinity0n3/fabtotum-experiments
gcodeservice.py
Python
gpl-3.0
149
0
#!/bin/env python # -*-
coding: utf-8; -*- from fabtotum.utils.pyro.gcod
eservice import GCodeServiceServer gcss = GCodeServiceServer() gcss.loop()
demisto/content
Packs/SMIME_Messaging/Integrations/SMIME_Messaging/SMIME_Messaging_test.py
Python
mit
3,174
0.00445
import pytest from SMIME_Messaging import Client, sign_email, encrypt_email_body, verify, decrypt_email_body, sign_and_encrypt,\ decode_str import demistomock as demisto with open('./test_data/signer_key.pem') as f: private_key = f.read() with open('./test_data/signer.pem') as file_: public_key = file_.r...
ta/signed.p7'}) v, _ = verify(client, {}) assert 'a sign of our times' in v def test_encrypt(mocker): mocker.patch.object(demisto, 'args', return_value={'message': 'testing message'}) encrypt, _ = encrypt_email_body(client, {}) assert 'MIME-Version: 1.0\nContent-Disposition: attachment; filename...
name="smime.p7m"\n' \ 'Content-Transfer-Encoding: base64' in encrypt def test_decrypt(mocker): mocker.patch.object(demisto, 'getFilePath', return_value={'path': './test_data/encrypt.p7'}) decrypted, _ = decrypt_email_body(client, {}) assert 'Hello world' in decrypted def test_sign_and_encryp...
hnakamur/django-rest-framework-json-api
rest_framework_json_api/serializers.py
Python
bsd-2-clause
3,036
0.003953
from django.utils.translation import ugettext_lazy as _ from rest_framework.serializers import * from rest_framework_json_api.utils import format_relation_name, get_resource_type_from_instance, \ get_resource_type_from_serializer class ResourceIdentifierObjectSerializer(BaseSerializer): default_error_message...
pk = data['id'] try: return self.model_class.objects.get(pk=pk) except ObjectDoesNotExist: self.fail('does_not_exist', pk_value=pk) except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data['pk']).__name__) class SparseFieldsetsMixin(...
') if context else None if request: sparse_fieldset_query_param = 'fields[{}]'.format(get_resource_type_from_serializer(self)) try: param_name = next(key for key in request.query_params if sparse_fieldset_query_param in key) except StopIteration: ...
ebmdatalab/openprescribing
openprescribing/matrixstore/tests/test_serializer.py
Python
mit
1,843
0
import sqlite3 import numpy import scipy.sparse from django.test import SimpleTestCase from matrixstore.serializer import serialize, serialize_compressed, deserialize class TestSerializer(SimpleTestCase): def test_simple_serialisation(self): obj = {"hello": 123} self.assertEqual(deserialize(ser...
matrix((5, 4)) new_obj = deserialize(serialize(obj)) self.assertTrue(numpy.array_equal(obj.todense(), new_obj.todense())) def test_dtype_is_preserved(self): obj = scipy.sparse.csc_matrix((5, 4), dtype=numpy.uint16) new_obj = deserialize(serialize(obj)) self.assertEqual(ob
j.dtype, new_obj.dtype) def test_sqlite_roundtrip(self): obj = {"hello": 123} data = serialize(obj) new_data = roundtrip_through_sqlite(data) new_obj = deserialize(new_data) self.assertEqual(new_obj, obj) def test_sqlite_roundtrip_with_compression(self): obj = {...
indautgrp/frappe
frappe/core/page/data_import_tool/exporter.py
Python
mit
8,270
0.030713
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, json from frappe import _ import frappe.permissions import re from frappe.utils.csvutils import UnicodeWriter from frappe.utils import cstr, formatdate, format_dat...
= [doctype]; if len(doctype) > 1: docs_to_export = doctype[1] doctype = doctype[0] if not parent_doctyp
e: parent_doctype = doctype column_start_end = {} if all_doctypes: doctype_parentfield = {} child_doctypes = [] for df in frappe.get_meta(doctype).get_table_fields(): child_doctypes.append(df.options) doctype_parentfield[df.options] = df.fieldname def get_data_keys_definition(): return get_data_ke...
jonathanwoodard/MLSP_2013
2b_data_preparation_logarithm.py
Python
mit
7,483
0.01176
import numpy as np import pandas as pd import scipy as sp import pickle from scipy import fft from time import localtime, strftime import matplotlib.pyplot as plt from skimage.feature import match_template import wave ########################### # Folder Name Setting ########################### folder = 'J:/DATAMIN...
len(LOG_SPEC_SEGMENTS)): y_min = LOG_SPEC_SEGMENTS[s][2][0] y_max = LOG_SPEC_SEGMENTS[s][2][1] segment = LOG_SPEC_SEGMENTS[s][3] if(y_min > 5): y_min_5 = y_min-5 else: y_min_5 = 0 if(y_max < 194): ...
gauss[y_min_5:y_max_5+1,:] result = match_template(spectrogram_part, segment) Log_Segment_Row.append(np.max(result)) TRAIN_LOG_SPEC_FEATURES.append(Log_Segment_Row) TRAIN_LOG_SPEC_FEATURES = np.array(TRAIN_LOG_SPEC_FEATURES) # SAVE THE LOG-FEATURES for the TRAININ...
zhumengyuan/kallithea
kallithea/lib/dbmigrate/versions/031_version_2_2_3.py
Python
gpl-3.0
977
0
import logging from sqlalchemy import * from kallithea.lib.dbmigrate.migrate import * from kallithea.lib.dbmigrate.migrate.changeset import * from kallithea.model import meta from kallithea.lib.dbmigrate.versions import _reset_base, notify log = logging.getLogger(__name__) def upgrade(migrate_engine): """ ...
engine; bind migrate_engine to your metadata """ _reset_base(migrate_engine) from kallithea.lib.dbmigrate.schema imp
ort db_2_2_3 # issue fixups fixups(db_2_2_3, meta.Session) def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine def fixups(models, _SESSION): notify('Creating repository states') for repo in models.Repository.get_all(): _state = models.Repository.STATE_CREATED...
mazayus/ProjectEuler
problem016.py
Python
mit
59
0
#!/u
sr/bin/env python3 print(sum(map(int, str(2**1000)))
)
pelucid/salesforce_bulk
salesforce_bulk/csv_adapter.py
Python
mit
914
0.00547
import csv from cStringIO import StringIO class CsvDictsAdapter(object): """Provide a DataChange generator and it provides a file-like object which returns csv data""" def __init__(self, source_generator): self.source = source_generator sel
f.buffer = StringIO() self.csv = None self.add_header = False def __iter__(self): return self def write_header(self): self.add_header = True def next(self): row = self.source.next() self.buffer.truncate(0) self.buffer.seek(0) if not self.c...
add_header: self.csv.writeheader() self.add_header = False self.csv.writerow(row) self.buffer.seek(0) return self.buffer.read()
Ditmar/plugin.video.pelisalacarta
pelisalacarta/channels/hdfull.py
Python
gpl-3.0
21,752
0.014127
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para hdfull # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os, sys from core impor...
/hdfull.tv/peliculas-estreno", folder=True)) itemlist.append( Item(channel=__channel__, action="peliculas" , title="Últimas películas actualizadas" , url="http://hdfull.tv/peliculas-actualizadas", folder=True)) itemlist.append( Item(channel=__channel__, action="generos" , title="Últimas películas por género" , ...
logger.info("pelisalacarta.channels.hdfull menuseries") itemlist = [] itemlist.append( Item(channel=__channel__, action="novedades_episodios" , title="Últimos episodios emitidos" , url="http://hdfull.tv/ultimos-episodios", folder=True)) itemlist.append( Item(channel=__channel__, action="novedades_episodi...
MartinHjelmare/home-assistant
homeassistant/components/qrcode/image_processing.py
Python
apache-2.0
1,716
0
"""Support for the QR image processing.""" from homeassistant.core import split_entity_id from homeassistant.components.image_processing import ( ImageProcessingEntity, CONF_SOURCE, CONF_ENTITY_ID, CONF_NAME) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the demo image process...
y def state(self): """Return the state of the entity.""" return self._state
@property def name(self): """Return the name of the entity.""" return self._name def process_image(self, image): """Process image.""" import io from pyzbar import pyzbar from PIL import Image stream = io.BytesIO(image) img = Image.open(stream)...
jamespcole/home-assistant
homeassistant/bootstrap.py
Python
apache-2.0
14,932
0
"""Provide methods to bootstrap a Home Assistant instance.""" import asyncio import logging import logging.handlers import os import sys from time import time from collections import OrderedDict from typing import Any, Optional, Dict, Set import voluptuous as vol from homeassistant import core, config as conf_util, c...
sistant core failed to initialize. " "Further initialization aborted") return hass await persistent_notification.async_setup(hass, config) _LOGGER.info("Home Assistant core initialized") # stage 0, load logging components for component in components: if component...
in LOGGING_COMPONENT: hass.async_create_task( async_setup_component(hass, component, config)) await hass.async_block_till_done() # Kick off loading the registries. They don't need to be awaited. asyncio.gather( hass.helpers.device_registry.async_get_registry(), ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/Properties/from_thesis/HMM2_then2_IsolatedLHS.py
Python
mit
2,493
0.01083
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HMM2_then2_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HMM2_then2_IsolatedLHS. """ # Flag this instanc...
self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'MM2_then2') # Set the node attributes # Add the attribute equations self["equations"] = [] def constraint(self, PreNode, graph...
and returns the node corresponding to that label. """ #=============================================================================== # This code is executed after the nodes in the LHS have been matched. # You can access a matched node labell...
GNOME/orca
test/keystrokes/firefox/line_nav_iframes_in_inline_block.py
Python
lgpl-2.1
1,242
0.000805
#!/usr/bin/python """Test of line navigation output of Firefox.""" from macaroon.playback import * import utils sequence = MacroSequence() #sequence.append(WaitForDocLoad()) sequence.append(PauseAction(5000)) # Work around some new quirk in Gecko that causes this test to fail if # run via the test harness rather t...
1", "SPEECH OUTPUT: 'Line 1'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "2. Line Down", ["BRAILLE LINE: 'Line 3'", " VISIBLE: 'Line 3', cursor=1", "SPEECH OUTPUT: 'Line 3'"])) sequence.append(ut...
e 1', cursor=1", "SPEECH OUTPUT: 'Line 1'"])) sequence.append(utils.AssertionSummaryAction()) sequence.start()
undertherain/benchmarker
benchmarker/kernels/batchmatmul/data.py
Python
mpl-2.0
448
0.002232
import torch d
ef get_data(params): batch_size = params["batch_size"] M, N, K = params["problem"]["size"] flop = (2.0 * M * N * K) params["problem"]["flop_estimated"] = flop * params["nb_epoch"] * batch_size m = params["problem"]["size"][0] n = params["problem"]["size"][1] k = params["problem"]["size"][2] ...
muchu1983/104_cameo
test/unit/test_parserForINSIDE.py
Python
bsd-3-clause
1,532
0.006207
# -*- coding: utf-8 -*- """ Copyright (C) 2015, MuChu Hsu Contributed by Muchu Hsu
(muchu1983@gmail.com) This file is part of BSD license <https://o
pensource.org/licenses/BSD-3-Clause> """ import unittest import logging import json from cameo.parserForINSIDE import ParserForINSIDE """ 測試 解析 硬塞的 頁面 """ class ParserForINSIDETest(unittest.TestCase): #準備 def setUp(self): logging.basicConfig(level=logging.INFO) pass #收尾 def tea...
nunoplopes/alive
codegen.py
Python
apache-2.0
6,406
0.016235
# Copyright 2014-2015 The Alive authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
permissions and # limitations under the License. from pretty import * from collections import defaultdict from functools import reduce class CFragment(object): 'Common superclass for C statements and expressions.' INDENT=2 class CTest(CFragment): def __init__(self, string): self.s = string d
ef format(self): return text(self.s + ';') def formatExpr(self, prec): return text(self.s) class CType(CFragment): pass class CPtrType(CType): def __init__(self, pointee): self.pointee = pointee def __str__(self): return str(self.pointee) + '*' def __repr__(self): return 'CPtrType({0....
robhowley/nextbeeronme
src/db/brewers.py
Python
apache-2.0
753
0.023904
from tableacc import TableAcc clas
s Brewers(TableAcc): def __init__(self): super(Brewers, self).__init__( table_name='brewers', cols=['id', 'name', 'location_id'], upsert_proc='brewerupsert') def bylocation_id(self, location_id, order_by=""): return self._select( cols=["id", "name"], where="locat
ion_id = %s", order_by=order_by, param=[location_id] ) def has_recommended_beers_by_loc(self, location_id, order_by=""): return self._view(view_name='brewerswithrecs', where="location_id = %s", order_by=order_by, param=[location_id]) if __name__ == "__main__": ...
K3D-tools/K3D-jupyter
docs/source/k3d_directives/plot.py
Python
mit
1,492
0.002011
from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective from docutils import nodes import os import importlib.util class K3D_Plot(SphinxDirective): """ Sphinx class for execute_code directive """ has_content = False required_arguments = 0 optional_arguments = 2...
2path(self.env.docname) code_path = os.path.join(
os.path.dirname(path), filename) if 'screenshot' in self.options: image_filepath = os.path.join(os.path.dirname(path), os.path.splitext(os.path.basename(filename))[0] + '.png') if os.path.isfile(image_filepath): return [] ...
jessicalucci/TaskManagement
taskflow/tests/unit/test_distributed_translator.py
Python
apache-2.0
3,987
0
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2013 Rackspace, 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 # #...
engine.client._listeners actual = set([]) for listeners in dict_listeners.values(): for listener in listeners: actual.add(listener[1].flow_task) self.assertEquals(actual, set([two, three])) def test_multiple_root_translate(self): wf =
graph_flow.Flow("mult-root") one = self.someTask() two = self.someTask() three = self.someOtherTask() wf.add(one, two, three) wf.link(one, three) wf.link(two, three) backend = impl_memory.MemoryBackend({}) lb = logbook.LogBook("my-log-book") fd ...
hgascon/pulsar
pulsar/core/sippy/UasStateIdle.py
Python
bsd-3-clause
5,074
0.007489
# Copyright (c)
2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by ...
(at your option) any later version. # # For a license to use the SIPPY software under conditions # other than those described here, or to purchase support for this # software, please contact Sippy Software, Inc. by e-mail at the # following addresses: sales@sippysoft.com. # # SIPPY is distributed in the hope that it w...
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_codeop.py
Python
epl-1.0
8,298
0.007351
""" Test cases for codeop.py Nick Mathewson """ import unittest from test.test_support import run_unittest, is_jython from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT if is_jython: import sys import cStringIO def unify_callables(d): for n,v in d.items(): if callable(v)...
ry: compile_command(str,symbol=symbol) self.fail("No exception thrown for invalid code") except SyntaxError: self.assertTrue(is_syntax) except OverflowError: self.assertTrue(not is_syntax) def test_valid(self): av = self.assertValid #...
", "<input>", 'single', PyCF_DONT_IMPLY_DEDENT)) self.assertEquals(compile_command("\n"), compile("pass", "<input>", 'single', PyCF_DONT_IMPLY_DEDENT)) else: av("") av("\n") ...
googleprojectzero/domato
generator.py
Python
apache-2.0
7,760
0.003093
# Domato - main generator script # -------------------------------------- # # Written and maintained by Ivan Fratric <ifratric@google.com> # # Copyright 2017 Google Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance wi...
nsamples)) if not os.path.exists(out_dir): os.mkdir(out_dir) outfiles = []
for i in range(nsamples): outfiles.append(os.path.join(out_dir, 'fuzz-' + str(i).zfill(5) + '.html')) generate_samples(template, outfiles) else: parser.print_help() if __name__ == '__main__': main()
pprett/statsmodels
statsmodels/datasets/strikes/data.py
Python
bsd-3-clause
1,924
0.007796
#! /usr/bin/env python """U.S. Strike Duration Data""" __docformat__ = 'restructuredtext' COPYRIGHT = """This is public domain.""" TITLE = __doc__ SOURCE = """ This is a subset of the data used in Kennan (1985). It was originally published by the Bureau of Labor Statistics. :: Kennan, J. 1985. "The...
le name definitions:: duration - duration of the strike in days iprod - unanticipated industrial production """ from numpy import recfromtxt, column_stack, array import statsmodels.tools.datautils as du from os.path import dirname, abspath def load(): """ Load the strikes data and ret...
turn du.process_recarray(data, endog_idx=0, dtype=float) def load_pandas(): """ Load the strikes data and return a Dataset class instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray_pandas(d...
keishi/chromium
ppapi/native_client/src/shared/ppapi_proxy/run_srpcgen.py
Python
bsd-3-clause
7,278
0.007832
#!/usr/bin/env python # Copyright (c) 2012 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. """Driver of srpcgen for ppapi_proxy sources. This must be run after modifying, adding, or removing .srpc files. The lists of .srp...
# file_basename Prefix of the output file names, suffixed # by .h, _server.cc, _client.cc. # srpc_files List of .srpc input file names. # client_thread_check (optional) True if the client side should # be generated ...
This asserts that calls are on the main thread. all_units = [ {'trusted_is_client': True, 'name': 'PppRpcs', 'file_basename': 'ppp_rpc', 'srpc_files': [ 'completion_callback.srpc', 'ppp.srpc', 'ppp_audio.srpc', 'ppp_find.srpc', 'ppp_inpu...
Theyrealone/ExcelMapper
run.py
Python
gpl-3.0
2,567
0.034671
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'rew...
l_rules=col_rules_sheet2_t3) t3_output_data = t3_excel_mapper.run(excel_data) workbook = xlsxwriter.Workbook('output {}.xlsx'.format(date)) worksheet = workbook.add_worksheet() for (row,col),results in t1_output_data.iteritems(): worksheet.write(row, col,len(results)) for (row,col),results in t2_output_...
a.iteritems(): worksheet.write(row, col,len(results)) workbook.close() print "Done." def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__...
jvrsantacruz/XlsxWriter
xlsxwriter/test/styles/test_write_cell_xfs.py
Python
bsd-2-clause
970
0.002062
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...styles import Styles from
...format import Format class TestWriteCellXfs(unittest.TestCase): """ Test the Styles _write_cell_xfs() method. """ def setU
p(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_cell_xfs(self): """Test the _write_cell_xfs() method""" xf_format = Format() xf_format.has_font = 1 self.styles._set_style_properties([[xf_format], None...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/ubuntuone-client/ubuntuone/platform/windows/ipc.py
Python
gpl-3.0
86
0.023256
../../../../../..
/../share/pyshared/ubuntuone-client/ubuntuone/platform/windows/ipc.py
joshzarrabi/e-mission-server
bin/delete_test_user_sections.py
Python
bsd-3-clause
428
0.002336
# Delete entries for the dummy user # This needs to be done every time we switch to a new database from pymongo import MongoClient from get_database import get_section_db from uuid import UUID # Users=get_user_db() fakeUserUUIDQuery = {'user_id': UUID('{951779de-a10c-3373-b186-c1c9b14b5e38}')} p
rint "About to delete %s sections" % get_section_db().find(fakeUserUUIDQuery).count() get_section_db().remove(fak
eUserUUIDQuery)
kizyle502/collegiatemasters
config/settings/local.py
Python
bsd-3-clause
2,176
0.00046
# -*- coding: utf-8 -*- ''' Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app ''' from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bool('DJANGO_DEBUG', default...
k5@&') # Mail settings # ------------------------------------------------------------------------------ EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend') # C
ACHING # ------------------------------------------------------------------------------ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } # django-debug-toolbar # ------------------------------------------------------------------------------ ...
B3AU/micropython
robocam/main.py
Python
lgpl-3.0
452
0.015487
__author__ = 'beau' import serial ser = serial.
Serial('/dev/tty.usbmodem1422',9600, timeout=1) import time import sys def get_angle(): print "requesting angle" start = time.time() ser.write('nofddfp\n') print "..." reply = ser.readline() deltaT = time.time()-start print reply print "round-trip time {}".format(de
ltaT) sys.stdout.flush() while True: get_angle() print "-------------" #time.sleep(0.1)
bdh1011/wau
venv/lib/python2.7/site-packages/pandas/io/common.py
Python
mit
4,935
0.000811
"""Common IO api utilities""" import sys import os import zipfile from contextlib import contextmanager, closing from pandas.compat import StringIO, string_types, BytesIO from pandas import compat if compat.PY3: from urllib.request import urlopen, pathname2url _urlopen = urlopen from urllib.parse import...
Parameters ---------- reader : a streamable file
-like object encoding : optional, the encoding to attempt to read Returns ------- a tuple of (a stream of decoded bytes, the encoding which was used) """ if compat.PY3 or encoding is not None: # pragma: no cover if encoding: errors = 'strict' else:...
collective/eden
modules/s3/s3translate.py
Python
mit
64,871
0.001434
# -*- coding: utf-8 -*- """ Translation API @copyright: 2012-14 (c) Sahana Software Foundation @license: MIT 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 restr...
trings belonging to more than one module are grouped under the "special" key. """ # Initialize to an empty list for each module d = {} modlist = self.get_module_list(current.request.folder) for m in modlist:
d[m] = [] # List of files belonging to 'core' module d["core"] = [] # 'special' files which contain strings from more than one module d["special"] = [] self.d = d self.modlist = modlist # Directories which are not re...
gjhiggins/pyralod
pyralod/__init__.py
Python
apache-2.0
3,712
0.001078
import os from pyramid.config import Configurator from pyramid.session import UnencryptedCookieSessionFactoryConfig import rdflib from .lib import ( bookdb, LABEL_PROPERTIES, detect_types, reverse_types, find_resources, reverse_resources, ) from .lib.htmlresults import term_to_string __vers...
bel}') config.add_rou
te('pick', '/pick/{uri:.*}') config.add_route('picked_format', '/picked/{action}/{format_}') config.add_route('picked_action', '/picked/{action}/') config.add_route('picked_index', '/picked/') config.add_subscriber('pyralod.subscribers.handle_setup', 'pyramid.events.NewRequest'...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/fs/contrib/tahoelafs/test_tahoelafs.py
Python
agpl-3.0
1,455
0.006873
#!/usr/bin/python """ Test the TahoeLAFS @author: Marek Palatinus <marek@palatinus.cz> """ import sys import logging import unittest from fs.base import FS import fs.errors as errors from fs.tests import FSTestCases, ThreadingTestCases from fs.contrib.tahoelafs import TahoeLAFS, Connection ...
ys.stdout)) WEBAPI = 'http://insecure.tahoe-lafs.org' # The public grid is too slow for threading testcases, disabling for now... class TestTahoeLAFS(unittest.TestCase,FSTestCases):#,ThreadingTestCases): # Disabled by default because it takes a *really* long time. __test__ = False def setU...
AFS.createdircap(WEBAPI) self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI) def tearDown(self): self.fs.close() def test_dircap(self): # Is dircap in correct format? self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap...