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
internap/arsenal
releasenotes/source/conf.py
Python
apache-2.0
8,940
0
# -*- coding: utf-8 -*- # 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...
. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index i
s generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'glancereleasenotes', u'Glance Release Notes Documentation'...
MissionCriticalCloud/marvin
marvin/cloudstackAPI/listIpForwardingRules.py
Python
apache-2.0
4,977
0.001005
"""List the IP forwarding rules""" from baseCmd import * from baseResponse import * class listIpForwardingRulesCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "false" """list resources by account. Must be used with the domainId parameter.""" self.account = None ...
the tag""" self.domainid = None """"tag key name""" self.key = None """"the project name where tag belongs to""" self.project = None """"the project id the tag belongs to""" self.pro
jectid = None """"id of the resource""" self.resourceid = None """"resource type""" self.resourcetype = None """"tag value""" self.value = None
sergejx/kaleidoscope
tests/test_generator.py
Python
bsd-3-clause
6,135
0.000326
import os from datetime import date from unittest.mock import MagicMock, call import pytest import imagesize from kaleidoscope import renderer, generator from kaleidoscope.model import Gallery, Album, Section, Photo from kaleidoscope.generator import generate, DefaultListener def test_generate_gallery_index(tmpdir,...
_photos, tmpdir, listener)
album = gallery_with_three_photos.albums[0] assert listener.starting_album.call_args == call(album, 3) assert listener.finishing_album.called assert listener.resizing_photo.call_count == 3 def test_counting_photos_to_resize( gallery_with_three_photos, tmpdir, disable_resize): """Listener sh...
rohitdatta/pepper
pepper/routes.py
Python
agpl-3.0
7,316
0.007791
import announcements, users, corporate, api, volunteer, teams, innovation def configure_routes(app): app.add_url_rule('/', 'landing', view_func=users.views.landing, methods=['GET']) # Signing Up/Registration app.add_url_rule('/register', 'sign-up', view_func=users.views.sign_up, methods=['GET', 'POST']) ...
ouncement', view_func=announcements.views.create_announcement, methods=['POST']) app.add_url_rule('/api/partners', 'partners', view_func=api.views.partner_list,
methods=['GET']) app.add_url_rule('/api/schedule', 'schedule', view_func=api.views.schedule, methods=['GET']) app.add_url_rule('/api/schedule/<day>', 'day-schedule', view_func=api.views.schedule_day, methods=['GET']) app.add_url_rule('/api/check-in', 'check-in-api', view_func=api.views.check_in, methods=['...
peeyush-tm/shinken
modules/ws-nocout/module.py
Python
agpl-3.0
15,057
0.030152
#!/usr/bin/env python """This Class is an Arbiter module for having a webservice throuhg which we can have `sync` and `live polling` functionalities """ import json import os import select import subprocess import sys import tarfile import time from shinken.basemodule import BaseModule from shinken.external_comman...
fixed,
trigger_id, duration, author, comment ) else: # SCHEDULE_HOST_DOWNTIME;<host_name>;<start_time>;<end_time>;<fixed>;<trigger_id>;<duration>;<author>;<comment> command = '[%s] SCHEDULE_HOST_DOWNTIME;%s;%s;%...
mfsteen/CIQTranslate-Kristian
openpyxl/utils/datetime.py
Python
gpl-3.0
3,155
0.00412
from __future__ import absolute_import from __future__ import division # Copyright (c) 2010-2016 openpyxl """Manage Excel date weirdness.""" # Python stdlib imports import datetime from datetime import timedelta, tzinfo import re from jdcal import ( gcal2jd, jd2gcal, MJD_0 ) from openpyxl.compat import ...
{2}):(\d{2})(.(\d{2}))?Z?') def datetime_to_W3CDTF(dt): """Convert from a datetime to a timestamp string.""" return datetime.datetime.strftime(dt, W3CDTF_FORMAT) def W3CDTF_to_datetime(formatted_string): """Convert from a timestamp string to a datetime object.""" match = W3CDTF_REGEX.match(formatted...
al2jd(dt.year, dt.month, dt.day)) - offset if jul <= 60 and offset == CALENDAR_WINDOWS_1900: jul -= 1 if hasattr(dt, 'time'): jul += time_to_days(dt) return jul @lru_cache() def from_excel(value, offset=CALENDAR_WINDOWS_1900): if value is None: return if 1 < value < 60 and ...
HailStorm32/Q.bo_stacks
qbo_webi/src/voiceRecognition/voiceRecognition.py
Python
lgpl-2.1
10,125
0.01541
#!/usr/bin/env python2.6 # -*- coding: utf-8 -*- #!/usr/bin/env python # # Software License Agreement (GPLv2 License) # # Copyright (c) 2012 TheCorpora SL # # 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...
break return self.htmlTemplate.render(language=self.language,lannames=self.languages_names,alllanguage=self.getLanguages()) else: return "Qbo listen not installed" # return self.htmlTemplate.render(language=self.language) @cherrypy.expose def rec(sel...
#Borramos la anterior grabacion, si la habia try: cmd="rm "+self.path+"tmp/*" self.p = Popen(cmd.split()) except ValueError: print "Nada que borrar" ''' try: cmd="rm "+self.path+"/*_en" self.p = Popen(cmd.split())...
romain-dartigues/ansible-modules-core
system/hostname.py
Python
gpl-3.0
20,763
0.003516
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Hiroaki Nakamura <hnakamur@gmail.com> # # This file is part of Ansible # # Ansible 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...
try: open(self.HO
STNAME_FILE, "a").write("") except IOError: err = get_exception() self.module.fail_json(msg="failed to write file: %s" % str(err)) try: f = open(self.HOSTNAME_FILE) try: return f.read().strip() fi...
strogonoff/django-dbmessages
setup.py
Python
apache-2.0
1,218
0.001642
#coding: utf-8 import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # Allow setup.
py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup(
name='django-dbmessages', version='0.2.0a', packages=['dbmessages'], include_package_data=True, license='BSD License', description='Request-independent messaging for Django on top of contrib.messages', long_description=README, author='Upwork, Anton Strogonoff', author_email='python@upw...
willre/homework
day19/web/app01/forms/home.py
Python
gpl-2.0
723
0.027027
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: Will """ from django import forms from app01 import models class ImportFrom(forms.Form): HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 host_typ
e = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE) ) hostname = forms.CharField() def __init__(self,*args,**kwargs): super(ImportFrom,self).__init__(*args,**kwargs) HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 self.fields['host_type'].wid...
xycfree/py_spider
spider/down_pic_thread.py
Python
gpl-3.0
1,358
0.021021
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-09-01 22:26:01 # @Author : Your Name (you@example.org) # @Link : http://example.org # @Version : $Id$ import os import threading import requests import lxml from threading import Thread from bs4 import BeautifulSoup import sys reload(sys) sys.setdef...
: def __init__(self, url, img, filename): super(Worker, self).__init__() self.url = url self.img = img self.filename = filename def run(self): try: u = self.url + self.img r = requests.get(u, stream=True) with open(self.filename, 'wb') as fd: for chunk in r.iter_content(4096): fd.write(ch...
= requests.get(url, stream=True) soup = BeautifulSoup(r.text, 'lxml') myimg = [img.get('src') for img in soup.find(id='brand-waterfall').find_all('img')] # 查询id下所有img元素 print 'myimg:', myimg for img in myimg: pic_name = pic_path + str(t) + '.jpg' # img_src = img.get('src') print 'img: ', img # self.downloa...
trachelr/mne-python
tutorials/plot_cluster_stats_spatio_temporal_2samp.py
Python
bsd-3-clause
4,321
0
""" .. _tut_stats_cluster_source_2samp: ========================================================================= 2 samples permutation test on source data with spatio-temporal clustering ========================================================================= Tests if the source space data are significantly differe...
_path + '/MEG/sample/sample_audvis-meg-lh.stc' subjects_dir = data_path + '/subjects' # Load stc to in common cortical space (fsaverage) stc = mne.read_source_estimate(stc_fname) stc.resample(50) stc = mne.morph_data('sample', 'fsaverage', stc, grade=5, smooth=20, subjects_dir=subjects_dir) n_ver...
r %d and %d subjects.' % (n_subjects1, n_subjects2)) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X1 = np.random.randn(n_vertices_fsave, n_times, n_subjects1) * 10 X2 = np.random.randn(n_vertices_fsave, n_times, n_subjects2) * 10 X1[:, :, :] += stc.data[:, :, np.newaxis] # make the ac...
teoreteetik/api-snippets
ip-messaging/rest/messages/list-messages/list-messages.5.x.py
Python
mit
533
0
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest.ip_messaging import TwilioIpMessagingClient # Your Account Sid and Auth Token from twilio.com/user/account account =
"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" token = "your_auth_token" client = TwilioIpMessagingClient(account, token) service = client.services.get(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") channel = service.channels.get(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") messages = channel.messages.list() for m
in messages: print(m)
tommyip/zulip
tools/lib/test_script.py
Python
apache-2.0
2,710
0.002583
from typing import Optional, Tuple import os import sys from distutils.version import LooseVersion from version import PROVISION_VERSION from scripts.lib.zulip_tools import get_dev_uuid_var_path def get_major_version(v): # type: (str) -> int return int(v.split('.')[0]) def get_version_file(): # type: () ...
. ''' def preamble(version): # type: (str) -> str text = PREAMBLE % (version, PROVISION_VERSION) text += '\n' return text NEED_TO_DOWNGRADE = ''' It looks like you checked out a branch that expects an older version of dependencies than t
he version you provisioned last. This may be ok, but it's likely that you either want to rebase your branch on top of upstream/master or re-provision your VM. Do this: `./tools/provision` ''' NEED_TO_UPGRADE = ''' It looks like you checked out a branch that has added dependencies beyond what you last provisioned. You...
peacekeeper/indy-sdk
wrappers/python/tests/crypto/test_auth_crypt.py
Python
apache-2.0
1,227
0.005705
import json import pytest from indy import crypto, did, error @pytest.mark.asyncio async def test_auth_crypt_works_for_created_key(wallet_handle, seed_my1, verkey_my2, message): verkey = await did.create_key(wallet_handle, json.dumps({'seed': seed_my1})) await crypto.auth_crypt(wallet_handle, verkey, verkey...
le, verkey_my1, verkey_my2, message): with pytest.raises(error.WalletInvalidHandle): invalid_wallet_handle = wallet_handle + 1 await crypto.auth_crypt(invalid_wallet_handle, verkey_my1, verkey_my2, message) @pytest.mark.asy
ncio async def test_auth_crypt_works_for_invalid_recipient_vk(wallet_handle, identity_trustee1, message): (_, key) = identity_trustee1 with pytest.raises(error.CommonInvalidStructure): await crypto.auth_crypt(wallet_handle, key, 'CnEDk___MnmiHXEV1WFgbV___eYnPqs___TdcZaNhFVW', message)
jaromrax/myservice
version2/mysglobal.py
Python
gpl-2.0
4,226
0.014908
#!/usr/bin/python3 ############# # this is to be leaded by every module. # I think #import mysglobal as g # args,loggerr @every module ################# import logging from logzero import setup_logger,LogFormatter,colors import argparse import os,sys import json from blessings import Terminal import getpass # ...
PATHS: when ~/.myservice/test/aaa myservice2 aaa enable : finds a path and adds into the .config.json myservice2 infinite ... runs the table in
the terminal (only 1 instance possible) OR connects to the screen -x myservice2_infinite """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-d','--debug', action='store_true' , help='') #parser.add_argument('-s','--serfmsg', default='',nargs="+" , help='serf message to...
StackStorm/mistral
mistral/tests/unit/lang/v2/base.py
Python
apache-2.0
3,920
0
# Copyright 2015 - StackStorm, 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 ...
is a test.', 'smtp_server': 'localhost', 'smtp_password': 'password' } } } def _parse_dsl_spec(self, dsl_file=None, add_tasks=False, cha
nges=None, expect_error=False): if dsl_file and add_tasks: raise Exception('The add_tasks option is not a valid ' 'combination with the dsl_file option.') if dsl_file: dsl_yaml = base.get_resource(self._resource_path + '/' + dsl_file) if ...
utek/pydesktime
pydesktime/desktime.py
Python
mit
2,182
0.000917
import requests import datetime import calendar class DeskTime(object): MAIN_URL = 'https://desktime.com/api/2/json/?{params}' def __init__(self, app_key, username, password): self.api_key = self._login(app_key, username, password) if self.api_key is None: raise Excepti...
etime.datetime.now().date()): employees = 'apike
y={apikey}&action=employees&date={date}' employees = employees.format(apikey=self.api_key, action='employees', date=date.isoformat()) url = self.MAIN_URL.format(params=employees) res = requests.get(url) data = res.json() if not data.get(...
adamhaney/airflow
tests/contrib/operators/test_gcp_bigtable_operator.py
Python
apache-2.0
29,272
0.00164
# -*- coding: utf-8 -*- # # 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 #...
instance.return_value = None with self.assertRaises(AirflowException) as e: op = BigtableClusterUpdateOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, cluster_id=CLUSTER_ID, nodes=NODES, task_id="id" ...
ok.assert_called_once_with() mock_hook.return_value.update_cluster.assert_not_called() @mock.patch('airflow.contrib.operators.gcp_bigtable_operator.BigtableHook') def test_updating_cluster_but_instance_does_not_exists_empty_project_id(self, ...
agiovann/Constrained_NMF
caiman/source_extraction/cnmf/utilities.py
Python
gpl-2.0
40,754
0.001718
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A set of utilities, mostly for post-processing and visualization We put arrays on disk as raw bytes, extending along the first dimension. Alongside each array x we ensure the value x.dtype which stores the string description of the array's dtype. See Also: ----------...
mask = image == image_max if exclude_border: # zero out the imag
e borders for i in range(mask.ndim): mask = mask.swapaxes(0, i) remove = (footprint.shape[i] if footprint is not None else 2 * exclude_border) mask[:remove // 2] = mask[-remove // 2:] = False mask = mask.swapaxes(0, i) # find top peak ca...
jonathanverner/brython
www/speed/benchmarks/create_function_complex_args.py
Python
bsd-3-clause
71
0.014085
for i in range(1000000):
def f(x, y=1, *args, **kw):
pass
appuio/ansible-role-openshift-zabbix-monitoring
vendor/openshift-tools/ansible/roles/lib_gcloud/build/lib/gcpresource.py
Python
apache-2.0
683
0
# pylint: skip-file class GCPResource(object): '''Object to represent a gcp resour
ce''' def __init__(self, rname, rtype, project, z
one): '''constructor for gcp resource''' self._name = rname self._type = rtype self._project = project self._zone = zone @property def name(self): '''property for name''' return self._name @property def type(self): '''property for type'''...
lydonjake/cs-grad-school-app
program/__init__.py
Python
gpl-3.0
211
0.004739
__author__ =
"Jacob Lydon" __copyright__ =
"Copyright 2017" __credits__ = [] __license__ = "GPLv3" __version__ = "0.1" __maintainer__ = "Jacob Lydon" __email__ = "jlydon001@regis.edu" __status__ = "Development"
polysquare/polysquare-ci-scripts
ciscripts/check/python/__init__.py
Python
mit
190
0
# /ciscripts
/check/python/__init__.py # # Module loader file for /ciscripts/check/python. # # See /LICENCE.md for Copyright information """Module loader file for /ciscripts/check/p
ython."""
peter1010/my_vim
vimfiles/py_scripts/build_types/gcc.py
Python
gpl-2.0
1,180
0.036441
# Build Code import os import subprocess import re class GCC: def __init__(self): self.enter_match = re.compile(r'Entering directory') self.leave_match = re.compile(r'Leaving directory') def can_build(self, dirname, ext): if ext in (".c", ".h", ".cpp", ".hpp"): files = [f.lower() for f in os.listdir(dirn...
gs = ["make"] if action: args.append(action) print(args) proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) errorLines = [] while True: line = proc.stdout.readline().decode("utf-8") if len(line) == 0: break output.write(line) if line.startswith("In file include...
nd(line) else: idx = line.find("Leaving directory") if idx >= 0: errorLines.append(line) else: idx = line.find("warning:") if idx >= 0: errorLines.append(line) output.write(line) return errorLines def get_plugin(): return GCC()
jszokoli/jsTK
jsRenamer/field_replacer.py
Python
gpl-3.0
6,998
0.018148
import maya.cmds as cmds from . import renamer_settings as settings class FieldReplacer(object): def __init__(self): print 'Initializing jsRenamer FieldReplacer...' #replaceMaterial = self.replaceMaterial def checkTemplate(self,node): #availPos = ['C','L','R','LF','RF','LB','RB','U',...
wField',query = True,text=True) for each in replacerSel: if '|' in each: replacerOldName=each.split('|')[-1] else: replacerOldName = each replacerNewName = replacerOldName.replace(replacerOld,replacerNew) print replacerNewName ...
prefixAddition = cmds.textField('addPrefixField',query = True,text=True) for each in prefixSel: newPrefixName = prefixAddition+each print newPrefixName cmds.rename(each,newPrefixName) ###Suffix Add def addSuffix(self, args=None): suffixSel = cmds.ls(sl=...
joopert/home-assistant
homeassistant/components/cloud/http_api.py
Python
apache-2.0
19,172
0.000939
"""The HTTP api to control the cloud integration.""" import asyncio from functools import wraps import logging import aiohttp import async_timeout import attr from hass_nabucasa import Cloud, auth, thingtalk from hass_nabucasa.const import STATE_DISCONNECTED import voluptuous as vol from homeassistant.components impo...
st handler.""" try: result = await handler(view, request, *args, **kwargs) return
result except Exception as err: # pylint: disable=broad-except status, msg = _process_cloud_exception(err, request.path) return view.json_message( msg, status_code=status, message_code=err.__class__.__name__.lower() ) return error_handler def _ws_hand...
gcobos/rft
scripts/get_all_images.py
Python
agpl-3.0
207
0
import web db = web.database(dbn='mysql', d
b='googlemodules', user='ale', passwd='3babes') for url in db.select('function', what='screenshot'): print 'http://www.googlemodules.com/image/screensh
ot'
bnorthan/projects
Scripts/Jython/Psfs/PSFModel.py
Python
gpl-2.0
1,817
0.053935
class PSFModel(object): def __init__(self, scopeType, psfModel, xySpace, zSpace, emissionWavelength, numericalAperture, designImmersionOilRefractiveIndex, \ designSpecimenLayerRefractiveIndex, actualImmersionOilRefractiveIndex, \ actualSpecimenLayerRefractiveIndex, actualPointSourceDepthInSpecimenLayer, home...
veIndex self.actualSpecimenLayerRefractiveIndex=actualSpecimenLayerRefractiveIndex self.actualPointSourceDepthInSpecimen
Layer=actualPointSourceDepthInSpecimenLayer def CreatePsf(self, command, psfCommandName, xSize, ySize, zSize): module=command.run(psfCommandName, True, \ "xSize", xSize, \ "ySize", ySize, \ "zSize", zSize, \ "fftType", "none", \ "scopeType", self.scopeType, \ "psfModel", self.psfModel, \ "xySpace", se...
lqe/EconomyCompensation
code.py
Python
gpl-3.0
2,064
0.036126
# -*- coding:utf-8 -*- '''Created on 2014-8-7 @author: Administrator ''' from sys import path as sys_path if not '..' in sys_path:sys_path.append("..") #用于import上级目录的模块 import web #早起的把一个文件分成多个文件,再把class导入 from login.login import (index,login,loginCheck,In,reset,register,find_password) from blog.blog imp...
se模式下可用 可以用一下方式解决 生产中 一般设置web.config.debug = False web.config.debug = True if web.config.get('_session') is None: session = web.session.Session(app,web.session.DiskStore('sessions')) web.config._session=s
ession else: session=web.config._session #用以下方式可以解决多文件之间传递session的问题 def session_hook():web.ctx.session=session app.add_processor(web.loadhook(session_hook)) if __name__=='__main__': app.run()
foobarbazblarg/stayclean
stayclean-2015-january/display-on-last-day-before-participants-must-check-in.py
Python
mit
1,018
0.006876
#!/usr/bin/python import participantCollection participantCollection = participantCollection.ParticipantCollection() numberStillIn = participantCollection.sizeOfParticipantsWhoAreStillIn() initialNumber = participantCollection.size() print "There are currently **" + str(numberStillIn) + " out of " + str(initialNumber...
ber,0))) + "%**." print "These participants have checked in at least once in the last 15 days:" print "" for participant in participantCollection.participantsWhoAreStillInAndHaveCheckedIn(): print "/u/" + participant.name print "" print "These participants have not reported a relapse, so they are still in the ...
ticipant in participantCollection.participantsWhoAreStillInAndHaveNotCheckedIn(): print "/u/" + participant.name + " ~" print ""
smarkets/smk_python_sdk
smarkets/statsd.py
Python
mit
2,824
0.000354
from __future__ import absolute_import, division, print_function, unicode_literals # Statsd client. Loosely based on the version by Steve Ivy <steveivy@gmail.com> import logging import random import socket import time from contextlib import contextmanager log = logging.getLogger(__name__) class StatsD(object): ...
'__main__': sd = StatsD() for i in range(1, 100):
sd.increment('test')
jgrillo/zoonomia
zoonomia/_version.py
Python
mit
22
0
__versi
on__ = '
0.0.1'
transparenciahackday/dar-scripts
scripts/raspadar/txt2taggedtext.py
Python
gpl-3.0
23,048
0.008054
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import locale locale.setlocale(locale.LC_ALL, 'pt_PT.UTF8') import logging logging.basicConfig(level=logging.DEBUG) import os import string import datetime from pprint import pprint from html2text import add_item ### Constantes ### MP_STATEMENT = 'deputado_i...
]?[\–\–\—\-])', re.UNICODE), '') re_interv_semquebra = (re.compile(ur'(?P<titulo>O Sr\.?|A Sr(\.)?(ª)?)\ (?P<nome>[\w ,’-]{1,50})\ ?(?P<partido>\([\w -]+\))?(?P<sep>\:[ \.]?[\–\–\—\-] )', re.UNICODE), '') re_interv_simples = (re.compile(ur'^(?P<nome>[\w ,’-]+)\ ?(?P<partido>\([\w -]+\))?\ ?(?P<sep>\:?[ \.]?[\–\–\—\-]?...
stype, text = p.split(']', 1) text = text.strip() return '[%s] %s' % (newtype, text) def get_type(p): stype, text = p.split(']', 1) stype = stype.strip('[] ') return stype def get_speaker(p): stype, text = p.split(']', 1) text = text.strip() try: speaker, text = re.split(re...
irinabov/debian-qpid-dispatch
python/qpid_dispatch_internal/router/__init__.py
Python
apache-2.0
1,041
0
# # 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 use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache...
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__ ...
google/embedding-tests
thought/image_text_model.py
Python
apache-2.0
11,824
0.008373
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
ply(inputs, tf.expand_dims(masks, 2)) inputs = self.hidden(inputs) return self.transformer.forward(inputs, masks) class DAN(object): def __init__(self, num_units): self.hidden = tf.keras.layers.Dense(num_units, activation=tf.nn.relu) def forward(self, inputs, masks): masks = tf.cast(masks, tf.flo...
tf.multiply(inputs, tf.expand_dims(masks, 2)) inputs = tf.reduce_sum(inputs, 1) / tf.reduce_sum(masks, 1, keepdims=True) return self.hidden(inputs) def get_text_encoder(encoder_type='rnn'): if encoder_type == 'rnn': return RNN elif encoder_type == 'trans': return Transformer elif encoder_type =...
steakunderscore/Bandwidth-Monitoring
src/webInterface.py
Python
gpl-3.0
3,059
0.010134
''' Created on 11/02/2010 @author: henry@henryjenkins.name ''' class webInterface(object): ''' classdocs ''' writeFile = None def __init__(self): pass def __openFile(self, fileName): self.writeFile = open(fileName, 'w') def closeFile(self): self.w...
self.writeFile.write('</tr>') self.writeFile.write('</table>') self.writeFile.write('</BODY>\n') def writeFooter(self): self.writeFile.write('</HTML>\n') def humanizeNumber(self,number = 0): if number > 1024*1024*1024: number = number...
umber/(1024*1024) number = str(number) + ' MBytes' elif number > 1024: number = number/1024 number = str(number) + ' KBytes' else: number = str(number) + ' Bytes' return number def outputIndex(self,file,users = None): self.__op...
ddemidov/ev3dev-lang-python-1
ev3dev/auto.py
Python
mit
497
0.004024
import platform
# ----------------------------------------------------------------------------- # Guess platform we are running on def current_platform(): machine = platform.machine() if machine == 'armv5tejl': return 'ev3' elif machine == 'armv6l': return 'brickpi' else: return 'unsupported' ...
Import ev3 by default, so that it is covered by documentation. from .ev3 import *
vileopratama/vitech
src/openerp/cli/deploy.py
Python
mit
4,038
0.003219
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os import requests import sys import tempfile import zipfile from . import Command class Deploy(Command): """Deploy a module on an Odoo instance""" def __init__(self): super(Deploy, self).__init__() self.session = requests.se...
raise def run(self, cmdargs): parser = argparse.ArgumentParser( prog="%s deploy" % sys.argv[0].split(os.path.sep)[-1], description=self.__doc__ ) parser.add_argument('path', help="Path of the module to deploy") parser.add_argument('url', nargs='?', help=...
host:8069)', default="http://localhost:8069") parser.add_argument('--db', dest='db', help='Database to use if server does not use db-filter.') parser.add_argument('--login', dest='login', default="admin", help='Login (default=admin)') parser.add_argument('--password', dest='password', default="a...
suizokukan/urwid
urwid/html_fragment.py
Python
lgpl-2.1
8,175
0.005505
#!/usr/bin/python # # Urwid html fragment output wrapper for "screen shots" # Copyright (C) 2004-2007 Ian Ward # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # v...
a = (";text-decoration:underline" * aspec.underline + ";font-weight:bold" * aspec.bold) def html_span(fg, bg, s): if not s: return "" return ('<span style="color:%s;' 'background:%s%s">%s</span>' % (fg, bg, extra, html_escape(s))) if cursor >= 0: c_off, _...
c2_off = util.move_next_char(s, c_off, len(s)) return (html_span(html_fg, html_bg, s[:c_off]) + html_span(html_bg, html_fg, s[c_off:c2_off]) + html_span(html_fg, html_bg, s[c2_off:])) else: return html_span(html_fg, html_bg, s) def html_escape(text): """Escape text s...
popara/jonny-api
matching/admin.py
Python
mit
786
0.001272
from django.contrib import admin # from models import Agent, ReCa, Accomodation, Beach, Activity, Contact # # @admin.register(ReCa, Activity) # class VenueAdmin(admin.ModelAdmin): # list_display = ('name', 'internal_rating', 'ready', 'description',) # list_filter = ('ready', 'internal_rating',) # search_fields =...
n',) # list_filter = ('ready', 'stars',) # # # @admin.register(Beach) # class BeachAdmin(admin.ModelAdmin): # list_display = ('name', 'type
', 'description',) # list_filter = ('name',) # # # admin.site.register(Agent) # admin.site.register(Contact) # #
samvarankashyap/googlecloudutility2
lib/simplejson/simplejson/encoder.py
Python
apache-2.0
25,806
0.001589
"""Implementation of JSONEncoder """ from __future__ import absolute_import import re from operator import itemgetter # Do not import Decimal directly to avoid reload issues import decimal from .compat import u, unichr, binary_type, string_types, integer_types, PY3 def _import_speedups(): try: from . import...
types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict, namedt
uple | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ ...
jabooth/menpo-archive
menpo/image/boolean.py
Python
bsd-3-clause
11,453
0
from copy import deepcopy import numpy as np from menpo.image.base import Image from skimage.transform import pyramid_gaussian class BooleanImage(Image): r""" A mask image made from binary pixels. The region of the image that is left exposed by the mask is referred to as the 'masked region'. The set o...
to boolean values. """ def __init__(self, mask_data): # Enforce boolean pixels, and add a channel dim mask_data = np.asarray(mask_dat
a[..., None], dtype=np.bool) super(BooleanImage, self).__init__(mask_data) @classmethod def _init_with_channel(cls, image_data_with_channel): r""" Constructor that always requires the image has a channel on the last axis. Only used by from_vector. By default, just calls ...
gward/buildbot
buildbot/process/step_twisted2.py
Python
gpl-2.0
6,316
0.004275
from buildbot.status import tests from buildbot.process.step import SUCCESS, FAILURE, BuildStep from buildbot.process.step_twisted import RunUnitTests from zope.interface import implements from twisted.python import log, failure from twisted.spread import jelly from twisted.pb.tokens import BananaError from twisted.w...
esults.countTests() count = self.results.countFailures() result = SUCCESS if total == None: result = (FAILURE, ['tests%s' % self.rtext(' (%s)')]) if count: result = (FAILURE, ["%d tes%s%s" % (count, (count == 1 and '...
e(result) def finishStatus(self, result): total = self.results.countTests() count = self.results.countFailures() color = "green" text = [] if count == 0: text.extend(["%d %s" % \ (total, total == 1 and "test" or "...
wavefancy/BIDMC-PYTHON
Exome/MinorReadsCoverage/MinorReadsCoverage.py
Python
mit
3,687
0.006509
#!/usr/bin/env python3 """ Calculate minor reads coverage. Minor-read ratio (MRR), which was defined as the ratio of reads for the less covered allele (reference or variant allele) over the total number of reads covering the position at which the variant was called. (Only applied to hetero sites.) ...
# sys.exit(-1) from pysam import VariantFile
vcfMetaCols=9 #number of colummns for vcf meta information. tags = ['GT','AD'] #GATK, AD: reads depth for ref and alt allele. cutoff = 1 if args['-f']: cutoff = float(args['-f']) # def depth(geno): # '''reformat a genotype record''' # ss = geno.split(':') # ...
cailloumajor/home-web
backend/home_web/settings.py
Python
gpl-3.0
7,131
0
# -*- coding: utf-8 -*- # pylint: disable=no-init """ Django settings for home_web project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djang...
'class': 'heating.log.PilotwireHandler', 'logLength': 500, }, }, 'loggers': { 'heating.pilotwire': { 'handlers':
['pilotwire_handler'], 'level': 'INFO', }, }, } # Authentication AUTHENTICATION_BACKENDS = [ 'core.auth.backends.SettingsBackend', ] + Common.AUTHENTICATION_BACKENDS # pylint: disable=no-member ADMIN_LOGIN = values.Value() ADMIN_PASSWORD = values.Se...
tplavcic/percona-xtradb-cluster
mysql-test/suite/tokudb/t/change_column_char.py
Python
gpl-2.0
1,383
0.006508
#!/usr/bin/env python import sys def gen_test(n): print "CREATE TABLE t (a CHAR(%d));" % (n) for v in [ 'hi', 'there', 'people' ]: print "INSERT INTO t VALUES ('%s');" % (v) for i in range(2,256): if i < n: print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/" print "--e...
de/diff_tables.inc;" print "DROP TABLE ti;" print "DROP TABLE t;" def main(): print "source include/have_tokudb.inc;" print "# this test is generated by change_char.py" print "# test char expansion" print "--disable_warnings" print "DROP TABLE IF EXISTS t,ti;" print "--enable_wa...
l n takes too long to run, so here is a subset of tests for n in [ 1, 2, 3, 4, 5, 6, 7, 8, 16, 31, 32, 63, 64, 127, 128, 254, 255 ]: gen_test(n) return 0 sys.exit(main())
devilry/devilry-django
devilry/devilry_dbcache/admin.py
Python
bsd-3-clause
1,516
0
from django.contrib import admin from devilry.devilry_dbcache.models import AssignmentGroupCachedData @admin.register(AssignmentGroupCa
chedData) class AssignmentGroupCachedDataAdmin(admin.ModelAdmin): list_display = [ 'id', 'group', 'first_f
eedbackset', 'last_feedbackset', 'last_published_feedbackset', 'new_attempt_count', 'public_total_comment_count', 'public_student_comment_count', 'public_examiner_comment_count', 'public_admin_comment_count', 'public_student_file_upload_count', 'ex...
willprice/arduino-sphere-project
scripts/example_direction_finder/temboo/Library/Utilities/Dates/GetTimestamp.py
Python
gpl-2.0
6,772
0.005472
# -*- coding: utf-8 -*- ############################################################################### # # GetTimestamp # Returns the current date and time, expressed as seconds or milliseconds since January 1, 1970 (epoch time). # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the...
ger) Adds the specified number of hours to the specified
date serial number. A negative number will subtract.) """ super(GetTimestampInputSet, self)._set_input('AddHours', value) def set_AddMinutes(self, value): """ Set the value of the AddMinutes input for this Choreo. ((optional, integer) Adds the specified number of minutes to the spec...
modcracker/Tork
tork/core/manage/stop.py
Python
mit
347
0.054755
import sys, os def stop(arv): pwd = os.getcwd
() # if argv given, folders = [argv] # else, folders = pwd ### for each folder in folders ##### check pwd/folder/temp/pids for existing pid files ####### kill -15 & rm files def main(): print "Please don't t
ry to run this script separately." if __name__ == '__main__': main()
oxc/Flexget
flexget/tests/test_list_interface.py
Python
mit
9,931
0.000503
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin class TestListInterface(object): config = """ templates: global: disable: [seen] tasks: list_get: entry_list: t...
- {title: 'title 1', url: "http://mock.url/file1.torrent"} - {title: 'title 2', url: "http://mock.url/file2.torrent
"} - {title: 'title 3', url: "http://mock.url/file3.torrent"} list_match: from: - entry_list: test_list remove_on_match: no test_multiple_list_accept_with_remove: mock: - {title: 'title 1', url: "http://mock.url/f...
epifanio/ecoop
ecooputil.py
Python
lgpl-3.0
10,832
0.003139
#!/usr/bin/python ############################################################################### # # # Project: ECOOP, sponsored by The National Science Foundation # Purpose: this code is part of the Cyberinfrastructure developed for the ECOOP project # http://tw.rpi.edu/web/project/ECOOP # ...
usage : uploadfile(inputfile, outputfile) @rtype : str @param username: str - username on
remote server @param password: str - password to access remote server @param hostname: str - hostname of remote server (default: localhost) @param port: port number on remote server (default: 22) @param inputfile: str - local path to the file to uploaded @param outputfile: remot...
scraperwiki/xypath
xypath/xypath.py
Python
bsd-2-clause
31,182
0.000994
#!/usr/bin/env python """ musings on order of variables, x/y vs. col/row Everyone agrees that col 2, row 1 is (2,1) which is xy ordered. This works well with the name. Remember that the usual iterators (over a list-of-lists) is outer loop y first.""" from __future__ import absolute_import import re import messytables...
_XYCell(object): """needs to contain: value, position (x,y), parent bag""" __slots__ = ['value', 'x', 'y', 'table', 'properties'] def __init__(self, value, x, y, table, properties=None): self.value
= value # of appropriate type self.x = x # column number self.y = y # row number self.table = table if properties is None: self.properties = {} else: self.properties = properties def __hash__(self): """ In order to make a set of ce...
bpain2010/kgecweb
hostels/models.py
Python
gpl-2.0
2,053
0.032148
from django.db import models from stdimage import StdImageField from django.core.validators import RegexValidator import datetime YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year+1)): YEAR_CHOICES.append((r,r)) S_CHOICE = [('1stYear','1stYear'),('2ndYear','2ndYear'),('3rdYear','3rdYear'),('4t...
eYear = models.IntegerFiel
d(choices=YEAR_CHOICES, default=datetime.datetime.now().year) PersonName = models.CharField (max_length=10) PersonYear = models.CharField (max_length=7, choices=S_CHOICE,default='NA') PersonImage = StdImageField(upload_to='Hostels/gb/',variations={'thumbnail': (300, 200,True)}) def __str__(self): return self.Ho...
wangcy6/storm_app
frame/c++/webrtc-master/modules/audio_coding/audio_network_adaptor/parse_ana_dump.py
Python
apache-2.0
4,718
0.010386
#!/usr/bin/python2 # Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All...
(): decisions = {} event = debug_dump_pb2.Event() for decision in event.encoder_runtime_config.DESCRIPTOR.fields: decisions[decision.name] = {'time': [], 'value': []} return decisions def ParseA
naDump(dump_file_to_parse): with open(dump_file_to_parse, 'rb') as file_to_parse: metrics = InitMetrics() decisions = InitDecisions() first_time_stamp = None while True: event = GetNextMessageFromFile(file_to_parse) if event == None: break if first_time_stamp == None: ...
deyvedvm/cederj
fund-prog/2017-2/ap1/questao3.py
Python
gpl-3.0
2,277
0.001778
# coding=utf-8 """ Faça um programa, contendo subprogramas, que: a) Leia da entrada padrão as dimensões,
quantidade de linhas e quantidade de colunas de uma matriz bidimensional; b) Gere uma matriz, onde cada célula é um número inteiro gerado aleatoriamente no intervalo 0 a 9; c) Mostre a matriz, linha a linha
na tela; d) Calcule e escreva a média de todos os valores na matriz; e) Escreva o conteúdo de todas as linhas que possuam todos os seus valores acima da média calculada em (d). Dica Utilize a função random.randint(a, b), disponível na API, que retorna um número randômico inteiro entre a e b, inclusive. Restrição Nã...
sharbison3/python-docs-samples
bigquery/api/getting_started.py
Python
apache-2.0
2,344
0
#!/usr/bin/env python # Copyright 2015, 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 ...
ld('bigquery', 'v2') # [END build_service] try: # [START run_query] query_request = bigquery_service.jobs() query_data = { 'query': ( 'SELECT TOP(corpus, 10) as
title, ' 'COUNT(*) as unique_words ' 'FROM [publicdata:samples.shakespeare];') } query_response = query_request.query( projectId=project_id, body=query_data).execute() # [END run_query] # [START print_results] print('Quer...
CCI-MOC/GUI-Backend
core/mixins.py
Python
apache-2.0
1,993
0
""" core.mixins - Mixins available to use with models """ from django.db.models.signals import post_save def on_changed(sender, **kwargs): """ Calls the `model_changed` method and then resets the state. """ instance = kwargs.get("instance") is_new = kwargs.get("created") dirty_fields = instanc...
Returns the model as a dict """ # Get all the field names that are not relations keys = (f.nam
e for f in self._meta.local_fields if not f.rel) return {field: getattr(self, field) for field in keys} def get_dirty_fields(self): """ Returns the fields dirty on the model """ dirty_fields = {} current_state = self.to_dict() for key, value in current_state...
mbedmicro/pyOCD
pyocd/probe/pydapaccess/interface/pywinusb_backend.py
Python
apache-2.0
6,277
0.001912
# pyOCD debugger # Copyright (c) 2006-2020 Arm Limited # SPDX-License-Identifier: Apache-2.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...
.interface import Interface from .common import filter_device_by_usage_page from ..dap_access_api import DAPAccessIntf from ....utility.timeout import Timeout OPEN_TIMEOUT_S = 60.0 LOG = logging.getLogger(__name__) try: import pywinusb.hid as hid except: if platform.
system() == "Windows": LOG.error("PyWinUSB is required on a Windows Machine") IS_AVAILABLE = False else: IS_AVAILABLE = True class PyWinUSB(Interface): """! @brief CMSIS-DAP USB interface class using pyWinUSB for the backend. """ isAvailable = IS_AVAILABLE def __init__(self): ...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/connection_monitor_parameters.py
Python
mit
2,077
0.001444
# 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 may cause incorrect behavior and will be lost if the code is # regenerated. # --------------------------
------------------------------------------------ from msrest.serialization import Model class ConnectionMonitorParameters(Model): """Parameters that define the operation to create a connection monitor. All required parameters must be populated in order to send to Azure. :param source: Required. :ty...
integree/hello-world
manage.py
Python
mit
648
0
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate ...
_ == '__main__': main()
calvinhklui/Schedulize
GenEdLookup.py
Python
mit
931
0.015038
import numpy as np import pandas as pd import pickle # Return 0 or 1 based on whether Course fulfills a General Education Requirement def lookupGenEd(cNum, college): fileName = "data/Dietrich Gen Eds.csv" picklepath = "data\\dietrich_gen_eds.p" try: with open(picklepath,'rb') as file: ...
= pickle.load(file) except: df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2']) gen_eds = set(df['Dept'].values) with open(picklepath,'wb') as file: pickle.dump(gen_eds,file) return cNum in gen_eds ''' genEdubility = lookupGenEd(73100, "dietrich") pr...
100") print('Is Gen Ed?:', genEdubility) print() genEdubility = lookupGenEd(15322, "scs") print("15322") print('Is Gen Ed?:', genEdubility) print() '''
immersinn/ncga
ncga/extract_billpage_content.py
Python
mit
2,219
0.00721
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 7 21:16:09 2017 @author: immersinn """ import regex as re def billsummaryaref_matcher(tag): return tag.name =='a' and hasattr(tag, 'text') and tag.text == 'View Available Bill Summaries' def extract_links(soup): """Extract Bill Text Lin...
= a['href'] spons_list.append({'userid' : userid_re.findall(hr)[0], 'chamber' : chamber_re.findall(hr)[0]}) meta[kw] =
spons_list elif kw in ['Counties', 'Keywords', 'Statutes']: meta[kw] = content.text.split(', ') else: meta[kw] = content.text if kw == 'Counties' and \ meta[kw][0].lower().strip() == 'no counties specifically cited': meta[kw] = N...
Azure/azure-linux-extensions
VMEncryption/main/oscrypto/ubuntu_1604/Ubuntu1604EncryptionStateMachine.py
Python
apache-2.0
7,381
0.003252
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # 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 # # U...
self.logger.log("OS volume is already encrypted") self.skip_encryption() self.log_machine_state() return self.log_machine_state() self.enter_prereq() self.log_machine_stat
e() self.enter_stripdown() self.log_machine_state() oldroot_unmounted_successfully = False attempt = 1 while not oldroot_unmounted_successfully: self.logger.log("Attempt #{0} to unmount /oldroot".format(attempt)) try: if attempt...
hryamzik/ansible
lib/ansible/modules/network/cumulus/_cl_ports.py
Python
gpl-3.0
2,580
0.00155
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Cumulus Networks <ce-ceng@cumulusnetworks.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_versio...
Cumulus Networks (@CumulusNetworks)" short_description: Configure Cumulus Switch port attributes (ports.conf) deprecated: removed_in: "2.5" why: The M(nclu) module is designed to be easier to use for individuals who are new to Cumulus Linux by exposing the NCLU interface in an automatable way. alternative: Use M(...
the Cumulus Linux ports.conf, file. This module does not do any error checking at the moment. Be careful to not include ports that do not exist on the switch. Carefully read the original ports.conf file for any exceptions or limitations. For more details go the Configure Switch Port Attribute Do...
pranka02/image_processing_py
gaussian.py
Python
mit
652
0.019939
import numpy as np def gauss(win, sigma)
: x = np.arange(0, win, 1, float) y = x[:,np.newaxis] x0 = y0 = win // 2 g=1/(2*np.pi*sigma**2)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2) return g def gaussx(win, sigma): x = np.arange(0, win, 1, float) y = x[:,np.newaxis] x0 = y0 = win // 2 gx=(x-x0)/(2*np...
gy=(y-y0)/(2*np.pi*sigma**4)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2) return gy
cnheitman/barf-project
tests/core/smt/test_smtsolver.py
Python
bsd-2-clause
13,055
0.000153
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # 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 notice, this # list of condit...
are_fun("z", z) self._solver.add(x | y == z) # Add constraints to avoid trivial solutions. self._solver.add(x > 1) s
elf._solver.add(y > 1) self._solver.add(x != y) self.assertEqual(self._solver.check(), "sat") x_val = self._solver.get_value(x) y_val = self._solver.get_value(y) z_val = self._solver.get_value(z) self.assertTrue(x_val | y_val == z_val) def test_lshift(self): ...
nextgis-extra/tests
lib_gdal/gdrivers/sgi.py
Python
gpl-2.0
2,443
0.006959
#!/usr/bin/env python ############################################################################### # $Id: sgi.py 31335 2015-11-04 00:17:39Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: PNM (Portable Anyware Map) Testing. # Author: Frank Warmerdam <warmerdam@pobox.com> # #################################...
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISIN
G # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ############################################################################### import sys sys.path.append( '../pymod' ) import gdaltest ###############################################################################...
ava-project/ava-website
website/apps/plugins/forms.py
Python
mit
2,440
0
import json import os import avasdk from zipfile import ZipFile, BadZipFile from avasdk.plugins.manifest import validate_manifest from avasdk.plugins.hasher import hash_plugin from django import forms from django.core.validators import ValidationError from .validators import ZipArchiveValidator class PluginArchive...
raise ValidationError('Error with upload, please try again') except KeyError: raise ValidationE
rror('No manifest.json found in archive') except json.JSONDecodeError: raise ValidationError('Error with manifest.json, bad Json Format') except avasdk.exceptions.ValidationError as e: raise ValidationError('Error in manifest.json ({})'.format(e)) def get_readme(self, archiv...
AntonelliLab/seqcap_processor
secapr/remove_uninformative_seqs.py
Python
mit
2,167
0.032764
#author: Tobias Andermann, tobias.andermann@bioenv.gu.se import os import sys import re import glob import shutil import
argparse from Bio import SeqIO from .utils import CompletePath # Get arguments def get_args(): parser = argparse.ArgumentParser( description="Set the maximum fraction of missing data that you want to allow in an alignment and drop all sequences above this threshold.", formatter_class=argparse.ArgumentDefaultsH...
fasta format.' ) parser.add_argument( '--maximum_missing', type=float, default=0.8, help='Define the maximal fraction of missing data that you want to allow. All sequences below this threshold will be exported into a new alignment.' ) parser.add_argument( '--output', required=True, action=CompletePath...
d-plaindoux/fluent-rest
tests/runall.py
Python
lgpl-2.1
828
0
# Copyright (C)2016 D. Plaindoux. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2, or (at your option) any # later version. import unittest import path_parse_test impo...
()) unittest.TextTestRunner(verbosity=2).run(suite
)
gzqichang/wa
qsite/qsite/apps.py
Python
mit
119
0.009009
from django.apps import AppConfig class QsiteConfig(AppCon
fig): name = '
qsite' verbose_name = '站点管理'
GDGLima/contentbox
third_party/social/tests/backends/test_yahoo.py
Python
apache-2.0
1,798
0
import json from httpretty import HTTPretty from social.p3 import urlencode from social.tests.backends.oauth import OAuth1Test class YahooOAuth1Test(OAuth1Test): backend_path = 'social.backends.yahoo.YahooOAuth' user_data_url = 'https://social.yahooapis.com/v1/user/a-guid/profile?' \ 'for...
'true' }) guid_body = json.dumps({ 'guid': { 'uri': 'https://social.yahooapis.com/v1/me/guid', 'value': '
a-guid' } }) user_data_body = json.dumps({ 'profile': { 'bdRestricted': True, 'memberSince': '2007-12-11T14:40:30Z', 'image': { 'width': 192, 'imageUrl': 'http://l.yimg.com/dh/ap/social/profile/' 'pro...
sghai/robottelo
tests/robottelo/ui/test_location.py
Python
gpl-3.0
2,887
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import six import unittest2 from robottelo.ui.location import Location from robottelo.ui.locators import common_locators from robottelo.ui.locators import locators if six.PY2: import mock else: from unittest import mock class LocationTestCase(...
it']), mock.call(common_locators['submit']) ]
self.assertEqual(3, location.click.call_count) location.click.assert_has_calls(click_calls, any_order=False) location.assign_value.assert_called_once_with( locators['location.name'], 'foo') # not called if parent is None location.select.assert_not_called() locati...
forslund/mycroft-core
test/integrationtests/voight_kampff/generate_feature.py
Python
apache-2.0
2,177
0
# Copyright 2020 Mycroft AI 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/licens
es/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 ...
mport Path import sys """Convert existing intent tests to behave tests.""" TEMPLATE = """ Scenario: {scenario} Given an english speaking user When the user says "{utterance}" Then "{skill}" should reply with dialog from "{dialog_file}.dialog" """ def json_files(path): """Generator function retur...
ChantyTaguan/zds-site
zds/utils/templatetags/seconds_to_duration.py
Python
gpl-3.0
787
0
from django import template import datetime register = template.Library() # https://stackoverflow.com/a/8907269/2226755 def strfdelta(tdelta, fmt): d = {"days": tdelta.days} d["hours"], rem = divmod(tdelta.seconds, 3600) d["minutes"], d["seconds"] = divmod(rem, 60) return fmt.format(**d) # TODO add...
her duration) from a duration in seconds. """ if value <= 0: return "" duration = datetime.timedelta(seconds=value) if datetime.timedel
ta(hours=1) > duration: return strfdelta(duration, "{minutes}m{seconds}s") else: return strfdelta(duration, "{hours}h{minutes}m{seconds}s")
olympiag3/olypy
tests/unit/test_olymap_skill.py
Python
apache-2.0
1,098
0.005464
import olymap.skill def test_learn_time(): tests = ( ({}, None), ({'SK': {'tl': ['14']}}, '14'), ({'SK': {'an': ['0']}}, None), ({'IT': {'tl': ['1']}}, None), ({'SK': {'an': ['1']}}, None), ) for box, answer in tests: assert olymap.skill.get_learn_time(box) =...
{'rs': ['632']}}, {'id': '632', 'oid': '632', 'name': 'Determine inventory of character'}), ({'SK': {'rs': ['630']}}, {'id': '630', 'oid': '630', 'name': 'Stealth'}), ({'SK': {'re': ['632']}}, None), ({'SL': {'rs': ['632']}}, None), ) data = {'630': {'firstline': ['630 skill ...
: ['632 skill 0'], 'na': ['Determine inventory of character'], 'SK': {'tl': ['14'], 'rs': ['630']}}} for box, answer in tests: assert olymap.skill.get_required_skill(box, data) == answer
joshrule/LOTlib
LOTlib/Examples/RationalRules/__init__.py
Python
gpl-3.0
157
0.006369
from Model import *
import MemoryDecay # Note we cannot import TwoConcepts here because that ends up modifying the grammar, ruining
it for example loaders
AmineChikhaoui/nixops
nixops/deployment.py
Python
lgpl-3.0
53,483
0.004463
# -*- coding: utf-8 -*- import sys import os.path import subprocess import json import string import tempfile import shutil import threading import exceptions import errno from collections import defaultdict from xml.etree import ElementTree import nixops.statefile import nixops.backends import nixops.logger import ni...
return nixops.util.undefined def _create_resource(self, name, type): c = self._db.cursor() c.execute("select 1 from Resources where deployment = ? and name = ?", (self.uuid, name)) if len(c.fetchall()) != 0: raise Exception("resource already exists in database!") ...
alues (?, ?, ?)", (self.uuid, name, type)) id = c.lastrowid r = _create_state(self, type, name, id) self.resources[name] = r return r def export(self): with self._db: c = self._db.cursor() c.execute("select name, value from Deployme...
Sonicbids/django
django/contrib/admin/filters.py
Python
bsd-3-clause
17,360
0.00121
""" This encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ import datetime from django.db import models...
continue return list
_filter_class(field, request, params, model, model_admin, field_path=field_path) class RelatedFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): other_model = get_model_from_relation(field) if hasattr(field, 'rel'): ...
anantag/flightsearch
backend/flightsearch/rawParser/admin.py
Python
gpl-2.0
139
0
from django.
contrib import admin from
rawParser.models import flightSearch # Register your models here. admin.site.register(flightSearch)
Ircam-Web/mezzanine-organization
organization/shop/management/commands/__init__.py
Python
agpl-3.0
846
0
# -*- coding: utf-8 -*- # # Copyrigh
t (c) 2016-2017 Ircam # Copyright (c) 2016-2017 Guillaume Pellerin # Copyright (c) 2016-2017 Emilie Zawadzki # This file is part of mezzanine-organization. # 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 option) any later version. # This program 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 Affero Ge...
IronCountySchoolDistrict/powerschool_apps
docs/conf.py
Python
mit
8,001
0.001125
# -*- coding: utf-8 -*- # # powerschool_apps documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration valu...
start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'powerschool_apps', 'powerschool_apps Documentation', """Iron County School District""", 'powerschool_apps', """PowerSchool customizations written in Django""", 'Miscellaneous'),
] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
looooo/panel-method
examples/tests/test_linear_2d_doublet.py
Python
gpl-3.0
276
0.003623
from parabem.pan2d import doublet_2_1 import parabem im
port numpy as np v1 = parabem.PanelVector2(-1, 0) v2 = parabem.PanelVector2(1, 0) panel = par
abem.Panel2([v2, v1]) vals = ([doublet_2_1(parabem.Vector2(x, 0), panel, True) for x in np.linspace(-2, 2, 20)]) print(vals)
rlsharpton/byte-of-Python
oop_objvar.py
Python
gpl-2.0
1,127
0.003549
__author__ = 'rls' class Robot: """Represents a robot, with a name.""" # A class variable, counting the number of robots population = 0 def __init__(self, name): """Initializes the data.""" self.name = name print('(Initializing {})'.format(self.name)) # When this pers...
print("There are still {:d} robots working.".format(Robot.population)) def say_hi(self): """Greeting by the robot Long doc statement.""" print("Greetings, my masters have called me {}".format(self.name)) @classmethod def how_many(cls): """Prints the current popu...
__version__ = 0.2
fujicoin/electrum-fjc
electrum/gui/kivy/main_window.py
Python
mit
44,226
0.003346
import re import os import sys import time import datetime import traceback from decimal import Decimal import threading import asyncio from electrum.bitcoin import TYPE_ADDRESS from electrum.storage import WalletStorage from electrum.wallet import Wallet, InternalAddressCorruption from electrum.paymentrequest import ...
elf, d): Logger.info("on_history") if self.wallet: self.wallet.clear_coin_price_cache() self._trigger_update_history() def on_fee_histogram(self, *args): self._trigger_update_history() def _get_bu(self): decimal_point = self.electrum_config.get('decimal_poin...
EFAULT) try: return decimal_point_to_base_unit_name(decimal_point) except UnknownBaseUnit: return decimal_point_to_base_unit_name(DECIMAL_POINT_DEFAULT) def _set_bu(self, value): assert value in base_units.keys() decimal_point = base_unit_name_to_decimal_poin...
befair/gasistafelice
gasistafelice/gf/gas/forms/order/__init__.py
Python
agpl-3.0
5,005
0.006194
""" Order module has been split for its complexity. Proposed clean hierarchy for GASSupplierOrder that can be used in many contexts such as: DES: ChooseSupplier ChooseGAS ChooseReferrer GAS: ChooseSupplier OneGAS ChooseReferrer Supplier: OneSupplier ChooseGAS ChooseR...
se import AddOrderForm, EditOrderForm from gf.gas.forms.order.plan import AddPlannedOrderForm from gf.gas.forms.order.intergas import AddInterGASOrderForm, AddInterGASPlannedOrderForm from gf.gas.models import GASSupplierOrder import copy import logging log = logging.getLogger(__name__) def form_class_factory
_for_request(request, base): """Return appropriate form class basing on GAS configuration and other request parameters if needed""" #log.debug("OrderForm--> form_class_factory_for_request") fields = copy.deepcopy(base.Meta.fields) gf_fieldsets = copy.deepcopy(base.Meta.gf_fieldsets) attrs = {} ...
tim-janik/testbit-tools
buglist.py
Python
gpl-3.0
7,933
0.024707
#!/usr/bin/env python # Copyright (C) 2008,2011 Lanedo GmbH # # Author: Tim Janik # # 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...
nome', 'http://bugzilla.gnome.org/buglist.cgi?bug_id='), ('fd', 'https://bugs.freedesktop.org/buglist.cgi?bug_id='), ('freedesktop', 'https://bugs.freedesktop.org/buglist.cgi?bug_id='), ('mb', 'https://bugs.maemo.org/buglist.cgi?bug_id='), ('maemo', 'https://bugs.maemo.org/buglist.cgi?...
'https://projects.maemo.org/bugzilla/buglist.cgi?bug_id='), ('gcc', 'http://gcc.gnu.org/bugzilla/buglist.cgi?bug_id='), ('libc', 'http://sources.redhat.com/bugzilla/buglist.cgi?bug_id='), ('moz', 'https://bugzilla.mozilla.org/buglist.cgi?bug_id='), ('mozilla', 'https://bugzilla.mozil...
qiudebo/13learn
code/python/myPython.py
Python
mit
1,435
0.0445
# *-* coding:utf-8 *-* from functools import partial # 可读性好 # range() print range(0,9,2) #递增列表 for i in xrange(0,9,2): # 只用于for 循环中 print i albums = ("Poe","Gaudi","Freud","Poe2") years = (1976,1987,1990,2003) for album in sorted(albums): print album for album in reversed(albums): print a...
解析,列表解析的表达式比map lambda效
率更高 def fuc(a): return a**2 x = range(1,10,1) print x print map(fuc,x) # map 对所有的列表元素执行一个操作 # lambda 创建只有一行的函数 -- 只使用一次,非公用的函数 print map(lambda x:x**2,range(6)) print [x**2 for x in range(6) if x>3] print filter(lambda x:x%2,range(10)) print [x for x in range(10) if x%2] # 11.7.2 函数式编程 print...
funkring/fdoo
addons/payment_paypal/models/paypal.py
Python
agpl-3.0
19,377
0.003716
# -*- coding: utf-'8' "-*-" import base64 try: import simplejson as json except ImportError: import json import logging import urlparse import werkzeug.urls import urllib2 from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment_paypal.controllers.main import Payp...
ypal_tx_values['custom'] = json.dumps({'return_url': '%s' % paypal_tx_values.pop('return_url')}) return partner_values, paypal_tx_values def paypal_get_form_action_url(self, cr, uid, id, context=None): acquirer = self.browse(cr, uid, id, context=context) return self._get_paypal_urls(cr, uid...
ken(self, cr, uid, ids, context=None): """ Note: see # see http://stackoverflow.com/questions/2407126/python-urllib2-basic-auth-problem for explanation why we use Authorization header instead of urllib2 password manager """ res = dict.fromkeys(ids, False) paramete...
rauburtin/pysftpserver
pysftpserver/tests/stub_sftp.py
Python
mit
6,888
0.000145
# Copyright (C) 2003-2009 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
f _realpath(s
elf, path): return self.ROOT + self.canonicalize(path) def list_folder(self, path): path = self._realpath(path) try: out = [] flist = os.listdir(path) for fname in flist: attr = SFTPAttributes.from_stat( os.lstat(os.pat...
dhgarcia/babelModules
pynnModules/Network/spike_file_to_spike_array.py
Python
gpl-3.0
8,559
0.015189
import numpy import itertools import random import math def convert_spike_list_to_timed_spikes(spike_list, min_idx, max_idx, tmin, tmax, tstep): times = numpy.array(range(tmin, tmax, tstep)) spike_ids = sorted(spike_list) possible_neurons = range(min_idx, max_idx) spikeArray = dict([(neuron, times) for...
for time_range in input_times[file_idx]: for neuron in convert_file_to_spikes(input_file_name=input_files[file_idx], min_idx=min_neuron_id, max_idx=max_neuron_id, tmin=time_range[0], tmax=time_range[1], compatible_input=compatible_input).items(): if neuron[0] in spikeArray: ...
spikeArray[neuron[0]] = neuron[1] for neuron in spikeArray.items(): spikeArray[neuron[0]] = numpy.sort(numpy.unique(numpy.array(neuron[1]))) return spikeArray def subsample_spikes_by_time(spikeArray, start, stop, step): subsampledArray = {} for neuron in spikeArray: tim...
jeremy-ma/gmmmc
gmmmc/fastgmm/setup_fast_likelihood.py
Python
mit
597
0.025126
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy as np import os sourcefiles = [ 'fast_likelihood.pyx'] ext_modules = [Extension("fast_likelihood", sourcefiles, include_dirs = [np.get_inclu...
enmp', '-lc++'], extra_link_args=['-fopenmp'],
language='c++')] setup( name = 'fastgmm', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
EntropyFactory/creativechain-core
qa/rpc-tests/p2p-fullblocktest.py
Python
mit
52,732
0.003926
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from ...
def __init__(self, header=None): super(CBrokenBlock, self).__init__(header) def initialize(self, base_block): self.vtx = copy.deepcopy(base_block.vtx) self.hashMerkleRo
ot = self.calc_merkle_root() def serialize(self): r = b"" r += super(CBlock, self).serialize() r += struct.pack("<BQ", 255, len(self.vtx)) for tx in self.vtx: r += tx.serialize() return r def normal_serialize(self): r = b"" r += super(CBroken...
mark-adams/django-waffle
waffle/south_migrations/0001_initial.py
Python
bsd-3-clause
7,674
0.007297
# encoding: utf-8 import datetime import django from south.db import db from south.v2 import SchemaMigration from django.db import models # Django 1.5+ compatibility if django.VERSION >= (1, 5): from django.contrib.auth import get_user_model else: from django.contrib.auth.models import User def get_user...
ser': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields...
'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'def...
davidmalcolm/pygobject
gi/_glib/__init__.py
Python
lgpl-2.1
4,827
0
# -*- Mode: Python; py-indent-offset: 4 -*- # pygobject - Python bindings for the GObject library # Copyright (C) 2006-2012 Johan Dahlin # # glib/__init__.py: initialisation file for glib module # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Pub...
plied warranty of # MERCHANTABILITY or FITNESS FOR A PART
ICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA from . import _glib ...
mzdaniel/oh-mainline
vendor/packages/scrapy/scrapy/contrib/linkextractors/htmlparser.py
Python
agpl-3.0
2,447
0.001635
""" HTMLParser-based link extractor """ from HTMLParser import HTMLParser from urlparse import urljoin from w3lib.url import safe_url_string from scrapy.link import Link from scrapy.utils.python import unique as unique_list class HtmlParserLinkExtractor(HTMLParser): def __init__(self, tag="a", attr="href", pro...
l, link.url) link.url = safe_url_string(link.url, response_encoding) link.text = link.text.decode(response_encoding) ret.append(link) return ret def extract_links(self, response): # wrapper needed to allow to work directly with text return self._extract_...
elf): HTMLParser.reset(self) self.base_url = None self.current_link = None self.links = [] def handle_starttag(self, tag, attrs): if tag == 'base': self.base_url = dict(attrs).get('href') if self.scan_tag(tag): for attr, value in attrs: ...
digitalocean/netbox
netbox/dcim/models/device_components.py
Python
apache-2.0
27,423
0.002079
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from dj...
er) which provides access to ConsolePorts. """
type = models.CharField( max_length=50, choices=ConsolePortTypeChoices, blank=True, help_text='Physical port type' ) tags = TaggableManager(through=TaggedItem) csv_headers = ['device', 'name', 'label', 'type', 'description'] class Meta: ordering = ('device', '_...
rz4/SpaceManBash
src/GameData.py
Python
mit
8,056
0.002731
''' GameData.py Last Updated: 3/16/17 ''' import json, os import numpy as np import pygame as pg from GameAssets import GameAssets as ga class GameData(): """ GameData class is used to stores game state information. """ def __init__(self): ''' Method initiates game state variables. ...
./data/music/"+data['music']) pg.mixer.music.set_volume(0.15) pg.mixer.music.play(loops=3) self.level_background = getattr(ga, data['background']) self.level_midground = getattr(ga, data['midground']) for script in data['scripts']: self.add_level_script(script...
''' self.frame_current.level_loaded = False self.game_objects = [] self.collisions = {} self.load_level() def switch_level(self, index): ''' Method switches level. Param: index ;int index of desired level ''' self....
aniketmaithani/kimani-adserver
Adserver/base/api/pagination.py
Python
gpl-2.0
640
0.001563
# -*- coding: utf-8 -*- # Third Party Stuff # Third Party Stuff from rest_framework.pagination import PageNumberP
agination as DrfPageNumberPagination class PageNumberPagination(DrfPageNumberPagination): # Client can control the page using this query parameter. page_query_param = 'page' # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. ...
limit the maximum page size the client may request. # Only relevant if 'page_size_query_param' has also been set. max_page_size = 1000