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 |
|---|---|---|---|---|---|---|---|---|
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_table19.py | Python | bsd-2-clause | 1,269 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, [email protected]
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | {},
{'header': " Column4 "}]})
workbook | .close()
self.assertExcelEqual()
|
YAmikep/django-xmlmapping | xmlmapping/models.py | Python | bsd-3-clause | 8,995 | 0.002779 | # Django
from django.db import models
# Third-party apps
import jsonfield # http://pypi.python.org/pypi/django-jsonfield/
from lxml import etree # http://lxml.de/
# Internal
from .log import default_logger as logger
from .utils.introspection import ModelFactory
from .utils.serializers import deserialize_f... | s: %s, Created Objects: %s %s' % (
log_desc,
nb_elems,
nb_targeted,
nb_created,
(nb_targeted == nb_created and ['[OK]'] or ['=> numbers different [KO]'])[0]
)
)
return nb_created
def _map_element... | models, get_id=None):
"""Maps an element to several models.
Args:
element: an XML element
models: the models to mapped
get_id: the function to use to calculate the ID of the element to identify it amongst the other.
Returns:
The number o... |
JackRamey/LaserPony | dbutils.py | Python | mit | 1,980 | 0.007071 | """Usage: dbutils.py [-dfh]
Options:
-d --dropall Deletes all collections in the database. Use this very wisely.
-f --force Forces all questions to 'yes'
-h --help show this
"""
import sys
from docopt import docopt
from laserpony import app
from laserpony.util import db
##UTILITY FUNCTIONS
... | "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choic... | or 'n').\n")
# Switch over to the virtual environment version of python
arguments = docopt(__doc__, argv=sys.argv[1:], version='0.1')
delete_db_message = "Are you absolutely sure you want to delete the entire database?"
if arguments['--dropall']:
if arguments['--force']:
db.connection.drop_database(app.c... |
bally12345/enigma2 | lib/python/Components/DiskInfo.py | Python | gpl-2.0 | 1,054 | 0.032258 | from GUIComponent import GUIComponent
from Variab | leText import VariableText
from os import statvfs
from enigma import eLabel
# TODO: Harddisk.py has similiar functions, but only similiar.
# fix this to use same code
class DiskInfo(VariableText, GUIComponent):
FREE = 0
USED = 1
SIZE = 2
def __init__(self, path, type, update = True):
GUIComponent.__init__(self... | te()
def update(self):
try:
stat = statvfs(self.path)
except OSError:
return -1
if self.type == self.FREE:
try:
percent = '(' + str((100 * stat.f_bavail) // stat.f_blocks) + '%)'
free = stat.f_bfree * stat.f_bsize
if free < 10000000:
free = _("%d Kb") % (free >> 10)
elif free < 10... |
YudingZhou/Yo-Fatty | ITA/graphic/chapter22_elementary_test.py | Python | gpl-2.0 | 1,375 | 0 | '''
Copy right (c) | [email protected]
'''
import unittest
from chapter22_elementary import Vertex
from chapter22_elementary import breath_first_search_input_adjacency_list
def printX(x):
print x
class MyTestCase(unittest.TestCase | ):
def test_something(self):
self.assertEqual(True, False)
def test_run_BFS_on_adjacency_list(self):
''' 4X4 vertex'''
v1 = Vertex(1)
v3 = Vertex(3)
v4 = Vertex(4)
v6 = Vertex(6)
v7 = Vertex(7)
v10 = Vertex(10)
v14 = Vertex(14)
v15... |
sputnick-dev/weboob | modules/citelis/module.py | Python | agpl-3.0 | 2,036 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Laurent Bachelier
#
# This file is part of weboob.
#
# weboob 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 ... | h weboob. If not, see <http://www.gnu.org/licenses/>.
from weboob.tools.backend import Module, BackendConfig
from weboob.tools.value import ValueBackendPassword
from weboob.capabilities.bank import CapBank, AccountNotFound
from .browser import CitelisBrowser
__all__ = ['CitelisModule']
class CitelisModule(Module... | CapBank):
NAME = 'citelis'
DESCRIPTION = u'Citélis'
MAINTAINER = u'Laurent Bachelier'
EMAIL = '[email protected]'
LICENSE = 'AGPLv3+'
VERSION = '1.1'
BROWSER = CitelisBrowser
CONFIG = BackendConfig(
ValueBackendPassword('merchant_id', label='Merchant ID', masked=False),
... |
xingjian-f/Leetcode-solution | 190. Reverse Bits.py | Python | mit | 231 | 0.030303 | class Solution(object):
d | ef reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
ret = 0
for i in range(32):
ret += (n%2) * 2**(31-i)
n /= 2
ret | urn ret |
rdo-infra/ci-config | ci-scripts/infra-setup/roles/rrcockpit/files/telegraf_py3/influxdb_utils.py | Python | apache-2.0 | 487 | 0 | import time
from datetime import datetime
def format_ts_from_float(ts):
return int(ts) * 1000000000
def format_ts_from_date(ts):
return | format_ts_from_float(time.mktime(ts.timetuple()))
def format_ts_from_str(ts, pattern='%Y-%m-%d %H:%M:%S'):
return format_ts_from_date(datetime.strptime(ts, pattern))
def format_ts_from_last_modified(ts, pattern='%a, %d %b %Y %H:%M:%S %Z'):
ts = datetime.strptime(ts, pattern)
retur | n int(time.mktime(ts.timetuple()) * 1000)
|
maximilianofaccone/puppy-siberian | usr/share/bleachbit/CleanerML.py | Python | gpl-3.0 | 8,532 | 0.00082 | # vim: ts=4:sw=4:expandtab
# BleachBit
# Copyright (C) 2014 Andrew Ziem
# http://bleachbit.sourceforge.net
#
# 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
... | mmand')
provider = None
for actionplugin in ActionProvider.plugins:
if actionplugin.action_key == command:
| provider = actionplugin(action_node)
if None == provider:
raise RuntimeError("Invalid command '%s'" % command)
self.cleaner.add_action(self.option_id, provider)
def list_cleanerml_files(local_only=False):
"""List CleanerML files"""
cleanerdirs = (Common.local_cleaners_dir,
... |
n6g7/scrapy-itemagic | itemagic/magic.py | Python | mit | 1,649 | 0.032141 | from extractors import XPathExtractor
from parser import Parser
from rules import ConstRule, Map, MapRule, SubPathRule, UrlRule, XPathRule
def is_list(obj):
return isinstance(obj, (list, tuple))
def is_str(obj):
return isinstance(obj, (str, unicode))
def parse_xpath_rule(line):
l = len(line)
if l == 2:
# Basi... | one, xpath=None, *args):
rules = []
# Build const rules
if is_list(const):
for line in const:
rules.append(ConstRule(line[0], line[1]))
elif isinstance(const, dict):
for field in const:
rules.append(ConstRule(field, const[field]))
# Build url rule
if is_str(url):
rules.append(UrlRule(url))
# Build... | is_list(xpath):
for line in xpath:
rules.append(parse_xpath_rule(line))
return Parser(*rules) |
claudiodriussi/DynaQ | dynaq/workspace.py | Python | lgpl-3.0 | 5,345 | 0.002058 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# workspace.py
#
# Copyright (c) 2014
# Author: Claudio Driussi <[email protected]>
#
from sqlalchemy.ext.declarative import declarative_base
from .db import *
class WorkSpace(object):
"""Encapsulate an whole SQLAlchemy orm from an DynaQ db definitio... | my orm objects
the objects are stored in self.tables dictionary
:param prefix: an optional prefix for table names ie: if the table
name is "user" and pr | efix is "data_" the name become "data_user"
:param pref_tabels: an optional dict for prefix bypass names for
singles names ie: if pref_tabels is {'zip_codes': ''} the name of
zip table is "zip_codes" even if prefix is "data_"
:param defaults: function for handle default values (not han... |
spulec/moto | moto/transcribe/responses.py | Python | apache-2.0 | 7,998 | 0.0005 | import json
from moto.core.responses import BaseResponse
from moto.core.utils import amzn_request_id
from .models import transcribe_backends
class TranscribeResponse(BaseResponse):
@property
def transcribe_backend(self):
return transcribe_backends[self.region]
@property
def request_params(se... | f._get_param("NextToken")
max_results = self._get_param("MaxResults")
response = se | lf.transcribe_backend.list_transcription_jobs(
state_equals=state_equals,
job_name_contains=job_name_contains,
next_token=next_token,
max_results=max_results,
)
return json.dumps(response)
@amzn_request_id
def list_medical_transcription_jobs(self)... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/hplip/base/mdns.py | Python | gpl-3.0 | 10,078 | 0.003671 | # -*- coding: utf-8 -*-
#
# (c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your opt... | PTR, QCLASS_IN))
first_record = True
for d in answers[index:index+MAX_ANSWERS_PER_PACKET]:
answer_record.seek(0)
answer_recor | d.truncate()
# NAME
if not first_packet and first_record:
first_record = False
write_name(answer_record, "_pdl-datastream._tcp.local")
answer_record.write(struct.pack("!B", 0x00))
else:
answer_record.write(struct.pack("... |
MagicForest/Python | src/training/Core2/Chapter14ExecutionEnvironment/hello.py | Python | apache-2.0 | 88 | 0.022727 | def say_hello():
print 'Hello'
if | __name__ == '__main__ | ':
say_hello()
|
SamaraCardoso27/eMakeup | backend/appengine/routes/home.py | Python | mit | 492 | 0.010163 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaecookie.deco | rator import no_csrf
from gaepermission.decorator import login_not_required
@login_not_required
@no_csrf
def index():
return TemplateResponse()
def insertStudent():
return TemplateResponse(template_path="/student/insert_student.html")
def | searchStudent():
return TemplateResponse(template_path="/student/search_student.html") |
adieu/authentic2 | authentic2/auth2_auth/auth2_ssl/views.py | Python | agpl-3.0 | 462 | 0.008658 | import functools
import registration.views
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.conf import | settings
import forms
def register(request):
'''Registration page for SSL auth without CA'''
next = request.GET.get(REDIRECT_FIELD_NAME, | settings.LOGIN_REDIRECT_URL)
return registration.views.register(request, success_url=next,
form_class=functools.partial(forms.RegistrationForm,
request=request))
|
cgvarela/pyserverlib | kontalklib/logging.py | Python | gpl-3.0 | 1,793 | 0.003904 | # -*- coding: utf-8 -*-
'''Twisted logging to Python loggin bridge.'''
'''
Kontalk Pyserver
Copyright (C) 2011 Kontalk Devteam <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundat... | ng system.'''
global level
l = cfg['server']['log.levels']
if 'ALL' in l:
level = LEVEL_ALL
else:
if 'DEBUG' in l:
level |= LEVEL_DEBUG
if 'INFO' in l:
level |= LEVEL_INFO
if 'WARN' in l:
l | evel |= LEVEL_WARN
if 'ERROR' in l:
level |= LEVEL_ERROR
def debug(*args, **kwargs):
global level
if level & LEVEL_DEBUG:
log.msg(*args, **kwargs)
def info(*args, **kwargs):
global level
if level & LEVEL_INFO:
log.msg(*args, **kwargs)
def warn(*args, **kwargs):
... |
mancoast/CPythonPyc_test | fail/301_pickletester.py | Python | gpl-3.0 | 35,665 | 0.001514 | import unittest
import pickle
import pickletools
import copyreg
from test.support import TestFailed, TESTFN, run_with_locale
from pickle import bytes_types
# Tests that try a number of pickle protocols should have a
# for proto in protocols:
# kind of outer loop.
protocols = range(pickle.HIGHEST_PROTOCOL + 1)
... | NT -1
69: K BININT1 255
71: J BININT -255
76: J BININT -256
81: M BININT2 65535
84: J BININT -65535
89: J BININT -65536
94: J BININT 2147483647
99: J BININT -2147483647
104: J BININT -214748364... | BINUNICODE 'abc'
118: q BINPUT 4
120: h BINGET 4
122: c GLOBAL 'copyreg _reconstructor'
146: q BINPUT 5
148: ( MARK
149: c GLOBAL '__main__ C'
161: q BINPUT 6
163: c GLOBA... |
pombredanne/todomvc-django | todo/views.py | Python | mit | 148 | 0.033784 | from django.views | .generic import TemplateView
# All todos view
class Home( TemplateView ):
# Set the view template
template_name = 'index.ht | ml' |
ovnicraft/server-tools | base_export_manager/__manifest__.py | Python | agpl-3.0 | 808 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Antiun Ingeniería S.L. - Antonio Espinosa
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': "Manage model export profiles",
'category': 'Personalization',
'version': '10.0.1.0.0',
'depends': [
'web',
],
'data': [
... | 'Ursa Information Systems, '
'Odoo Community Association (OCA)',
'website': 'https://www.tecnativa.com',
'license': 'AGPL-3',
'installable': | True,
'application': False,
}
|
moonbury/notebooks | github/Numpy/Chapter3/atr.py | Python | gpl-3.0 | 599 | 0.008347 | from __future__ import print_function
import numpy as np
h, l, c = np.loadtxt('data.csv', delimiter=',', usecols=(4, 5, 6), unpack=True)
N = 5
h = h[-N:]
l = l[-N:]
print("len(h)", len(h), "len(l)", len(l))
print("Close", c)
previousclose = c[-N -1: -1]
print("len(previousclose)", len(previousclose))
print("Previou... | [0] = np.mean(truerange)
for i in range(1, N):
| atr[i] = (N - 1) * atr[i - 1] + truerange[i]
atr[i] /= N
print("ATR", atr)
|
levythu/swift | swift/common/storage_policy.py | Python | apache-2.0 | 33,131 | 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 the... | gePolicy instance for the
index encoded in the policy_string.
"""
if '-' in policy_string:
base, policy_index = policy_string.rsplit('-', 1)
el | se:
base, policy_index = policy_string, None
policy = POLICIES.get_by_index(policy_index)
if get_policy_string(base, policy) != policy_string:
raise PolicyError("Unknown policy", index=policy_index)
return base, policy
class BaseStoragePolicy(object):
"""
Represents a storage polic... |
xod442/sample_scripts | get-xapi.py | Python | gpl-2.0 | 3,401 | 0.000588 | #!/usr/bin/env python3
###
# (C) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation t... | BILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM | , DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###
import sys
if sys.version_info < (3, 2):
raise Exception('Must use Python 3.2 or later')
import hpOneView as hpov
from p... |
jvazquez/organization | organization/job_offers/constants.py | Python | unlicense | 334 | 0 | import os
# Application constants
APP_NAME = 'job_offers'
IN | STALL_DIR = os.path.dirname(os.path.abspath(__file | __))
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_NAME = os.path.join(INSTALL_DIR, 'job_offers.log')
# Testing fixtures
JOB_OFFER_FIXTURES = os.path.join(INSTALL_DIR, "fixtures/job_offers.json")
|
saketkc/open-ehr-django | open-ehr-django-src/labs/forms.py | Python | lgpl-3.0 | 4,518 | 0.019478 | from django import forms
from open-ehr.labs.models import PatientInfo
from open-ehr.registration.forms import *
from open-ehr.report_manager.models import *
from django.forms.widgets import CheckboxSelectMultiple
class PatientInfoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.created_by = ... | wargs)
self.fields['gender'] = forms.ChoiceField(choices= (('male',('Male')),('female',('Female'))))
self.fields['patient_first_name'].label="Patient's First Name:"
self.fields['patient_last_name'].label="Patient's Last Na | me:"
self.fields['patient_dob'].label="Date of Birth:"
self.fields['report_due_on'].label="Report due on:"
self.fields['reference_doctor_name'].label="Reference Doctor Name:"
self.fields['sample_id'].label="Sample Id:"
#report_element_categories = ReportElementCategories.objects.... |
moveone/dbmail | python/bin/autoreplier.py | Python | gpl-2.0 | 3,784 | 0.026163 | #!/usr/bin/python
#
# Copyright: NFG, Paul Stevens <[email protected]>, 2005
# License: GPL
#
# $Id: autoreplier.py,v 1.4 2004/12/01 10:15:58 paul Exp $
#
# Reimplementation of the famous vacation tool for dbmail
#
#
import os,sys,string,email,getopt,shelve,time,re,smtplib
from dbmail.lib import DbmailAutoreply
def usag... | s()
body=replymsg.get_payload()
body="%s\n---\n\n%s\n" % ( body, self.getAlias() )
r | eplymsg.set_payload(body)
self.send_message(replymsg)
self.cache[u][to]=int(time.time())
def reply(self):
self.openCache()
self.do_reply()
self.closeCache()
if __name__ == '__main__':
try:
opts,args = getopt.getopt(sys.argv[1:],"u:m:a:",
... |
PRIArobotics/HedgehogServer | hedgehog/server/hardware/simulated.py | Python | agpl-3.0 | 2,565 | 0.00039 | from typing import Dict
import random
from . import HardwareAdapter, POWER
from hedgehog.protocol.messages import io
class SimulatedHardwareAdapter(HardwareAdapter):
def __init__(self, *args, simulate_sensors=False, **kwargs):
super().__init__(*args, **kwargs)
self.simulate_sensors = simulate_se... | nc def emergency_action(self, activate):
self.emergency = activate
async def get_emergency_state(self) -> bool:
return self.emergency
async def | set_io_config(self, port, flags):
self.io_configs[port] = flags
async def get_analog(self, port):
if not self.simulate_sensors:
return 0
mu, sigma = {
io.INPUT_FLOATING: (800, 60),
io.INPUT_PULLUP: (4030, 30),
io.INPUT_PULLDOWN: (80, 30),
... |
rapilabs/django-shopfront | backend/django_shopfront/wsgi.py | Python | mit | 410 | 0 | """
WSGI config for django_shopfront project.
It exposes the WSGI callabl | e as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import | get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_shopfront.settings")
application = get_wsgi_application()
|
M4rtinK/anaconda | tests/unit_tests/pyanaconda_tests/test_installation_tasks.py | Python | gpl-2.0 | 15,098 | 0.000795 | #
# Martin Kolman <[email protected]>
#
# Copyright 2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be use... | on, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
# trademarks that are incorporated in the source code or documentation are not
# subject to the GNU General Public License and may only be used or replicated
# with the express permission of Red Hat, Inc.
#
import unittest
from pyan... | ort TaskQueue
class InstallTasksTestCase(unittest.TestCase):
def setUp(self):
self._test_variable1 = 0
self._test_variable2 = 0
self._test_variable3 = 0
self._test_variable4 = None
self._test_variable5 = None
self._test_variable6 = None
self._task_started_co... |
cloudtools/troposphere | troposphere/cloudtrail.py | Python | bsd-2-clause | 2,138 | 0.001871 | # Copyright (c) 2012-2022, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
from . import AWSObject, AWSProperty, PropsDictType, Tags
from .validators import boolean
class DataResource(AWSProperty):
"""
`DataResour... | "CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"InsightSelectors": ([InsightSelector], False),
... | str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
|
joshmoore/openmicroscopy | components/tools/OmeroPy/scripts/omero/import_scripts/Populate_ROI.py | Python | gpl-2.0 | 1,244 | 0.012862 | """
components/tools/OmeroPy/scripts/omero/import_scripts/Populate_Plate_Roi.py
Uses the omero.util.populate_roi functionality to parse all the
measurement files attached to a plate, and generate server-side
rois.
params:
Plate_ID: id of the plate which should be parsed.
Copyright 2009 Glencoe Software, Inc. All... | = """Generates regions of interest from the measurement files associated with a plate
This script is executed by t | he server on initial import, and should typically not need
to be run by users.""")
factory = PlateAnalysisCtxFactory(client.getSession())
analysis_ctx = factory.get_analysis_ctx(client.getInput("Plate_ID").val)
n_measurements = analysis_ctx.get_measurement_count()
for i in range(n_measurements):
measurement_ctx = ... |
erinxocon/Text-Parsing-Function-Dispatcher | tpfd/parser.py | Python | mit | 2,830 | 0.00424 | #coding=utf-8
"""
parser.py
This contains the main Parser class that can be instantiated to create rules.
"""
from .rules import RuleMap
from .compat import basestring
class Parser(object):
"""
Parser exposes a couple methods for reading in strings.
Currently only parse_file is working.
... | r rules. Calls the associated functions when the rule
is invoked via parse found
"""
def parse_decorator(func):
"""Event decorator closure thing"""
self._parse_rule_map.add_rule(eventname, func)
return func
return parse_decorator
def | on_find(self, eventname):
"""
Decorator for rules. Calls the associated functions when the rule
is invoked via parse found
"""
def find_decorator(func):
"""Event decorator closure thing"""
self._find_rule_map.add_rule(eventname, func)
r... |
ACJTeam/enigma2 | lib/python/Components/InputDevice.py | Python | gpl-2.0 | 8,051 | 0.026581 | from config import config, ConfigSlider, ConfigSubsection, ConfigYesNo, ConfigText, ConfigInteger
from SystemInfo import SystemInfo
from fcntl import ioctl
import os
import struct
# asm-generic/ioctl.h
IOC_NRBITS = 8L
IOC_TYPEBITS = 8L
IOC_SIZEBITS = 13L
IOC_DIRBITS = 3L
IOC_NRSHIFT = 0L
IOC_TYPESHIFT = IOC_NRSHIFT+I... | ice = ""
self.createConfig()
def createConfig(self, *args):
config.inputDevices = ConfigSubsection()
for device in sorted(iInputDevices.Devices.iterkeys()):
self.currentDevice = device
#print "[InitInputDevices] -> creating config entry for device: %s -> %s " % (self.currentDevice, iInputDevices.Devices[... | lf.currentDevice)
self.currentDevice = ""
def inputDevicesEnabledChanged(self,configElement):
if self.currentDevice != "" and iInputDevices.currentDevice == "":
iInputDevices.setEnabled(self.currentDevice, configElement.value)
elif iInputDevices.currentDevice != "":
iInputDevices.setEnabled(iInputDevices... |
yaybu/touchdown | touchdown/aws/route53/alias_target.py | Python | apache-2.0 | 689 | 0 | # Copyright 2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may n | ot 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
# limitations under the Licens... |
perryl/morph | cliapp/__init__.py | Python | gpl-2.0 | 1,188 | 0 | # Copyright (C) 2011 Lars Wirzenius
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed i... | he Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
__version__ = '1.20130808'
from fmt import TextFormat
from settings import (Settings, log_group_name, config_group_name,
perf_group_name)
from runcmd import runcmd, runcmd_unchecked, shell_quote, s... | import Plugin
from pluginmgr import PluginManager
__all__ = locals()
|
valohai/minique | minique/cli.py | Python | mit | 1,399 | 0.000715 | import argparse
import logging
from typing import List, Optional
from redis import StrictRedis
from minique.compat import sentry_sdk
from minique.work.worker import Worker
def get_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--redis-url", required=True)
... | ngle-tick", action="store_true")
return parser
def main(argv: Optional[List[str]] = None) -> None:
parser = get_parser()
args = parser.parse_args(argv)
logging.basicConfig(datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO)
redis = StrictRedis.from_url(args.redis_url)
worker = Worker.for_queue_na... | .info("Worker initialized")
if sentry_sdk:
try:
sentry_sdk.init()
except Exception as exc:
worker.log.warning("Failed to initialize Sentry: %s", exc, exc_info=True)
else:
hub = sentry_sdk.hub.Hub.current
if hub and hub.client and hub.client.dsn... |
rainforestapp/destimator | destimator/tests/test.py | Python | mit | 7,733 | 0.001681 | from __future__ import print_function, unicode_literals
import os
import shutil
import zipfile
import datetime
import tempfile
import subprocess
from copy import deepcopy
import pytest
import numpy as np
from numpy.testing import assert_almost_equal
from sklearn.dummy import DummyClassifier
from destimator import De... | assert d1 != d2
meta | data_v1a = dict(metadata_v1)
metadata_v1a['metadata_version'] = 3
d1a = DescribedEstimator(clf, features, labels, features, labels, compute_metadata=False, metadata=metadata_v1a)
assert d1 != d1a
def test_from_file(self, clf_described):
save_dir = tempfile.mkdtemp()
try:
... |
planoAccess/clonedONOS | tools/test/scenarios/bin/verify-topo-devices.py | Python | apache-2.0 | 1,143 | 0.002625 | #! /usr/bin/env python
import requests
import sys
import urllib
from requests.auth import HTTPBasicAuth
if len(sys.argv) != 5:
print "usage: verify-topo-links onos-node cluster-id first-index last-index"
sys.exit(1)
node = sys.argv[1]
cluster = sys.argv[2]
first = int(sys.argv[3])
last = int(sys.argv[4])
f... | t lookingFor
| for arrayIndex in range(0, len(topoJson["devices"])):
device = topoJson["devices"][arrayIndex]
if device == lookingFor:
found = found + 1
print "Match found for " + device
break
if found == last - first:
sys.exit(0)
print "Found " + str(found) + " matches, n... |
michellab/Sire | wrapper/Squire/__init__.py | Python | gpl-2.0 | 155 | 0.012903 | #############################
##
## The Sq | uire module
##
## (C) Christopher Woods
##
import Sire.MM
import Sire.System
from | Sire.Squire._Squire import *
|
YAtOff/python0-reloaded | projects/hard/phonebook/phonebook.py | Python | mit | 5,283 | 0.000934 | """
Телефонен указател
Задачата е да се напишат функции, които работят като телефонен указател.
Телефонният указател трябва да се съхранява във файл.
Телефоните се представят като речник с две полете:
- `name` - име на човек
- `phone` - телефоне номер
Например:
{
'name': 'Ivan',
'phone': '... | съка с контакти,
като запазва списъка сортиран по име.
>>> contacts = []
>>> insert_contact(contacts, 'Pesho', 1)
>>> insert_contact(contacts, 'Gosho', 2)
>>> contacts[0]['name']
'Gosho'
>>> contacts[1]['name']
'Pesho'
>>> insert_contact(contacts, 'Boby', 3)
>>> contacts[0]['nam... | >> contacts[2]['name']
'Pesho'
>>> insert_contact(contacts, 'Tosho', 4)
>>> contacts[3]['name']
'Tosho'
"""
pass
def do_command(command, *args):
result = {
'set': set_phone,
'remove': remove_phone,
'find': find_phone
}[command](*args)
if result:
prin... |
anbangr/trusted-juju | juju/providers/orchestra/tests/test_files.py | Python | agpl-3.0 | 6,631 | 0 | from cStringIO import StringIO
from twisted.internet.defer import fail, succeed
from twisted.web.error import Error
from juju.errors import FileNotFound, ProviderError, ProviderInteractionError
from juju.lib.testing import TestCase
from juju.providers.orchestra import MachineProvider
from .test_digestauth import Get... | _file_storage(custom_config)
def test_no_auth_error(self):
self.add_plain("peregrine", "PUT", "", "croissant", 999)
fs = self.get_file_storage()
d = fs.put("peregrine", StringIO("croissant"))
self.assertFailure(d, ProviderError)
def verify(error):
self.assertIn(... | n("peregrine", "PUT", "", "croissant", 201)
fs = self.get_file_storage()
d = fs.put("peregrine", StringIO("croissant"))
d.addCallback(self.assertEquals, True)
return d
def test_no_auth_204(self):
self.add_plain("peregrine", "PUT", "", "croissant", 204)
fs = self.get_... |
pagekite/PyPagekite | droiddemo.py | Python | agpl-3.0 | 4,921 | 0.009348 | #!/usr/bin/python -u
from __future__ import absolute_import
from __future__ import print_function
#
# droiddemo.py, Copyright 2010-2013, The Beanstalks Project ehf.
# http://beanstalks-project.net/
#
# This is a proof-of-concept PageKite enabled HTTP server for Android.
# It has bee... | sl4a/scripts/droiddemo.py'
#
#############################################################################
#
# 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
# Lice... | rogram 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 General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# ... |
solanolabs/rply | tests/test_ztranslation.py | Python | bsd-3-clause | 2,200 | 0.000455 | import py
try:
| from pypy.rpython.test.test_llinterp import interpret
except ImportError:
py.test.skip('Needs PyPy to be on the PYTHONPATH')
from rply import ParserGenerator, Token
from rply.errors import ParserGeneratorWarning
from .base import BaseTests
from .utils import FakeLexer, BoxInt, ParserState
class TestTran | slation(BaseTests):
def run(self, func, args):
return interpret(func, args)
def test_basic(self):
pg = ParserGenerator(["NUMBER", "PLUS"])
@pg.production("main : expr")
def main(p):
return p[0]
@pg.production("expr : expr PLUS expr")
def expr_op(p):... |
jleclanche/pywow | game/currencies/__init__.py | Python | cc0-1.0 | 702 | 0.029915 | # -*- coding: utf-8 -*-
"""
Enchants
- CurrencyTypes.dbc
"""
from .. import *
class Currency(Mod | el):
pass
class CurrencyTooltip(Tooltip):
def tooltip(self):
self.append("name", self.obj.getName())
self.append("description", self.obj.getDescription(), color=YELLOW)
return self.flush()
Currency.Tooltip = CurrencyTooltip
class CurrencyProxy(object):
"""
WDBC proxy for currencies
"""
def __init__(self... | ypes.dbc", build=-1)
def get(self, id):
return self.__file[id]
def getDescription(self, row):
return row.description_enus
def getName(self, row):
return row.name_enus
Currency.initProxy(CurrencyProxy)
|
tommy-u/chaco | chaco/tests/test_colormapped_scatterplot.py | Python | bsd-3-clause | 2,802 | 0 | import unittest
from unittest2 import skip
from numpy import alltrue, arange
from enable.compiled_path import CompiledPath
# Chaco imports
from chaco.api import (ArrayDataSource, ColormappedScatterPlot, DataRange1D,
LinearMapper, PlotGraphicsContext, jet)
class TestColormappedScatterplot(unit... | DataSource(arange(10))
self.size_data = arange(10)
self.index_range = DataRange1D()
self.index_range.add(self.index)
self.index_mapper = LinearMapper(range=self.index_range)
self.value_range = DataRange1D()
self.value_range.add(self.value)
self.value_mapper = Li... | taRange1D()
self.color_range.add(self.color_data)
self.color_mapper = jet(self.color_range)
self.scatterplot = ColormappedScatterPlot(
index=self.index,
value=self.value,
index_mapper=self.index_mapper,
value_mapper=self.value_mapper,
... |
ManuelLR/Notmail_Bot | repository/repository.py | Python | gpl-3.0 | 4,697 | 0.00149 | # Copyright 2017 by Notmail Bot contributors. All rights reserved.
#
# This file is part of Notmail Bot.
#
# Notmail Bot 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 Lice... | user = User(id, parse_json_to_accounts(result['accounts']))
return user
def update_user(self, user):
users = self.db.table('Users')
query = Query()
users.update({'id': user.id, 'accounts': parse_accounts_to_json(user.accounts)},
query.id == user.id)
... | arse_json_to_accounts(a['accounts'])))
return res
def remove_user(self, user_id):
users = self.db.table('Users')
query = Query()
users.remove(query.id == user_id)
def get_accounts_of_user(self, user):
user = self.search_user(user.id)
return user.accounts
de... |
haddocking/disvis | disvis/main.py | Python | apache-2.0 | 23,344 | 0.004112 | #! usr/bin/python
from __future__ import print_function, division, absolute_import
from os import remove
from os.path import join, abspath
from sys import stdout, exit
from time import time
import multiprocessing as mp
from argparse import ArgumentParser
import logging
import numpy as np
from disvis import DisVis, PD... | g fixed chain.')
p.add_argument('ligand', type=file,
help='PDB-file containing scanning chain.')
p.add_argument('restraints', type=file,
help='File containing the distance restraints')
p.add_argument('-a', ' | --angle', dest='angle', type=float, default=15, metavar='<float>',
help='Rotational sampling density in degrees. Default is 15 degrees.')
p.add_argument('-vs', '--voxelspacing', dest='voxelspacing', metavar='<float>',
type=float, default=1,
help='Voxel spacing of search grid in ... |
thouska/spotpy | spotpy/examples/getting_started.py | Python | mit | 1,975 | 0.013671 | # -*- coding: utf-8 -*-
'''
Copyright 2015 by Tobias Houska
This file is part of Statistical Parameter Estimation Tool (SPOTPY).
:author: Tobias Houska
This class holds the example code from the getting_started web-documention.
'''
from __future__ import print_function, division, absolute_import, unicode_literals
# G... | to your working storage
from spotpy.examples.spot_setup_rosenbrock import spot_setup # Import the two dimensional Rosenbrock example
#The example comes along with parameter boundaries, the Rosenbrock function, the optimal value of the function and RMSE as a likelihood.
#So we can directly start to analyse the Rosenb... | # Give Monte Carlo algorithm the example setup and saves results in a RosenMC.csv file
#spot_setup.slow = True
sampler = spotpy.algorithms.mc(spot_setup(), dbname='RosenMC', dbformat='ram')
#Now we can sample with the implemented Monte Carlo algortihm:
sampler.sample(10000) # Sample 1... |
scalable-networks/ext | pybombs/app_store.py | Python | gpl-2.0 | 5,226 | 0.020666 | #!/usr/bin/env python
#
# Copyright 2013 Tim O'Shea
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# P... | ));
button.setAutoRaise(True);
self.connect(action, QtCore.SIGNAL("triggered()"), callback);
self.lay.addWidget(button, self.idx/self.width, self.idx%self.width);
self.idx = | self.idx + 1;
class Installer:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "installing "+ self.name;
install(self.name);
self.parent.refresh();
class Remover:
def __init__(self, parent, name):
self.paren... |
navnorth/LR-Data | src/payload_schema/__init__.py | Python | apache-2.0 | 265 | 0 |
from .fe | tch import FetchParser
from .json_ld import JsonLdParser
from .lom import LomParser
from .lrmi import LrmiParser
from .nsdl_dc import NsdlDcParser
__all__ = [
'FetchParser',
'JsonLdParser',
'LomParse | r',
'LrmiParser',
'NsdlDcParser',
]
|
ravik/mapbox-baseSDK | tests/test_geocoder.py | Python | mit | 12,916 | 0.004026 | # coding=utf-8
import json
import re
import responses
import pytest
import mapbox
def test_geocoder_default_name():
"""Default name is set"""
geocoder = mapbox.Geocoder()
assert geocoder.name == 'mapbox.places'
def test_geocoder_name():
"""Named dataset name is set"""
geocoder = mapbox.Geocode... | )
response = mapbox.Geocoder(
access_token='pk.test').reverse(
lon=lon, lat=lat,
types=('address', 'country', 'place', 'poi.landmark', 'postcode', 'region'))
assert response.status_code == 200
assert response.json()['query'] == [lon, lat]
|
@responses.activate
def test_geocoder_forward_proximity():
"""Proximity parameter works"""
responses.add(
responses.GET,
'https://api.mapbox.com/geocoding/v5/mapbox.places/1600%20pennsylvania%20ave%20nw.json?proximity=0.0,0.0&access_token=pk.test',
match_querystring=True,
body=... |
MarcAndreJean/PCONC | Modules/04-02-CPU.py | Python | mit | 15,906 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Projet : Editeur, Compilateur et Micro-Ordinateur pour
un langage assembleur.
Nom du fichier : 04-02-CPU.py
Identification : 04-02-CPU
Titre : CPU
Auteurs : Francis Emond, Malek Khattech,
... | def __init__(self, bus):
"""
Constructeur de la classe CPU.
Le constructeur initialise les composants du CPU dont l'ALU.
Elle s'occupe aussi de lier le CPU avec le bus en entrée.
:example:
>>> test = CPU(modBus.Bus())
:param bus: Le bus... | """
self.event = False
# Connexion avec le bus.
self.bus = bus
self.bus.register(self)
# Création de l'ALU.
self.alu = modALU.ALU()
# Création des registres.
self.regP = 0x0000 # Program counter.
self.regI = 0x0000 # Instruction register.
... |
kkoci/orthosie | inventory/migrations/0002_auto_20151206_2111.py | Python | gpl-3.0 | 438 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-07 02:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migratio | n(migrations.Migration):
dependencies = [
('inventory', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='produce',
name='plu',
| field=models.IntegerField(unique=True),
),
]
|
KhronosGroup/COLLADA-CTS | StandardDataSets/collada/library_visual_scenes/visual_scene/node/_reference/_reference_node_translate_xyz_cube/_reference_node_translate_xyz_cube.py | Python | mit | 3,826 | 0.007057 |
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ... | OSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
# See Core.Logic.FJudgementCont... | aseline: just verifies that the standard steps did not crash.
# JudgeSuperior: also verifies that the validation steps are not in error.
# JudgeExemplary: same as intermediate badge.
# We import an assistant script that includes the common verifications
# methods. The assistant buffers its checks, so that running... |
MaxVanDeursen/tribler | Tribler/Test/Community/Multichain/__init__.py | Python | lgpl-3.0 | 77 | 0 | """
This pa | ckage conta | ins tests for the Multichain community in Tribler.
"""
|
zhangyubaka/tweepy_favbot | bot.py | Python | mit | 923 | 0.006501 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAut | hHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def tdata():
userid = str(input("Please input id who you want fav attack\n"))
count = input("input number you want to fav!\n")
return userid, count
def main():
t = tdata()
tl... | orite, tl)
except tweepy.error.TweepError as e:
if e.args[0][0]['code'] == 139:
print("You have already favorited this status! \n")
else:
print(e.reason)
finally:
print("Done!")
if __name__ == "__main__":
main()
|
googleapis/python-datacatalog | samples/generated_samples/datacatalog_v1_generated_data_catalog_modify_entry_overview_sync.py | Python | apache-2.0 | 1,496 | 0.000668 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | nitialize request argu | ment(s)
request = datacatalog_v1.ModifyEntryOverviewRequest(
name="name_value",
)
# Make the request
response = client.modify_entry_overview(request=request)
# Handle the response
print(response)
# [END datacatalog_v1_generated_DataCatalog_ModifyEntryOverview_sync]
|
hiteshgarg14/Django-Social-Website | bookmarks/common/decorators.py | Python | mit | 478 | 0.004184 | from django.http import HttpResponseBadRequest, HttpResponse
"""
Build custom deco | rators for your views if you find that you are repeating
the same checks in multiple views.
"""
def ajax_required(f):
def wrap(request, *args, **kwargs):
if not request.is_ajax():
#return HttpResponse("hi")
return HttpRespo | nseBadRequest()
return f(request, *args, **kwargs)
wrap.__doc__ = f.__doc__
wrap.__name__ = f.__name__
return wrap
|
gforcada/jenkins-job-builder | jenkins_jobs/sphinx/yaml.py | Python | apache-2.0 | 4,991 | 0 | # Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# 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... | d_signature(self, encoding=None):
docstrings = Documenter.get_doc(self, encoding, 2)
if len(docstrings) != 1:
return
doclines = docstring | s[0]
setattr(self, '__new_doclines', doclines)
if not doclines:
return
# match first line of docstring against signature RE
match = yaml_sig_re.match(doclines[0])
if not match:
return
name = match.group(1)
# ok, now jump over remaining empt... |
nwjs/chromium.src | third_party/android_deps/libs/com_google_firebase_firebase_messaging/3pp/fetch.py | Python | bsd-3-clause | 1,389 | 0.00072 | #!/usr/bin/env python
# Copyright 2021 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.
# This is generated, do not edit. Update BuildConfigGenerator.groovy and
# 3ppFetch.template instead.
from __future__ import print_fun... | ported extension for %s' % _FILE_URL)
partial_manifest = {
'url': [_FILE_URL],
'name': [_FILE_NAME],
'ext': ext,
}
print(json.dumps(par | tial_manifest))
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers()
latest = sub.add_parser("latest")
latest.set_defaults(func=lambda _opts: do_latest())
download = sub.add_parser("get_url")
download.set_defaults(
func=lambda _opts: get_download_url(os.environ['_3PP_... |
sigma-random/pwnypack | tests/__init__.py | Python | mit | 90 | 0 | i | mport pwny
def setup():
pwny.target.assume(pwny.Target(arch=pwny.Target.Arch.x | 86))
|
retoo/pystructure | tests/python/typeinference/import_star_definitions.py | Python | lgpl-2.1 | 74 | 0.027027 | class Class(object):
pass
def func():
return 3.14
CONSTANT = 42 | ||
McSinyx/hsg | others/other/nuoc.py | Python | gpl-3.0 | 941 | 0.002125 | #!/usr/bin/env python3
from heapq import heapify, heappop, heappush
with open('NUOC.INP') as f:
m, n = map(int, f.readline().split())
height = [[int(i) for i in line.split()] for line in f]
queue = ([(h, 0, i) for i, h in enumerate(height[0])]
+ [(h, m - 1, i) for i, h in enumerate(height[-1])]
... | n range(m)]
+ [(height[i][-1], i, n - 1) for i in range(m)])
heapify(queue)
visited = ([[True] * n]
+ [[True] + [False] * (n - 2) + [True] for _ in range(m - 2)]
+ [[True] * n])
result = 0
while queue:
h, i, j = h | eappop(queue)
for x, y in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1):
if 0 <= x < m and 0 <= y < n and not visited[x][y]:
result += max(0, h - height[x][y])
heappush(queue, (max(height[x][y], h), x, y))
visited[x][y] = True
with open('NUOC.OUT', 'w') as f: print(... |
srijanrodo/telegram-bots-python-api | telegram.py | Python | gpl-2.0 | 8,175 | 0.050765 | import requests
from tel_types import User, Message, Update, UserProfilePhotos
import time
base_url = 'https://api.telegram.org/bot'
class Telegram:
def __init__(self, token):
self.call_url = base_url + token + '/'
self.token = token
self.req_timeout = 5
self.text_limit = 4096
self.last_error = ''
self.... | != dict:
return None
data = args[0]
if 'reply_markup' in data:
data['reply_markup'] = data['reply_markup'].json_str
tmp = self.__method_create_json__('sendMe | ssage', data = data)
if tmp is None:
return None
if tmp['ok'] is False:
self.last_error = tmp['description']
return None
return Message(tmp['result'])
def sendLargeMessage(self, **data):
if 'text' not in data:
return None
text = data['text']
while len(text) > self.text_limit:
send = self.spl... |
sayan801/indivo_server | indivo/tests/data/record.py | Python | gpl-3.0 | 1,535 | 0.013029 | from indivo.models import Record, Demographics
from base import *
class TestRecord(TestModel):
model_fields = ['label', 'demographics', 'owner', 'external_id']
model_class = Record
def _setupargs(self, label, demographics=None, owner=None, external_id=None, extid_principal_key=None):
self.label = ... | [
{'label':'testing_record_label',
'demographics':ForeignKey('demographics', 'TEST_DEMOGRAPHICS', 0),
'owner':ForeignKey('account', 'TEST_ACCOUNTS', 0),
},
{'label':'test_record_label | 2',
'demographics':ForeignKey('demographics', 'TEST_DEMOGRAPHICS', 1),
'owner':ForeignKey('account', 'TEST_ACCOUNTS', 0),
},
{'label':'empty_record',
},
{'label':'bob',
'owner':ForeignKey('account', 'TEST_ACCOUNTS', 0),
},
{'label':'jane',
'owner':ForeignKey('account', 'TE... |
paulfitz/sheetsite | sheetsite/tasks/notify.py | Python | mit | 2,767 | 0.001084 | from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import json
import os
from sheetsite.site_queue import app
import smtplib
@app.task
def notify_one(email, subject, page, text):
print("send [%s] / %s / %s" % (email, subject, page))
server_ssl = smtplib.SMTP_SSL("smtp.gmail.... | ext
template = env.get_template('update.txt')
page_text = template.render(site_params)
for target in notifications['rows']:
email = target.get('EMAIL', None)
if email is None:
email = target.get('email', None)
if email is not None:
if site_params['no_notify']... | email))
else:
notify_one.delay(email=email,
subject="update to {}".format(site_params.get('name',
'directory')),
page=page,
... |
ahmad88me/PyGithub | github/GithubApp.py | Python | lgpl-3.0 | 6,426 | 0.004669 | ############################ Copyrights and license ############################
# #
# Copyright 2020 Raju Subramanian <[email protected]> #
# ... | This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under ... | Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY ... |
proximate/proximate | messageboard.py | Python | bsd-3-clause | 15,997 | 0.002688 | #
# Proximate - Peer-to-peer social networking
#
# Copyright (c) 2008-2011 Nokia Corporation
#
# All rights reserved.
#
# This software is licensed under The Clear BSD license.
# See the LICENSE file for more details.
#
from gobject import timeout_add_seconds, source_remove
from random import random, randrange
from tim... | warning('msgboard: Invalid meta: %s\n' % str(meta))
continue
metas.append(meta)
return metas
def got_query_results(self, user, reply, ctx):
metas = self.process_results(reply)
self.msg_cache(user, metas)
for meta in metas:
if self.is_hot(met... | tx in self.searchctxs:
sctx.process(user, metas)
def handle_message(self, user, sm):
""" Handle messages that were found from other users' fileshares """
if not self.validate_message(sm):
sm['ttl'] = 0
warning('msgboard: Invalid message: %s\n' % str(sm))
... |
openstack/python-muranoclient | muranoclient/tests/unit/osc/v1/fakes.py | Python | apache-2.0 | 823 | 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 the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie | d. See the
# License for the specific language governing permissions and limitations
# under the License.
from osc_lib.tests import utils
from unittest import mock
class TestApplicationCatalog(utils.TestCommand):
def setUp(self):
super(TestApplicationCatalog, self).setUp()
self.app.client... |
TorleifHensvold/ITGK3 | Oving5/torleif/07_Forenkling_av_brøker.py | Python | mit | 706 | 0.04416 |
def forenkling(a,b):
while b!=0:
| gammel_b=b
b=a%b
a=gammel_b
#print(a,b)
return a
print(forenkling(30,20))
print(forenkling(10,2))
def gcd(a,b):
a=forenkling(a,b)
return a
def reduce_fraction(a,b):
divisor=forenkling(a,b)
a=int(a/divisor)
b=int(b/divisor)
return a,b
def m... | if a!=b:
print('Forkortningen av brøken gir: ',a,'/',b,sep='')
else:
print('Forkortningen av brøken gir: 1')
main()
|
LamCiuLoeng/vat | vatsystem/model/__init__.py | Python | mit | 2,266 | 0.004854 | # -*- coding: utf-8 -*-
"""The application's model objects"""
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
#from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
# Global session manager: DBSession() returns the Thread-l... | to spare some typing.
# You can have a query property on all your model classes by doing this:
# DeclarativeBase.query = DBSession.query_property()
# Or you can use a session-aware mapper as it was used in TurboGears 1:
# DeclarativeBase = declarative_base(mapper=DBSession.mapper)
# Global metadata.
# The default met... | = DeclarativeBase.metadata
metadata2 = DeclarativeBase2.metadata
# If you have multiple databases with overlapping table names, you'll need a
# metadata for each database. Feel free to rename 'metadata2'.
#metadata2 = MetaData()
#####
# Generally you will not want to define your table's mappers, and data objects
# he... |
AntSharesSDK/antshares-python | sdk/AntShares/Core/IssueTransaction.py | Python | apache-2.0 | 922 | 0 | # -*- coding:utf-8 -*-
"""
Description:
Issue | Transaction
Usage:
from AntShares.Core.IssueTransaction import IssueTransaction
"""
from AntShares.Core.AssetType import AssetType
from AntShares.Helper import *
from AntShares.Core.Transaction import Transaction
from AntShares.Core.TransactionType import TransactionType
from random import randint
class IssueT... | sactionType = TransactionType.IssueTransaction # 0x40
self.Nonce = self.genNonce()
def genNonce(self):
return random.randint(268435456, 4294967295)
def getScriptHashesForVerifying(self):
"""Get ScriptHash From SignatureContract"""
pass
def serializeExclusiveData(self, wri... |
rpatterson/instrumenting | src/instrumenting/profilehandler.py | Python | gpl-2.0 | 4,513 | 0.000886 | import sys
import logging
import profile
import pstats
try:
import cStringIO as StringIO
StringIO # pyflakes
except ImportError:
import StringIO
from instrumenting import utils
class BaseProfilingHandler(utils.InstrumentingHandler):
"""
Python logging handler which profiles code.
It can al... | red to start the profiler and it is
already started, a warning message is logged and it is left
running. Similarly, if the handler is configured to stop the
profiler and it is already stopped, a warning message is
logged and it is no | t started.
In order to avoid surprising performance impacts, if the
handler is configured such that it enables and disables the
profiler for the same single log message, an error message is
logged but the profiler is still disabled.
"""
started = False
if self.s... |
Pyroseza/Random | test.py | Python | mit | 23 | 0.043478 | print("h | ello world!")
| |
unibet/unbound-ec2 | unbound_ec2/config.py | Python | isc | 3,425 | 0.00438 | import ConfigParser
import os.path
import ast
DEFAULT_ | CONF_FILE = '/etc/unbound/unbound_ec2.conf'
DEFAULT_AWS_REGION = 'us-west-1'
DEFAULT_ZONE = 'zone.tld'
DEFAULT_REVERSE_ZONE = '127.in-addr.arpa'
DEFAULT_TTL = '300'
DEFAULT_CACHE_TTL = '30'
DEFAULT_SERVER_TYPE = 'caching'
DEFAULT_LOOKUP_TYPE = 'cache'
DEFAULT_LOOKUP_TAG_NAME_INCLUDE_DOMAIN = 'True'
DEFAULT_LOOKUP_FILTE... | DED_ZONES = ''
class UnboundEc2Conf(object):
"""Configuration parser for Unbound EC2 module.
"""
def __init__(self, conf_file=None):
self.config = ConfigParser.ConfigParser()
self.conf_file = conf_file if conf_file else os.environ.get('UNBOUND_EC2_CONF',
... |
clawpack/clawpack-4.x | doc/sphinx/example-acoustics-2d/1drad/setrun.py | Python | bsd-3-clause | 5,754 | 0.012165 | """
Module to set up run time parameters for Clawpack.
The values set in the function setrun are then written out to data files
that will be read in by the Fortran code.
"""
import os
from pyclaw import data
#------------------------------
def setrun(claw_pkg='classic'):
#------------------------------
... | -----------
# if dt_variable==1: variable time steps used based on cfl_desired,
# if dt_variable==0: fixed time steps dt = dt_initial will always be used.
clawdata.dt_variable = 1
# Initial time step for variable dt.
# If dt_variable==0 then dt=dt_initial for all steps:
clawdata.dt_initi... |
# Max time step to be allowed if variable dt used:
clawdata.dt_max = 1e+99
# Desired Courant number if variable dt used, and max to allow without
# retaking step with a smaller dt:
clawdata.cfl_desired = 1.0
clawdata.cfl_max = 1.0
# Maximum number of time steps to allow between... |
golden1232004/webrtc_new | tools/python_charts/webrtc/main.py | Python | gpl-3.0 | 6,301 | 0.011903 | #!/usr/bin/env python
# Copyright (c) 2011 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. ... | to be displayed on the resulting page.
messages = []
# Load the page HTML template.
try:
f = open(page_template_filename)
page_template = f.read()
f.close()
except IOError as e:
ShowErrorPage('Cannot open page template file: %s<br>Details: %s' %
| (page_template_filename, e))
return
# Read data from external Python script files. First check that they exist.
for filename in data_filenames:
if not os.path.exists(filename):
messages.append('Cannot open data file: %s' % filename)
data_filenames.remove(filename)
# Read data from all e... |
potash/drain | bin/run_step.py | Python | mit | 692 | 0.001445 | import sys
from os.path import dirname
import drain.step, drain.serialize
from drain.drake import is_target_filename, is_step_filename
if len(sys.argv) == 1:
raise ValueError('Need at least one argument')
args = sys.argv[1:]
dr | ain.PATH = dirname(dirname(dirname(args[0])))
if is_target_filename(args[0]):
output = drain.serialize.load(args[0])
args = args[1:]
else:
output = None
if not is_step_filename(args[0]):
raise ValueError('Need a step to run')
step = drain.serialize.load(args[0])
inputs = []
for i in args[1:]:
i | f is_step_filename(i) or is_target_filename(i):
inputs.append(drain.serialize.load(i))
step.execute(output=output, inputs=inputs)
|
bit-trade-one/SoundModuleAP | lib-src/lv2/sratom/waflib/Tools/icc.py | Python | gpl-2.0 | 890 | 0.057303 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,sys
from waflib.Tools import ccroot,ar,gcc
from waflib.Configure import conf
@conf
def find_icc(conf):
if sys.platform=='cygwin':
conf.fatal('The Intel ... | c=conf.cmd_to_list(cc)
conf.get_cc_ver | sion(cc,icc=True)
v['CC']=cc
v['CC_NAME']='icc'
def configure(conf):
conf.find_icc()
conf.find_ar()
conf.gcc_common_flags()
conf.gcc_modifier_platform()
conf.cc_load_tools()
conf.cc_add_flags()
conf.link_add_flags()
|
sagark/tsdb-perf-test | tests/insertlongstream.py | Python | bsd-2-clause | 1,776 | 0.013514 | #Java/SQL stuff
from java.lang import *
#Grinder stuff
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
#misc
import time
import sys
#project specific
from framework import TSdata_w, TSdata_h, importstrs
#import relevant t_DATABASENAME depending on settings in grinder.properties
in... | er.info("Insertion finished at: " + str(time.time()))
self.testdb.close_all()
grinder.stopThisWorkerThread()
res = self.testdb.run_query_all()
grinder.logger.info("Query Results as (start time, end time, "
"completion" +
... | " time): (" + str(res[0]) + ", " + str(res[1]) +
", " + str(res[2]) + ")")
#log db size
size = self.testdb.get_db_size()
grinder.logger.info("The database size is now " + size + " bytes.")
self.testdb.reset_conn_state()
|
epawlowska/whylog | whylog/config/consts.py | Python | bsd-3-clause | 247 | 0 | class YamlFileNames(object):
rules = 'rules.yaml'
parsers = 'parsers.yaml'
default_log_typ | es = 'log_types.yaml'
unix_log_types = 'unix_log_types.yaml'
windows_log_types = 'win | dows_log_types.yaml'
settings = 'settings.yaml'
|
scardine/image_size | setup.py | Python | mit | 776 | 0.001289 |
import codecs
from setuptools import setup
VERSION = '0.2.0'
def read_long_description():
long_desc = []
with codecs.open('README.rst', 'r', 'utf8') as longdesc:
long_desc.append(longdesc.read())
with codecs.open('HISTORY.rst', 'r', 'utf8') as history:
long_desc.appe | nd(history.read())
return u'\n\n'.join(long_desc)
LONG_DESCRIPTION = read_long_description()
setup(
name='get_image_size',
url='https://github.com/scardine/image_size',
version=VERSION,
long_description=LONG_DESCRIPTION,
author='github.com/scardine',
author_email=' ',
license='MIT',
... | sole_scripts': [
'get-image-size = get_image_size:main',
],
},
)
|
bpsinc-native/src_third_party_chromite | scripts/pushimage.py | Python | bsd-3-clause | 18,246 | 0.006577 | # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ChromeOS image pusher (from cbuildbot to signer).
This pushes files from the archive bucket to the signer bucket and marks
artifacts for signing (... | Full path to the instruction file us | ing |image_type| and |self.board|.
"""
if image_type == image_type.upper():
name = image_type
elif image_type == 'recovery':
name = self.board
else:
name = '%s.%s' % (self.board, image_type)
return os.path.join(signing.INPUT_INSN_DIR, '%s.instructions' % name)
@staticmethod
d... |
shailcoolboy/Warp-Trinity | ResearchApps/Measurement/examples/TxPower_vs_BER/warpnet_experiment_structs.py | Python | bsd-2-clause | 5,510 | 0.023775 | # WARPnet Client<->Server Architecture
# WARPnet Parameter Definitions
#
# Author: Siddharth Gupta
import struct, time
from warpnet_common_params import *
from warpnet_client_definitions import *
from twisted.internet import reactor
import binascii
# Struct IDs
STRUCTID_CONTROL = 0x13
STRUCTID_CONTROL_ACK = 0x14
STR... | some basic parameters to pass to the WARP board. The local variable can be accessed
# globally by calling ControlStruct.txPower etc. The struct must also understand the conversion from integer values to binary
# using the | prepToSend function; it will be provided with the nodeID.
# typedef struct {
# char structID;
# char nodeID;
# char txPower;
# char channel;
# char modOrderHeader;
# char modOrderPayload;
# short reserved;
# int pktGen_period;
# int pktGen_length;
# } warpnetControl;
class ControlStruct(ClientStruc... |
kasper190/SPAforum | accounts/forms.py | Python | mit | 2,436 | 0.002053 | from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import ugettext_lazy as _
User = get_user_model()
class AdminUserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widg... | mmit:
self.user.save()
return | self.user |
amenonsen/ansible | lib/ansible/modules/network/fortios/fortios_system_email_server.py | Python | gpl-3.0 | 12,462 | 0.001284 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | port:
description:
- SMTP server port.
type: int
reply_to:
description:
- Reply-To email address.
type: str
security:
| description:
- Connection security used by the email server.
type: str
choices:
- none
- starttls
- smtps
server:
description:
- SMTP server IP address or host... |
em92/quakelive-local-ratings | qllr/blueprints/player/methods.py | Python | agpl-3.0 | 6,371 | 0.000942 | import json
from functools import reduce
from typing import Optional
from asyncpg import Connection
from qllr.common import DATETIME_FORMAT, clean_name, convert_timestamp_to_tuple
from qllr.db import cache
from qllr.exceptions import MatchNotFound, PlayerNotFound
from qllr.settings import MOVING_AVG_COUNT
async def... | m_id
WHERE p.steam_id = $1
"""
result = await con.fetchval(query, steam_id)
if result is None:
raise PlayerNotFound(steam_id)
result["ratings"] = list(map(choose_rating_values, result["ratings"]))
# weapon stats (frags + acc)
query = """
SELECT array_agg(json_build_object(
... | on_id,
CASE
WHEN SUM(shots) = 0 THEN 0
ELSE CAST(100. * SUM(hits) / SUM(shots) AS INT)
END AS accuracy
FROM (
SELECT weapon_id, frags, hits, shots
FROM scoreboards_weapons sw
LEFT JOIN ( -- TODO: need to change from LEFT... |
pombredanne/logbook | logbook/notifiers.py | Python | bsd-3-clause | 11,853 | 0.000169 | # -*- coding: utf-8 -*-
"""
logbook.notifiers
~~~~~~~~~~~~~~~~~
System notify handlers for OSX and Linux.
:copyright: (c) 2010 by Armin Ronacher, Christopher Grebs.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import base64
from time import time
from logbook.base import N... | ROR
def get_priority(self, record):
"""Returns the priority flag for Gr | owl. Errors and criticals are
get highest priority (2), warnings get higher priority (1) and the
rest gets 0. Growl allows values between -2 and 2.
"""
if record.level >= ERROR:
return 2
elif record.level == WARNING:
return 1
return 0
def em... |
SoftwareEngineeringToolDemos/ICSE-2011-Checker-Framework | release/release_push.py | Python | gpl-2.0 | 24,373 | 0.020843 | #!/usr/bin/env python
# encoding: utf-8
"""
release_push.py
Created by Jonathan Burke on 2013-12-30.
Copyright (c) 2015 University of Washington. All rights reserved.
"""
#See README-maintainers.html for more information
from release_vars import *
from release_utils import *
from sanity_checks import *
import urll... | ar" ),
pgp_user, pgp_passphrase )
mvn_sign_and_deploy_all( SONATYPE_OSS_URL, SONATYPE_STAGING_REPO_ID, JDK7_BINARY_RELEASE_POM, JDK7_BINARY,
os.path.join(MAVEN_RELEASE_DIR, mvn_dist, "jdk7-source.jar" ),
os.path.join(MAVEN_REL... | loy_all( SONATYPE_OSS_URL, SONATYPE_STAGING_REPO_ID, JDK8_BINARY_RELEASE_POM, JDK8_BINARY,
os.path.join(MAVEN_RELEASE_DIR, mvn_dist, "jdk8-source.jar" ),
os.path.join(MAVEN_RELEASE_DIR, mvn_dist, "jdk8-javadoc.jar" ),
pgp_user, pgp_... |
qedsoftware/commcare-hq | corehq/apps/export/tests/test_table_configuration.py | Python | bsd-3-clause | 10,403 | 0.000481 | from django.test import SimpleTestCase
from corehq.apps.export.const import USERNAME_TRANSFORM
from corehq.apps.export.models import (
DocRow,
RowNumberColumn,
PathNode,
ExportRow,
ScalarItem,
ExportColumn,
TableConfiguration,
)
class TableConfigurationTest(SimpleTestCase):
def test_... | eConfiguration(path=[])
self.assertEqual(
table._get_sub_documents(
{'foo': 'a'},
0
),
| [
DocRow(row=(0,), doc={'foo': 'a'})
]
)
def test_simple_repeat(self):
table = TableConfiguration(
path=[PathNode(name="foo", is_repeat=True)]
)
self.assertEqual(
table._get_sub_documents(
{
'fo... |
somini/gpodder | src/gpodder/query.py | Python | gpl-3.0 | 5,258 | 0.001331 | # -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2014 Thomas Perl and the gPodder Team
#
# gPodder 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... | ery)
def filter(self, episodes):
return filter(self.match, episodes)
def UserEQL(query):
"""EQL wrapper for user input
Automatically adds missing quotes around a
non-EQL string for us | er-based input. In this
case, EQL queries need to be enclosed in ().
"""
if query is None:
return None
if query == '' or (query and query[0] not in "(/'\""):
return EQL("'%s'" % query)
else:
return EQL(query)
|
trun/redux | redux/internal/scheduler.py | Python | mit | 5,911 | 0.00203 | from greenlet import greenlet
import os
from sandbox import Sandbox, SandboxConfig
from redux.internal.exceptions import RobotDeathException
import traceback
# this is just for testing
LOADER_CODE_TEST = """
import time
while True:
try:
print 'running... %s' % str(rc)
time.sleep(1)
print 'd... | = game_world
def yield_execution(self):
# TODO yield bonus
Scheduler.instance().end_thread()
def interface(self):
""" |
Returns an encapsulated version of the controller that can safely be
passed to the sandboxed player code.
"""
this = self
class _interface(object):
def __init__(self):
self._robot = this.robot.interface() # TODO robot should cache its own interface
... |
Azure/azure-sdk-for-python | sdk/containerregistry/azure-containerregistry/tests/test_container_registry_client.py | Python | mit | 23,434 | 0.004139 | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from datetime import datetime
from azure.core import credentials
import pytest
import six
import time
from azure.containerregistry import (
Repositor... | client.list_repository_names()
assert isinstance(repositories, ItemPaged)
count = 0
prev = None
for repo in repositories:
count += 1
assert isinstance(repo, six.string_types)
assert prev != repo
prev = repo
assert count > 0
... | arer()
def test_list_repository_names_by_page(self, containerregistry_endpoint):
client = self.create_registry_client(containerregistry_endpoint)
results_per_page = 2
total_pages = 0
repository_pages = client.list_repository_names(results_per_page=results_per_page)
prev = N... |
vandorjw/django-template-project | project/project_name/urls.py | Python | mit | 1,221 | 0.005733 | from django.conf.urls import patterns, include, url
from django.contrib.sitemaps import Sitemap
from django.views.generic import TemplateView
from django.contrib import admin
from {{ project_name }}.views import HomePageView, ContactPageView, RobotPageView, HumanPageView
from {{ project | _name }}.sitemap import BlogSitemap, HardCodedSitemap
admin.autodiscover()
sitemaps = {
'blog': | BlogSitemap,
'hardcodedpages': HardCodedSitemap,
}
urlpatterns = patterns('',
url(
regex=r"^$",
view=HomePageView.as_view(),
name="homepage",
),
url(
regex=r"^contact/$",
view=ContactPageView.as_view(),
name="contactpage",
),
url(
regex=r... |
CARMinesDouai/MultiRobotExplorationPackages | inria_demo/scripts/autodock_client.py | Python | mit | 3,861 | 0.019684 | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Yujin Robot
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must r... |
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER 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 BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (IN... |
cgstudiomap/cgstudiomap | main/parts/web/web_widget_x2many_2d_matrix/__openerp__.py | Python | agpl-3.0 | 1,516 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | ty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You shou | ld have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "2D matrix for x2many fields",
"version": "1.0",
"author": "Therp BV",
"l... |
richardliaw/ray | rllib/agents/ars/ars_tf_policy.py | Python | apache-2.0 | 4,456 | 0 | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
import gym
import numpy as np
import tree
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.es.es_tf_policy import make_session
from ray.rllib.models import ModelCatalog
from ray.rllib.policy.polic... | sor.shape))
else:
| if not tf1.executing_eagerly():
tf1.enable_eager_execution()
self.sess = self.inputs = None
# Policy network.
self.dist_class, dist_dim = ModelCatalog.get_action_dist(
self.action_space, self.config["model"], dist_type="deterministic")
self.mod... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/waterdemand/docs/latex/build_docs.py | Python | gpl-2.0 | 1,657 | 0.007846 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
import os
import waterdemand
basepath = waterdemand.__path__[0]
path = os.path.join(basepath, "docs", "latex")
cwd = os.getcwd()
os.chdir(path)
modules = ["userguide"]
for module ... | .close()
# run latex, make the index, then run latex again to resolve cross-references correctly and inclu | de the index
if os.system("pdflatex -interaction=nonstopmode " + module + ".tex") > 0:
raise Exception("pdflatex failed")
# The makeindex command will fail if the module doesn't have an index - so it's important NOT to check
# if the result of the system call succeeded. (The advantage of calli... |
jeremiedecock/snippets | python/pyqt/pyqt5/widget_QTableView_share_selection_in_two_views.py | Python | mit | 1,608 | 0.003109 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView, QVBoxLayout, QWidget
class MyModel(QAbstractTableModel):
def __init__(self... | super().__init__(parent)
def rowCount(self, parent):
return 2
def columnCount(self, parent):
return 3
def data(self, index, role):
if role == Qt.DisplayRole:
re | turn "({},{})".format(index.row(), index.column())
return QVariant()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
table_view1 = QTableView()
table_view2 = QTableView()
my_model = MyModel(None)
table_view1.setModel(my_model)
table_view2.setModel(my_... |
MauricioDinki/hatefull | hatefull/apps/answers/migrations/0001_initial.py | Python | bsd-3-clause | 1,380 | 0.003623 | # -*- | coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-07 20:55
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration | ):
initial = True
dependencies = [
('questions', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tests', '0003_test_user'),
]
operations = [
migrations.CreateModel(
name='Answer',
fields=[
('id', mod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.