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 |
|---|---|---|---|---|---|---|---|---|
richlanc/KaraKara | website/karakara/views/feedback.py | Python | gpl-3.0 | 1,173 | 0.004263 | from pyramid.view import view_config
from externals.lib.misc import strip_non_base_types
from externals.lib.log import log_event
from . import web, action_ok, action_error
from ..model import DBSession
from ..model.model_feedback import Feedback
import logging
log = logging.getLogger(__name__)
@view_config(route_n... | eld, value | in request.params.items():
try: setattr(feedback, field,value)
except: pass
feedback.environ = strip_non_base_types(request.environ)
DBSession.add(feedback)
log.info('feedback - {0}'.format(request.params.get('details')))
log_event(request, **request.params)
return action_ok(message... |
IGITUGraz/scoop | scoop/broker/brokerzmq.py | Python | lgpl-3.0 | 15,234 | 0.001313 | #!/usr/bin/env python
#
# This file is part of Scalable COncurrent Operations in Python (SCOOP).
#
# SCOOP 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 3 of
# the Licens... | s variable will contain a dict (map) of workers: task
self.available_workers = set()
self.unassigned_tasks = deque()
self.assigned_tasks = defaultdict(set)
self.heartbeat_times = {}
self.init_time = time.time()
self.last_task_check_time = time.time()
# Shared vari... | # Handle cloud-like behavior
self.discovery_thread = None
self.config = defaultdict(bool)
self.processConfig({'headless': headless})
def addBrokerList(self, aBrokerInfoList):
"""Add a broker to the broker cluster available list.
Connects to the added broker if needed."""
... |
kmichal2/plivo | app.py | Python | mit | 7,016 | 0.007127 | import os
from flask import Flask, Response, request, url_for
import psycopg2
import urlparse
import plivo
import plivoxml
AUTH_ID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
CALLER_ID = '+12345678901'
BOX_ID = '+12345678901'
MY_URL = 'http://morning-ocean-4669.herokuapp.com/re... | writefile():
response = plivoxml.Response()
client = request.values.get('client')
try:
file = open("/tmp/foo.txt", "w")
file. | write('this is a line of text')
file.close()
read_file = open("/tmp/foo.txt", 'r')
text = read_file.read()
read_file.close()
response.addSpeak(text)
except Exception, e:
response.addSpeak(e)
return Response(str(response), mimetype='text/xml')
@app.route("/re... |
dekom/threepress-bookworm-read-only | bookworm/gdata/tests/all_tests_coverage.py | Python | bsd-3-clause | 1,805 | 0.00554 | #!/usr/bin/env python
#
# Copyright (C) 2009 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... | atom.mock_http_core, atom.client, gdata.gauth, gdata.client,
gdata.core, gdata.data, gdata.blogger.data, | gdata.blogger.client,
gdata.maps.data, gdata.maps.client, gdata.spreadsheets.data])
|
UdK-VPT/Open_eQuarter | mole/extensions/acqu_berlin/fbinter_wfs_floors_alkis.py | Python | gpl-2.0 | 1,594 | 0.00941 | # -*- coding: utf-8 -*-
from qgis.core import NULL
from mole.project import config
from PyQt4.QtCore import QVariant
def load(self=None):
self.load_wfs()
return True
def evaluation(self=None, parameters={},feature=None):
from mole import oeq_global
result = {'FLOORS': {'type': QVariant.Double,
... | WFS Capture)',
sourcelayer_name='Floors (WFS Capture)',
targetlayer_name=config.data_layer_name,
active=False,
description=u'',
#source='http://fbinter.stadt-berlin.de/fb/wfs/geometry/senstadt/re_alkis_gebaeude?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=fis:re_alkis_gebaeude&SRSNAME=EPSG:... | t_method=None,
evaluation_method=evaluation,
postflight_method=None)
extension.registerExtension(default=True)
|
openmv/openmv | scripts/examples/OpenMV/04-Image-Filters/grayscale_bilateral_filter.py | Python | mit | 1,399 | 0.009292 | # Grayscale Bilteral Filter Example
#
# This example shows off using the bilateral filter on grayscale images.
import sensor, image, time
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.GRAYSCALE) # or sensor.RGB565
sensor.set_framesize(sensor.QQVGA) # or sensor.QVGA (or others)
sensor.skip... | pace_sigma=1)
# Note that the bilateral filter can introduce image defects if you set
# color_sigma/spac | e_sigma to aggresively. Increase the sigma values until
# the defects go away if you see them.
print(clock.fps()) # Note: Your OpenMV Cam runs about half as fast while
# connected to your computer. The FPS should increase once disconnected.
|
sostenibilidad-unam/posgrado | posgradmin/posgradmin/migrations/0040_auto_20191120_2258.py | Python | gpl-3.0 | 484 | 0.002066 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2019-11-21 04:58
from __future__ import uni | code_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
( | 'posgradmin', '0039_auto_20191120_2249'),
]
operations = [
migrations.AlterModelOptions(
name='profesor',
options={'ordering': ['user__first_name', 'user__last_name'], 'verbose_name_plural': 'Profesores'},
),
]
|
jeffery9/mixprint_addons | ineco_kpi/crm_lead.py | Python | agpl-3.0 | 1,871 | 0.003741 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | e_ref, '%Y-%m-%d') + relativedelta(days=30))
vals.update({'date_deadline': next_date.strftime('%Y-%m-%d')})
| return super(crm_lead, self).create(cr, uid, vals, context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
equitania/myodoo-addons-v10 | eq_website_quote/__init__.py | Python | agpl-3.0 | 1,002 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo Addon, Open Source Management Solution
# Copyright (C) 2014-now Equitania Software GmbH(<http://www.equitania.de>).
#
# This program is free software: you can redistribute it and/or modify
# it un... | 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 det | ails.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
|
cpcloud/ibis | ibis/tests/sql/test_select_sql.py | Python | apache-2.0 | 33,419 | 0 | import pytest
import ibis
from ibis.backends.base.sql.compiler import Compiler
from .conftest import get_query
def test_nameless_table():
# Generate a unique table name when we haven't passed on
nameless = ibis.table([('key', 'string')])
assert Compiler.to_sql(nameless) == 'SELECT *\nFROM {}'.format(
... | id="explicit_column",
),
| pytest.param(
lambda t: t.aggregate(
[t['f'].sum().name('total')], ['foo_id', 'bar_id']
),
"""SELECT `foo_id`, `bar_id`, sum(`f`) AS `total`
FROM star1
GROUP BY 1, 2""",
id="string_columns",
),
],
)
def test_simple_aggregate_query(star1, expr... |
openstack/python-zaqarclient | zaqarclient/queues/v1/message.py | Python | apache-2.0 | 2,204 | 0 | # Copyright (c) 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | f.claim_count = claim_count
self.checksum = checksum
# NOTE(flaper87): Is this really
# necessary? Should this be returned
# by Zaqar?
# The url has two forms depending on if it has been claimed.
# /v1/queues/worker-jobs/messages/5c6939a8?claim_id=63c9a592
# or
... | self._id.split('?')[0]
else:
self._id = id
def __repr__(self):
return '<Message id:{id} ttl:{ttl}>'.format(id=self._id,
ttl=self.ttl)
@property
def claim_id(self):
if '=' in self.href:
return self.href.spl... |
joferkington/numpy | numpy/core/tests/test_multiarray.py | Python | bsd-3-clause | 242,380 | 0.000772 | from __future__ import division, absolute_import, print_function
import collections
import tempfile
import sys
import shutil
import warnings
import operator
import io
import itertools
import ctypes
import os
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
from decimal import D... | err_msg="%r: 2**%d - 1" % (ut, i))
class TestAttributes(TestCase):
def setUp(self):
self.one = np.arange(10)
self.two = np.arange(20).reshape(4, 5)
self.three = np.arange(60, dtype=np.float64).resh | ape(2, 5, 6)
def test_attributes(self):
assert_equal(self.one.shape, (10,))
assert_equal(self.two.shape, (4, 5))
assert_equal(self.three.shape, (2, 5, 6))
self.three.shape = (10, 3, 2)
assert_equal(self.three.shape, (10, 3, 2))
self.three.shape = (2, 5, 6)
as... |
beniwohli/apm-agent-python | elasticapm/contrib/django/middleware/wsgi.py | Python | bsd-3-clause | 2,302 | 0.001738 | # BSD 3-Clause License
#
# Copyright (c) 2012, the Sentry Team, see AUTHORS for more details
# Copyright (c) 2019, Elasticsearch BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Red... | UBSTITUTE 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 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
from django | .apps import apps
from elasticapm.contrib.django.client import get_client
from elasticapm.middleware import ElasticAPM as ElasticAPMBase
class ElasticAPM(ElasticAPMBase):
"""
Identical to the default WSGI middleware except that
the client comes dynamically via ``get_client
>>> from elasticapm.contri... |
mcieslik-mctp/papy | src/papy/util/codefile.py | Python | mit | 1,160 | 0.003448 | """
:mod:`papy.util.codefile`
=========================
Provides template strings for saving **PaPy** pipelines directly as Python
source code.
"""
# imap call signature
I_SIG = ' %s = NuMap(worker_type="%s", worker_num=%s, stride=%s, buffer=%s, ' + \
'ordered =%s, skip =%s, name ="%s")\n'
# pi... | ' ' + 'return (pipers, xtras, pipes)' + '\n\n' + \
'if __name_ | _ == "__main__":' + '\n' + \
' ' + 'pipeline()' + '\n' + \
'' + '\n'
|
riga/luigi | test/local_target_test.py | Python | apache-2.0 | 11,097 | 0.000361 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | LocalTarget(self.path, luigi.format.Gzip)
p = t.open('w')
test_data = b'test'
p.write(test_data)
print(self.path)
self.assertFalse(os.path.exists(self.pat | h))
p.close()
self.assertTrue(os.path.exists(self.path))
# Using gzip module as validation
f = gzip.open(self.path, 'r')
self.assertTrue(test_data == f.read())
f.close()
# Verifying our own gzip reader
f = LocalTarget(self.path, luigi.format.Gzip).open('... |
acsone/mozaik | mozaik_person/tests/__init__.py | Python | agpl-3.0 | 1,096 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of mozaik_person, an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# mozaik_person 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 y | our option) any later version.
#
# mozaik_person 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 hav... |
google/material-design-icons | update/venv/lib/python3.9/site-packages/fontTools/misc/roundTools.py | Python | apache-2.0 | 1,585 | 0.018297 | """
Various round-to-integer helpers.
"""
import math
import functools
import logging
log = log | ging.getLogger(__name__)
__all__ = [
"noRound",
"otRound",
"maybeRound",
"roundFunc",
]
def noRound(value):
return value
def otRound(value):
"""Round float value to neares | t integer towards ``+Infinity``.
The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
defines the required method for converting floating point values to
fixed-point. In part... |
plotly/plotly.py | packages/python/plotly/plotly/validators/layout/slider/_minorticklen.py | Python | mit | 474 | 0 | import _plotly_utils. | basevalidators
class MinorticklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="minorticklen", parent_name="layout.slider", **kwargs
):
super(MinorticklenValid | ator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "arraydraw"),
min=kwargs.pop("min", 0),
**kwargs
)
|
michelm/beehive | waftools/cppcheck.py | Python | mit | 16,204 | 0.02845 | #! /usr/bin/env python
# -*- encoding: utf-8 -*-
# Michel Mooij, michel.mooij7@gmail.com
"""
Tool Description
================
This module provides a waf wrapper (i.e. waftool) around the C/C++ source code
checking tool 'cppcheck'.
See http://cppcheck.sourceforge.net/ for more information on the cppcheck tool
itself... | _C
std_cxx = self.env.CPPCHECK_STD_CXX
max_configs = self.env.CPPCHECK_MAX_CONFIGS
bin_enable = self.env.CPPCHECK_BIN_ENABLE
lib_enable = self.env.CPPCHECK_LIB_ENABLE
cmd = '%s' % self.env.CPPCHECK
args = ['--inconclusive','--report-progress','--verbose','--xml','--xml-version=2']
args.append('--max-configs=%s... | % std_cxx)
else:
args.append('--language=c')
args.append('--std=%s' % std_c)
if self.bld.options.cppcheck_check_config:
args.append('--check-config')
if set(['cprogram','cxxprogram']) & set(features):
args.append('--enable=%s' % bin_enable)
else:
args.append('--enable=%s' % lib_enable)
for src in self... |
tobspr/panda3d | direct/src/showbase/VFSImporter.py | Python | bsd-3-clause | 19,654 | 0.002646 | __all__ = ['register', 'sharedPackages',
'reloadSharedPackage', 'reloadSharedPackages']
from panda3d.core import Filename, VirtualFileSystem, VirtualFileMountSystem, OFileStream, copyStream
from direct.stdpy.file import open
import sys
import marshal
import imp
import types
# The sharedPackages dictionary ... | self.timestamp = vfile.getTimestamp()
self.fil | ename = filename
self.desc = desc
self.packagePath = packagePath
def load_module(self, fullname, loadingShared = False):
#print >>sys.stderr, "load_module(%s), dir_path = %s, filename = %s" % (fullname, self.dir_path, self.filename)
if self.desc[2] == imp.PY_FROZEN:
retu... |
nckx/dstat | plugins/dstat_vm_mem.py | Python | gpl-2.0 | 1,136 | 0.006162 | ### Author: Bert de Bruijn <bert+dstat$debruijn,be>
### VMware memory stats
### Displays memory stats coming from the hypervisor inside VMware VMs.
### The vmGuestLib API from | VMware Tools needs to be installed
class dstat_plugin(dstat):
def __init__(self):
self.name = 'vmware memory'
self.vars = ('active', 'balloone | d', 'mapped', 'swapped', 'used')
self.nick = ('active', 'balln', 'mappd', 'swapd', 'used')
self.type = 'd'
self.width = 5
self.scale = 1024
def check(self):
try:
global vmguestlib
import vmguestlib
self.gl = vmguestlib.VMGuestLib()
... |
dev-zzo/pwn-tools | scanners/udp-probe.py | Python | unlicense | 7,615 | 0.003414 | #!/usr/bin/python
"""
UDP Service Scanner version 0.1 by dev_zzo
This work has largely been inspired by:
https://github.com/portcullislabs/udp-proto-scanner
As is, this is more like a prober than scanner;
it operates using predefined probes for each known protocol.
"""
import argparse
import socket
import struct
im... | r = long2ip(a)
results.append(addr)
addr += 1
else:
addr = ip2long(target_spec)
results.append(target_spec)
return results
def scan_main(args):
"Main scanning routine"
global __scan_spec
targets = parse_targets(args.targets)
respons... | CK_DGRAM)
s.bind(('', 57022))
try:
for port, name, probe in __scan_spec:
print("Running probe '%s'..." % name)
s.settimeout(None)
for target in targets:
s.sendto(probe, (target, port))
s.settimeout(0.0)
# print("Waiting for r... |
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.util/src/openmdao/util/__init__.py | Python | mit | 137 | 0.007299 | """
This package contains a number of utilities that are used inside o | f openmdao.
It does n | ot depend on any other openmdao package.
"""
|
rfugger/villagescc | cc/relate/views.py | Python | agpl-3.0 | 5,122 | 0.002148 | from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.db.models import Q
from django.contrib import messages
from cc.general.util import render
import cc.ripple.api as ripple
from cc.profile.models impo... |
form = AcknowledgementForm(request.POST, max_ripple=max_amount)
if form.is_valid():
| acknowledgement = form.send_acknowledgement(
request.profile, recipient)
send_acknowledgement_notification(acknowledgement)
messages.info(request, MESSAGES['acknowledgement_sent'])
return HttpResponseRedirect(acknowledgement.get_absolute_url())
else:
... |
tdlong/YeastRobot | UserPrograms/ASE/Mon_ToBeads_3.py | Python | gpl-3.0 | 2,655 | 0.050094 | import sys
# where RobotControl.py, etc lives
sys.path.append('/home/pi/Desktop/ADL/YeastRobot/PythonLibrary')
from RobotControl import *
#################################
### Define Deck Layout
#################################
deck="""\
DW96P DW96P DW96W DW96W BLANK
DW96P DW96P DW96W DW96W BLANK
DW96P DW... | pick up 2 * 200ul of SDS from C5, add to C2
position(row,5,position = OffsetDict[offset])
aspirate(200,depth=adjusted_dept | h + 2,speed=50, mix=0)
position(row,2,position = OffsetDict[offset])
dispense(200, depth=adjusted_depth + 3, speed=100)
position(row,5,position = OffsetDict[offset])
aspirate(200,depth=adjusted_depth + 2,speed=50, mix=0)
position(row,2,position = OffsetDict[offset])
dispense(200, depth=adjusted_depth - 2, ... |
migueldiascosta/easybuild-framework | easybuild/toolchains/gmpich2.py | Python | gpl-2.0 | 1,420 | 0.001408 | ##
# Copyright 2012-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | ributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a co | py of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for gmpich2 compiler toolchain (includes GCC and MPICH2).
:author: Kenneth Hoste (Ghent University)
"""
from easybuild.toolchains.gcc import GccToolchain
from easybuild.toolchains.mpi.mpi... |
amwelch/a10sdk-python | a10sdk/core/ip/ip_dns_suffix.py | Python | apache-2.0 | 1,146 | 0.010471 | from a10sdk.common.A10BaseClass import A10BaseClass
class Suffix(A10BaseClass):
"""Class Description::
DNS suffix.
Class suffix supports CRUD Operations and inherits from `common | /A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param domain_name: {"description": "DNS suf | fix", "format": "string", "minLength": 1, "optional": true, "maxLength": 32, "type": "string"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operat... |
magic0704/oslo.db | oslo_db/sqlalchemy/models.py | Python | apache-2.0 | 4,841 | 0 | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012 Cloudscaling Group, Inc.
# All Rights Reserved.
#
# Licens... | lied. See the
# License for the specific language governing permissions and limitations
# under | the License.
"""
SQLAlchemy models.
"""
import six
from oslo_utils import timeutils
from sqlalchemy import Column, Integer
from sqlalchemy import DateTime
from sqlalchemy.orm import object_mapper
class ModelBase(six.Iterator):
"""Base class for models."""
__table_initialized__ = False
def save(self, se... |
avocadoinnocenceproject/farflungfruit | render.py | Python | mit | 303 | 0.006601 | from jinja2 import Template
import codecs
def render(file, props=None):
if props == None:
return '404'
with | codecs.open('./views/' + file + '.html', 'r', encoding='utf8') as f:
content = f.read()
templated = Template(content).render(props)
return templ | ated
|
zstars/weblabdeusto | server/admin/cli/migrate_db_40m1_to_50/migrationlib.py | Python | bsd-2-clause | 4,717 | 0.007844 | import sys, os
sys.path.append(os.sep.join(("..","..","..","src")))
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import traceback
import MySQLdb as dbi
import weblab.db.model as Model
########################################################
#
# Abstract class. All classes implementi... | "NAME": db }
engine = create_engine(connection_url, convert_unicode=True, echo=False)
Model.Base.metadata.create_all(engine)
for klass in self.order:
fix = klass(self.user, self.password, db)
fix.exec | ute()
|
USGSDenverPychron/pychron | pychron/hardware/newport/newport_group.py | Python | apache-2.0 | 2,866 | 0.000349 | # ===============================================================================
# Copyright 2011 Jake Ross
#
# 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... | PING = dict(
acceleration="HA",
deceleration="HD",
# emergency_deceleration = 'HE',
jerk="HJ",
velocity="HV",
axes="HN",
)
class NewportGroup(Axis):
# acceleration = Float
# deceleration = Float
emergency_deceleration = None
jerk = Float
# velocity = Float
name = "Group... | ration = Float
axes = Tuple
# calculate_parameters = Bool(True)
id = None
def _set_acceleration(self, v):
self._acceleration = v
def _set_deceleration(self, v):
self._deceleration = v
def _set_velocity(self, v):
self._velocity = v
def load(self, path):
... |
obsoleter/suds | suds/umx/__init__.py | Python | lgpl-3.0 | 1,849 | 0.002704 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser 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 ... | self, node, **kwargs):
Object.__init__(self)
self.node = node
self.data = None
self.text = None
for k,v in list(kwargs.items()):
setattr(s | elf, k, v)
def __getattr__(self, name):
if name not in self.__dict__:
if name in self.extensions:
v = None
setattr(self, name, v)
else:
raise AttributeError('Content has no attribute %s' % name)
else:
v = ... |
RuiNascimento/krepo | script.module.lambdascrapers/lib/lambdascrapers/sources_placenta/en_placenta-1.7.8/to_be_fixed/needsfixing/vumoo.py | Python | gpl-2.0 | 7,170 | 0.004045 | # -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want wi... | ': quality,
'language': 'en',
'url': link,
'direct': True,
'debridonly': False
})
| except Exception:
continue
return sources
except Exception:
return
def resolve(self, url):
try:
return url
except Exception:
return
def __get_episode_urls(self, data):
try:
... |
WPMedia/dd-agent | tests/checks/integration/test_cassandra.py | Python | bsd-3-clause | 2,080 | 0.000481 | # stdlib
import threading
import time
from types import ListType
import unittest
# 3p
from nose.plugins.attrib import attr
# project
from aggregator import MetricsAggregator
from dogstatsd import Server
from jmxfetch import JMXFetch
from tests.checks.common import Fixtures
STATSD_PORT = 8121
class DummyReporter(th... | .assertTrue(len([t for t in metrics if "cassandra.db." in t['metric'] and "instance:cassandra_instance" in t[ | 'tags']]) > 40, metrics)
|
kasundezoysa/senze | testpi/myDevice.py | Python | apache-2.0 | 4,355 | 0.027325 | #!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
import datetime
import socket
import time
import sys
import os.path
lib_path = os.path.abspath('../utils')
sys.path.append(lib_pat... | self.ip= socket.gethostbyname(host)
self.port = port
#self._reactor=reactor
#self.ip=reactor.resolve(host)
def startProtocol(self):
| self.transport.connect(self.ip,self.port)
if state=='INITIAL':
#If system is at the initial state, it will send the device creation Senze
self.register()
else:
response=raw_input("Enter your Senze:")
self.sendDatagram(response)
def stopProtocol(self):
... |
crate/crate-docs-theme | src/crate/theme/rtd/conf/sql_99.py | Python | apache-2.0 | 1,537 | 0 | # -*- coding: utf-8; -*-
#
# Licensed to Crate (https://crate.io) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License");
# yo... | ire | d by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# However, if you... |
blechta/dolfin-tape | dolfintape/demo_problems/StokesVortices.py | Python | gpl-3.0 | 2,060 | 0.000971 | # Copyright (C) 2015 Jan Blechta
#
# This file is part of dolfin-tape.
#
# dolfin-tape 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 3 of the License, or
# (at your option) any later version.
#
# dolfin-tape is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ev... |
project-rig/rig | rig/place_and_route/utils.py | Python | gpl-2.0 | 13,067 | 0.000077 | """Utilities functions which assist in the generation of commonly required data
structures from the products of placement, allocation and routing.
"""
from collections import defaultdict
from six import iteritems, itervalues
import warnings
from rig.place_and_route.machine import Machine, Co | res, SDRAM, SRAM
from rig.place_and_route.constraints import ReserveResourceConstraint
from rig.machine_control.consts import AppState
def build_machine(system_info,
core_resource=Cores,
sdram_resource=SDRAM,
sram_resource=SRAM):
"""Build a :py:class:`~rig.p... | Links are tested by sending a 'PEEK' command down the link which
checks to see if the remote device responds correctly. If the link
is dead, no response will be received and the link will be assumed
dead. Since peripherals do not generally respond to 'PEEK'
commands, working links att... |
code-for-india/sahana_shelter_worldbank | modules/s3db/climate.py | Python | mit | 27,377 | 0.009972 | # -*- coding: utf-8 -*-
""" Sahana Eden Climate Model
@copyright: 2011-2013 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software witho... | ---------------------------------------------------------------------
# Climate Place
#
# This resource is spread over 4 tables, which | we assume are linked by
# common IDs
#
# @ToDo: Migrate to gis_location?
# Although this table has many fields unused so a performance hit?
# elevation is not included as it would just mean a performance hit
# when we are generating 2D maps without elevation info.
... |
rancher/rancher | tests/validation/tests/rke/test_install_config.py | Python | apache-2.0 | 4,984 | 0 | from .conftest import * # NOQA
from .common import * # NOQA
def test_install_config_1(test_name, cloud_provider, rke_client, kubectl):
"""
Node Address specified as just IP and using only this in the node spec
Specific kubernetes_version can be used
"""
rke_template = 'cluster_install_config_11.... | "
Create a cluster with minimum possible values, will use the defaulted
network plugin for RKE
"""
rke_template = 'cluster_install_config_8.yml.j2'
nodes = cloud_provider.create_multiple_nodes(3, test_name)
create_a | nd_validate(
cloud_provider, rke_client, kubectl, rke_template, nodes,
remove_nodes=True)
def test_install_config_9(test_name, cloud_provider, rke_client, kubectl):
"""
Launch a cluster with unencrypted ssh keys
"""
key_name = 'install-config-9'
rke_template = 'cluster_install_conf... |
hzlf/openbroadcast.org | website/apps/massimporter/migrations/0001_initial.py | Python | gpl-3.0 | 4,610 | 0.000434 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django_extensions.db.fields
import django.db.models.deletion
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
("importer", "0001_initial"),
... | blank=True,
to=settings.AUTH_USER_MODEL,
null=True,
),
),
],
options={
"ordering": ("-created",),
"verbose_name": "Import",
"verbose_name_plural": "Imports"... | "permissions": (("massimport_manage", "Manage Massimporter Sessions"),),
},
),
migrations.CreateModel(
name="MassimportFile",
fields=[
(
"id",
models.AutoField(
verbose_name... |
rhyswhitley/savanna_iav | src/data_preproc/pickleit/pickle_inputs.py | Python | cc0-1.0 | 2,001 | 0.004998 | #!/usr/bin/env python
import os
import re
import netCDF4 as nc
import numpy as np
import pandas as pd
import pickle
def get_value(nc_o | bj, label):
return nc_obj.variables[label][:].flatten()
def get_dataframe(nc_path):
"""
A quick function to transform a netcdf file into a pandas dataframe that
| can be used for analysis and plotting. Attributes are extracted using
in built netCDF4 library functions. Time is arbitrary and needs to be
set by the user.
"""
print("> pickling contents in object at {0}".format(nc_path))
# make a connection to the netCDF file
ncdf_con = nc.Dataset(nc_path,... |
kgjamieson/NEXT-psych | examples/cartoon_tuple_n25k8/experiment_tuple_n25k8.py | Python | apache-2.0 | 4,671 | 0.004282 | """
author: Lalit Jain, lalitkumarjj@gmail.com
modified: Chris Fernandez, chris2fernandez@gmail.com
last updated: 05/27/2015
A module for replicating the 25 total arms with 8 arms shown at a time tuple bandits pure exploration
experiments from the NEXT paper.
Usage:
python experiment_tuple_n25k8.py
"""
import os, sys... | _BUCKET_NAME)
# Update the cartoon_dueling.html file wit the exp_uid_list and widget_key_list
# with open('cartoon_tuple_n25k8.html','r') as page:
# print "opended file"
# page_string = page.read()
# page_string = page_string.replace("{{exp_uid_list}}", str(exp_uid_list))
# page_string = page_string.replace("{... | ring)
# out.flush()
# out.close()
|
david2307/backend_159 | communities/serializers.py | Python | gpl-3.0 | 460 | 0.008696 | from rest_framework import serializers
from . | models import Community, Objective, SocialNetwork, Sector
class ObjectiveSerializer(serializers.ModelSerializer):
clas | s Meta:
model = Objective
class CommunitySerializer(serializers.ModelSerializer):
objectives = ObjectiveSerializer(many=True)
class Meta:
model = Community
depth = 1
class SectorSerializer(serializers.ModelSerializer):
class Meta:
model = Sector |
chhsiao1981/f6a_tw_crawler | tests/__init__.py | Python | mit | 147 | 0 | # -*- coding: utf-8 -*-
from f6a_tw_crawl | er.constants | import *
import unittest
import logging
def setup():
pass
def teardown():
pass
|
sassystacks/DASS | Simulation/Test_userInput_roll.py | Python | mit | 5,053 | 0.008114 | from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative
from pymavlink import mavutil # Needed for command message definitions
from Find_serial_ports import serial_ports
import time
import math
import argparse
parser = argparse.ArgumentParser(description='Control Copter and send comm... | .
See the above link for information on the type_mask (0=enable, 1=ignore).
At time of writing, acceleration a | nd yaw bits are ignored.
"""
msg = vehicle.message_factory.set_position_target_global_int_encode(
0, # time_boot_ms (not used)
0, 0, # target system, target component
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame
0b0000111111000111, # type_mask (only s... |
jbruce12000/septic-tank | septic_tank/outputs.py | Python | mit | 9,478 | 0.007597 | from pipeline import Pipe
from pysolr import Solr
import json
import logging
import sys
import time
import zmq
import sqlite3 as lite
from collections import defaultdict
class Output(Pipe):
def data_invalid(self,data):
if 'type' not in data:
return True
if len(data.keys()) < 2:
... | th="ft.db",commitrate=10000):
super(SQLiteOutput, self).__init__()
self.path = path
self.commitrate = commitrate
self.sqlitecache = defaultdict(list)
self.commityet = 0
self.tables = {};
def create_table_sql_for(self,data):
| columns=",".join(data.keys())
#return "create virtual table %s using fts4(%s)" % (data['type'],columns)
return "create table if not exists %s (%s)" % (data['type'],columns)
def create_insert_sql_for(self,data):
columns = sorted(data.keys())
return "insert into %s (%s) values (%... |
justinbois/fish-activity | tests/test_summarize.py | Python | mit | 4,743 | 0.001265 | import pytest
import numpy as np
import pandas as pd
from pandas.util.testing import assert_frame_equal
import fishact
def test_sleep_latency():
df = pd.DataFrame({'zeit': np.linspace(0.0, 19.0, 20),
'sleep': np.ones(20, dtype=int)})
assert np.isnan(fishact.summarize._sleep_latency(d... | '2017-03-30 14:11:00',
'2017-03-30 14:12:00',
'2017-03-30 14:13:00 | ',
'2017-03-30 14:14:00',
'2017-03-30 14:15:00',
'2017-03-30 14:16:00',
'2017-03-30 14:17:00',
... |
qedsoftware/commcare-hq | corehq/ex-submodules/casexml/apps/case/tests/test_out_of_order_processing.py | Python | bsd-3-clause | 1,076 | 0 | import os
from django.test.utils import override_settings
fr | om django.test import TestCase
from casexml.apps.case.tests.util import delete_all_cases
from corehq.apps.receiverwrapper.util import submit_form_locally
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
@override_settings(CASEXML_FORCE_DOMAIN_CHECK=False)
class OutOfO | rderCaseTest(TestCase):
def setUp(self):
super(OutOfOrderCaseTest, self).setUp()
delete_all_cases()
def testOutOfOrderSubmissions(self):
dir = os.path.join(os.path.dirname(__file__), "data", "ordering")
for fname in ('update_oo.xml', 'create_oo.xml'):
with open(os.p... |
cblair/docset_from_html | get_plist_text.py | Python | mit | 959 | 0.006257 | #!/usr/bin/env python3
def get_plist_text(cf_bundler_identifier, cf_bundle_name=None,
docset_platform_family=None):
"""TODO"""
cf_bundle_name = cf_bundle_name or cf_bundler_identifier.upper()
docset_platform_family = docset_platform_family or cf_bundle_name.upper()
return """
<?xml version="1... | tifier}</string>
<key>CFBundleName</key>
<string>{cf_bundle_name}</string>
<key>DocSetPlatformFamily</key>
<string>{docset_platform_family}</string>
<key>isDashDocset</key>
<true/>
</dict>
</plist>""".format(cf_bundler_identifier=cf_bundler_identifier,
cf_... | et_platform_family) |
allisonrandal/openstack-spec-tracker | spectracker/pagerender.py | Python | apache-2.0 | 1,658 | 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
# d... | date=str(datetime.utcnow()),
frequency=topics))
def render_spec_list(template_dir, output_dir, spec_list):
template_file = "specifications | .html"
template_env = Environment(loader=FileSystemLoader(template_dir))
keytopics_tmpl = template_env.get_template(template_file)
output_file = os.path.join(output_dir, template_file)
with open(output_file, 'w') as fh:
fh.write(keytopics_tmpl.render(date=str(datetime.utcnow()),
... |
harun-emektar/webfs | tests/Test_WebDirParser.py | Python | apache-2.0 | 1,416 | 0.011299 | from webfs import WebDirParser
testDoc = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /ubuntu</title>
</head>
<body>
<h1>Index of /ubuntu</h1>
<pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> <a href=" | ?C=M;O=A">Last modified</a> <a href="?C=S;O=A">Size</a> <a href="?C=D;O=A">Description</a><hr><img src="/icons/back.gif" alt="[DIR]"> <a href="/ | ">Parent Directory</a> -
<img src="/icons/folder.gif" alt="[DIR]"> <a href="dists/">dists/</a> 18-Jun-2014 12:46 -
<img src="/icons/folder.gif" alt="[DIR]"> <a href="indices/">indices/</a> 28-Apr-2008 17:47 -
<img src="/icons/compressed.gif" alt... |
dc3-plaso/plaso | tests/parsers/winreg_plugins/officemru.py | Python | apache-2.0 | 3,793 | 0.001318 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
import unittest
from plaso.formatters import officemru # pylint: disable=unused-import
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib impor... | TIME)
self.assertEqual(event_object.value_string, expected_value_string)
expected_message = u'[{0:s}] Value: {1:s}'.format(
key_path, expected_value_string)
expected_short_message = u'{0:s}...'.format(expected_value_string[0:77])
self._TestGetM | essageStrings(
event_object, expected_message, expected_short_message)
if __name__ == '__main__':
unittest.main()
|
apavlo/h-store | third_party/python/fabric/utils.py | Python | gpl-3.0 | 4,636 | 0.000431 | """
Internal subroutines for e.g. aborting execution with an error message,
or performing indenting on multiline output.
"""
import sys
import textwrap
def abort(msg):
"""
Abort execution, print ``msg`` to stderr and exit with error status (1.)
This function currently makes use of `sys.exit`_, which rais... | for`` loop). Sin | ce such use cases typically also
require a lack of line endings (such as printing a series of dots to
signify progress) it also omits the traditional newline by default.
.. note::
Since `~fabric.utils.fastprint` calls `~fabric.utils.puts`, it is
likewise subject to the ``user`` :doc:`outpu... |
mayapurmedia/tovp | tovp/contributions/migrations/0023_auto_20150414_1305.py | Python | mit | 792 | 0.002525 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models | , migrations
class Migration(migrations.Migration):
dependencies = [
('contributions', '0022_auto_20150413_1726'),
]
o | perations = [
migrations.AddField(
model_name='bulkpayment',
name='overwrite_pan_card',
field=models.CharField(null=True, verbose_name='Overwrite PAN card number', max_length=50, blank=True),
preserve_default=True,
),
migrations.AddField(
... |
smarr/Truffle | vm/mx.vm/mx_vm.py | Python | gpl-2.0 | 19,478 | 0.002362 | #
# ----------------------------------------------------------------------------------------------------
#
# Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify ... | license_files=[],
third_party_license_files=[],
dependencies=['sdk'],
jar_distributions=[
'vm:INSTALLER',
'truffle:TruffleJSON'
],
support_distributions=['vm:IN | STALLER_GRAALVM_SUPPORT'],
launcher_configs=[
mx_sdk_vm.LauncherConfig(
destination="bin/<exe:gu>",
jar_distributions=[
'vm:INSTALLER',
'truffle:TruffleJSON'
],
dir_jars=True,
main_class="org.graalvm.component.instal... |
vdrey/Toolbox | Python/BHP/BHP-Code/BHP-Code/Chapter4/arper.py | Python | mit | 2,682 | 0.020507 | from scapy.all import *
import os
import sys
import threading
interface = "en1"
target_ip = "172.16.1.71"
gateway_ip = "172.16.1.254"
packet_count = 1000
poisoning = True
def restore_target(gateway_ip,gateway_mac,target_ip,target_mac):
# slightly different method using send
print "[*] Rest... | son_target(gateway_ip,gateway_mac,target_ip,target_mac):
global poisoning
poison_target = ARP( | )
poison_target.op = 2
poison_target.psrc = gateway_ip
poison_target.pdst = target_ip
poison_target.hwdst= target_mac
poison_gateway = ARP()
poison_gateway.op = 2
poison_gateway.psrc = target_ip
poison_gateway.pdst = gateway_ip
poison_gateway.hwdst= gateway_mac
print "[*] B... |
MinchinWeb/topydo | topydo/commands/DepriCommand.py | Python | gpl-3.0 | 1,906 | 0.001049 | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <me@bramschoenmakers.nl>
#
# 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 L... | ist))
for todo in self.todos:
if todo.priority() != None:
self.todolist.set_priority(todo, None)
self.out("Priority removed.")
self.out(self.printer.print_todo(todo))
def usage(self):
return """\
Synopsis: depri <NUMBER1> [<NUMBER2> ...]
... | (s).
It is also possible to deprioritize items as complete with an expression using
the -e flag. Use -x to also process todo items that are normally invisible
(with the 'ls' subcommand).
"""
|
manuelzs/django-bitid | djbitid/backends.py | Python | mit | 2,846 | 0.004216 | from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.contrib.auth.models import User
from pybitid import bitid
from models import Nonce
class BitIdBackend(object):
USE_TESTNET_DEFAULT = False
def authenticate(self, bitid_uri=None, callback_uri=None,
... | oof of goodwill (@see pybitid_demo.services.fake_tx_db_service)
if not self.goodwill_check(address):
errors.append("Address is invalid or not legal")
return None
# Creates a new user and stores it in db
user = User.objects.create_user(username=address)... | he authentication, let's set the user id in the nonce and update it in db
nonce.user = user
nonce.save()
return user
def goodwill_check(self, address):
"""
TODO Check to prevent flooding
"""
return True
|
koniiiik/django | tests/requests/test_data_upload_settings.py | Python | bsd-3-clause | 6,773 | 0.001329 | from io import BytesIO
from django.core.exceptions import RequestDataTooBig, TooManyFieldsSent
from django.core.handlers.wsgi import WSGIRequest
from django.test import SimpleTestCase
from django.test.client import FakePayload
TOO_MANY_FIELDS_MSG = 'The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_... | _content_length(self):
self.request.environ['CONTENT_LENGTH'] = ''
self.request.body
class DataUploadMaxNumberOfFieldsGet(SimpleTestCase):
def test_get_max_fields_exceeded(self):
with se | lf.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=1):
with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG):
request = WSGIRequest({
'REQUEST_METHOD': 'GET',
'wsgi.input': BytesIO(b''),
'QUERY_STRING': 'a=1&a=2;a=3',
... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/instrument/shared_instrument_bandfill.py | Python | mit | 459 | 0.04793 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from | swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/instrument/shared_instrument_bandfill.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### | END MODIFICATIONS ####
return result |
lvella/tagmaker | tagmaker.py | Python | gpl-3.0 | 3,169 | 0.002841 | #!/usr/bin/python3
# Copyright 2013 Universidade Federal de Uberlândia
# Author: Lucas Clemente Vella <lucas.vella@i9nagi.ufu.br>
# Utility to batch create conference tags from CSV data and SVG template.
import os
import io
import os.path
import sys
import csv
import re
import subprocess
import itertools
import jinj... | "pdfnup --suffix nup --nup '2x4' --paper a4paper --no-landscape --noautoscale true --frame true --outfile {} -- ".format(os.path.join(batch_path, 'to_print.pdf')) + ' '.join(map('"{}"'.format, outnames))
print( | group_cmd)
os.system(group_cmd)
print('Done.')
if __name__ == "__main__":
main()
|
jamesward-demo/air-quick-fix | AIRQuickFixServer/pyamf/flex/messaging.py | Python | apache-2.0 | 9,203 | 0.001087 | # Copyright (c) 2007-2008 The PyAMF Project.
# See LICENSE for details.
"""
Flex Messaging implementation.
This module contains the message classes used with Flex Data Services.
@see: U{RemoteObject on OSFlash (external)
<http://osflash.org/documentation/amf3#remoteobject>}
@author: U{Arnar Birgisson<mailto:arnarbi... | #: C{Base64} encoded credentials in this header.
REMOTE_CREDENTIALS_HEADER = "DSRemoteCredentials"
#: The request timeout value is set on outbound messages by services or
#: channels and the value controls how long the responder will wait for an
#: acknowledgement, result or fault response for the me... | before timing
#: out the request.
REQUEST_TIMEOUT_HEADER = "DSRequestTimeout"
def __init__(self, *args, **kwargs):
self.body = kwargs.get('body', None)
self.clientId = kwargs.get('clientId', None)
self.destination = kwargs.get('destination', None)
self.headers = kwargs.get('... |
pylada/pylada-light | src/pylada/crystal/binary.py | Python | gpl-3.0 | 2,322 | 0.004737 | ###############################
# This file is part of PyLaDa.
#
# Copyright (C) 2013 National Renewable Energy Lab
#
# PyLaDa is a high throughput computational platform for Physics. It aims to make it easier to submit
# large numbers of jobs on supercomputers. It provides a python interface to physical input, suc... | 0.5, 0.5, 0,
scale=1, name='Zinc-Blende' )\
.add_atom(0, 0, 0, 'A')\
.add_atom(0.25, 0.25, 0.25, 'B')
def wurtzite():
""" wurtzite lattice """
from pylada.crystal import Structure
return Structure(0.5, 0.5, 0,
-0.866025, 0.866025, 0,
... | scale=1, name='Wurtzite' )\
.add_atom(0.5, 0.288675, 0, 'A')\
.add_atom(0.5, -0.288675, 0.5, 'A')\
.add_atom(0.5, 0.288675, 0.25, 'B')\
.add_atom(0.5, -0.288675, 0.75, 'B')
|
dannysellers/django_orders | tracker/views/workorder_views.py | Python | gpl-2.0 | 5,164 | 0.012393 | from django.template import RequestContext
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from django.core.urlresolvers import reverse
... | method != 'POST':
return HttpResponseRedirect(reverse('work_orders'))
else:
# TODO: Alert the user t | o discrepancies b/w the Work Order and the Shipment (i.e. different quantity)
order = WorkOrder.objects.get(id = orderid)
ship_desc = request.POST.get('shipid')
ship_id = re.findall('#(\d+):', ship_desc)[0]
shipment = Shipment.objects.get(shipid = ship_id)
order.shipment = ship... |
cgpotts/cs224u | test/test_np_model_gradients.py | Python | apache-2.0 | 7,151 | 0.000699 | from nltk.tree import Tree
from np_shallow_neural_classifier import ShallowNeuralClassifier
from np_rnn_classifier import RNNClassifier
from np_autoencoder import Autoencoder
from np_tree_nn import TreeNN
import numpy as np
import pytest
import utils
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Sp... | ""
for param_name, d_params in param_pairs:
params = getattr(model, param_name)
# This iterator will allow is to cycle over all the values for
# arra | ys of any dimension:
iterator = np.nditer(params, flags=['multi_index'], op_flags=['readwrite'])
while not iterator.finished:
idx = iterator.multi_index
actual = params[idx]
params[idx] = actual + epsilon
_, pred = model.forward_propagation(ex)
... |
mustafa-cosar/ceng445Project | src/ApplicationProcess.py | Python | gpl-3.0 | 4,252 | 0.004468 | from multiprocessing import *
from ceng445 import *
import json
import traceback
STATUS_OK = 'OK'
STATUS_FAIL = 'FAIL'
class ApplicationProcess(Process):
def __init__(self, connectionInfo):
super(ApplicationProcess, self).__init__()
self._conn = connectionInfo[0]
self._addr = connectionInf... | and), indent='\t')
self._conn.send(result.encode('utf-8'))
except:
print("Connection closed! with pair: ", self._conn)
self._conn.close()
def handle(self, cmd):
result = {}
command = cmd.get | ('command', None)
print(cmd)
if command == 'available':
try:
result['result'] = self._app.available()
result['status'] = STATUS_OK
except:
result['status'] = STATUS_FAIL
elif command == 'loaded':
try:
... |
bmenard1/GroundSurveyor | ground_surveyor/uf_mosaic.py | Python | apache-2.0 | 5,019 | 0.003188 | import os
import json
import logging
import numpy
from osgeo import gdal
from ground_surveyor import gsconfig
def pick_best_pile_layer(pile_md_filename,
selection_options):
pile_md = json.load(open(pile_md_filename))
best_i = -1
best_value = 0
target_field = selec... | get(
'small_cross_correlation_threshold',
None | )
zero_threshold = selection_options.get('zero_threshold',
None)
for i in range(len(pile_md['sharpness'])):
if cc_threshold is not None:
cc_raw = pile_md['cross_correlation_raw'][i]
if cc_raw < cc_threshold:
continue... |
appsembler/mayan_appsembler | apps/ocr/parsers/exceptions.py | Python | gpl-3.0 | 218 | 0 | class ParserError(Exception):
"""
Raised when a text parser fails to understand a file it been passed
| or the resulting parsed text is invalid
"""
pass
class Pars | erUnknownFile(Exception):
pass
|
bytescout/ByteScout-SDK-SourceCode | Cloud API Server/Barcode Reader API/Python/Read Barcode From Uploaded File/ReadBarcodeFromUploadedFile.py | Python | apache-2.0 | 3,125 | 0.00736 | import os
import requests # pip install requests
# Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
# If it's not then please replace this with with your hosting url.
# Base URL for PDF.co Web API requests
BASE_URL = "https://localhost"
# Source file name
SourceFile = ".... | de['TypeName']}")
print(f" Value: {barcode['Value']}")
print(f" Document Page Index: {barcode['Page']}")
print(f" Rectangle: {barcode['Rect']}")
print(f" Confidence: {barcode['Confidence']}")
print("")
| else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Pres... |
RexFuzzle/sfepy | tests/test_hyperelastic_tlul.py | Python | bsd-3-clause | 3,003 | 0.00333 | input_names = {'TL': '../examples/large_deformation/hyperelastic.py',
'UL': '../examples/large_deformation/hyperelastic_ul.py',
'ULM': '../examples/large_deformation/hyperelastic_ul_up.py'}
output_name_trunk = 'test_hyperelastic_'
from sfepy.base.testing import TestCommon
from tests_basic... | name = output_name_trunk + hp
solver_options = Struct(output_filename_trunk=name,
output_format='vtk',
save_ebc=False, save_ebc_nodes=False,
save_regions=False,
... | assign_standard_hooks(self, test_conf.options.get, test_conf)
self.report( 'hyperelastic formulation: %s' % (hp, ) )
status = NLSStatus(conditions=[])
pb, state = solve_pde(test_conf,
solver_options,
nls_... |
paramsingh/backpage | backpage/urls.py | Python | mit | 315 | 0.015873 | fr | om django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'backpage.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^app/', incl | ude('app.urls'))
) |
alpine9000/amiga_examples | tools/external/amitools/amitools/fs/block/UserDirBlock.py | Python | bsd-2-clause | 2,641 | 0.009466 | import time
from Block import Block
from ..ProtectFlags import ProtectFlags
class UserDirBlock(Block):
def __init__(self, blkdev, blk_num):
Block.__init__(self, blkdev, blk_num, is_type=Block.T_SHORT, is_sub_type=Block.ST_USERDIR)
def set(self, data):
self._set_data(data)
self._read()
def read(... | .write(self)
def dump(self):
Block.dump(self,"UserDir")
print " own_key: %d" % (self.own_key)
pf = ProtectFlags(self.protect)
print " protect: 0x%x 0b%s %s" % (self.protect, pf.bin_str(), pf)
print " comment: '%s'" % self.comment
print " mod_ts: %s" % self.mod_ts
print " na... | chain: %d" % self.hash_chain
print " parent: %d" % self.parent
print " extension: %s" % self.extension
|
Toilal/roundtm | roundtm/console.py | Python | lgpl-3.0 | 1,499 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# RoundTM - A Round based Tournament Manager
# Copyright (c) 2013 Rémi Alvergnat <toilal.dev@gmail.com>
#
# RoundTM is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Fo... | init__(self, event):
self._eve | nt = event
@property
def next_round(self):
"""Go to next round, using the provided strategy"""
return self._event.next_round()
@property
def ranking(self):
"""Display current ranking"""
i = 1
for stat in self._event.ranking:
print "[%s] %s" % (i, sta... |
Microvellum/Fluid-Designer | win64-vc/2.78/scripts/freestyle/styles/apriori_density.py | Python | gpl-3.0 | 1,743 | 0.003442 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | chain(ChainPredicateIterator(upred, bpred), NotUP1D(QuantitativeInvisibilityU | P1D(0)))
shaders_list = [
ConstantThicknessShader(2),
ConstantColorShader(0.0, 0.0, 0.0, 1.0)
]
Operators.create(TrueUP1D(), shaders_list)
|
gregvw/vector-addition | test.py | Python | mit | 180 | 0.016667 | import numpy as np
from vectoradd import printvec, addvec
if __name__ == '__main__':
n = 10
a = np.arange(n)
b = 2*n | p.flipu | d(a)
c = addvec(a,b)
printvec(c)
|
taknevski/tensorflow-xsmm | tensorflow/contrib/learn/python/learn/estimators/dynamic_rnn_estimator.py | Python | apache-2.0 | 49,250 | 0.00264 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | m __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import layers
from tensorflow.contrib import rnn as contrib_rnn
from tensorflow.contrib.framework.python.framework import deprecated
from tensorflow.contrib.layers.python.layers import opti... | timators import estimator
from tensorflow.contrib.learn.python.learn.estimators import model_fn
from tensorflow.contrib.learn.python.learn.estimators import prediction_key
from tensorflow.contrib.learn.python.learn.estimators import rnn_common
from tensorflow.python.framework import dtypes
from tensorflow.python.framew... |
clkao/grano | grano/views/sessions_api.py | Python | mit | 5,328 | 0.002252 | import requests
from flask import session, Blueprint, redirect
from flask import request
from grano import authz
from grano.lib.exc import BadRequest
from grano.lib.serialisation import jsonify
from grano.views.cache import validate_cache
from grano.core import db, url_for, app
from grano.providers import github, twi... | t('next_url'):
raise BadRequest("No | 'next_url' is specified.")
session['next_url'] = request.args.get('next_url')
return twitter.authorize(callback=callback)
@blueprint.route('/api/1/sessions/callback/twitter', methods=['GET'])
@twitter.authorized_handler
def twitter_authorized(resp):
next_url = session.get('next_url', '/')
if resp is N... |
astrofrog/glue-vispy-viewers | glue_vispy_viewers/scatter/multi_scatter.py | Python | bsd-2-clause | 5,723 | 0.000175 | from __future__ import absolute_import, division, print_function
from contextlib import contextmanager
import numpy as np
from matplotlib.colors import ColorConverter
from ..extern.vispy import scene
from glue.external import six
class MultiColorScatter(scene.visuals.Markers):
"""
This is a helper class ... | yer = self.layers[label]
if not layer['visible'] or layer['data'] is None:
continue
if layer['mask'] is None:
n_points = layer['data'].shape[0]
else:
n_points = np.sum(layer['mas | k'])
if n_points > 0:
# Data
if layer['mask'] is None:
data.append(layer['data'])
else:
data.append(layer['data'][layer['mask'], :])
# Colors
if layer['color'].ndim == 1:
... |
djangothon/django-engage | django_engage/settings.py | Python | mit | 3,040 | 0 | """
Django settings for django_engage project.
Generated by 'django-admin startproject' using Djang | o 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirn... | .path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4%z9k*!y3p*yba5*^-ve^4^2rxol0f4fqvdkq41&tc5unkz=#^'
# SECURITY WARNING: do... |
Splawik/pytigon | pytigon/prj/scheditor/sched/models.py | Python | lgpl-3.0 | 531 | 0.001883 | import django
from django.db import models
from pyti | gon_lib.schdjangoext.fields import *
from pytigon_lib.schdjangoext.models import *
import pytigon_lib.schdjango | ext.fields as ext_models
from pytigon_lib.schtools import schjson
from django.utils.translation import gettext_lazy as _
from django.contrib import admin
import os, os.path
import sys
from pytigon_lib.schhtml.htmltools import superstrip
from schwiki.models import *
from schcommander.models import *
from schtasks.... |
fluidinfo/Tickery | setup.py | Python | apache-2.0 | 1,202 | 0 | #!/usr/bin/env python
import glob
from distutils.core import setup
from tickery.version import version
# Where Tickery files such as the HTML, Javascript, and the Twisted plugin
# should be installed on the destination host:
TICKERY_ROOT = '/opt/tickery'
setup(name='tickery',
version=version,
scripts=gl... | o.com',
url= | 'http://fluidinfo.com/')
|
AntonelliLab/seqcap_processor | secapr/utils.py | Python | mit | 531 | 0.011299 | #!/usr/bin/env python3
# -*- co | ding: utf-8 -*-
"""
Created on Tue Oct 15 17:08:10 2019
@author: Tobias Andermann (tobias.andermann@bioenv.gu.se)
"""
import numpy as np
np.set_printoptions(suppress=True)
import pandas as pd
import matplotlib.pyplot as plt
import os
import argparse
class CompletePath(argparse.Action):
"""give the full path of ... | namespace, values, option_string=None):
setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values)))
|
cescobarresi/ciscoreputation | ciscoreputation/__about__.py | Python | mit | 1,212 | 0.003344 | # encoding: utf-8
import os.path
__all__ = [
"__title__", "__summary__", "__uri__", "__version__",
"__author__", "__email__", "__license__", "__copyright__",
]
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
except NameError:
base_dir = None
__title__ = "ciscoreputation"
__summa | ry__ = "Get the Cisco's senderbase.org reputation for a hostname or ip address"
__uri__ = "https://github.com/cescobarresi/ciscoreputation"
# Versioning is a 3-part MAJOR.MINOR.MAINTENANCE numbering scheme, where the project author increments:
#
# MAJOR version when they make incompatible API changes,
# MINOR ve... | n when they add functionality in a backwards-compatible manner, and
# MAINTENANCE version when they make backwards-compatible bug fixes.
# zero or more dev releases (denoted with a ”.devN” suffix)
# zero or more alpha releases (denoted with a ”.aN” suffix)
# zero or more beta releases (denoted with a ”.bN”... |
sorz/isi | store/category/migrations/0001_initial.py | Python | mit | 1,172 | 0.003413 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(pri... | 'name', models.CharField(max_length=255, verbose_name='Category Name')),
('description', models.TextField(null=True)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='PropertyName',
fields=[
... | eated=True, serialize=False)),
('name', models.CharField(max_length=255, verbose_name='Property Name')),
('description', models.TextField(null=True)),
('category', models.ForeignKey(to='category.Category')),
],
options={
},
... |
Cornices/cornice.ext.swagger | cornice_swagger/converters/__init__.py | Python | apache-2.0 | 620 | 0.001613 | """
This module handles the conversion between colander obj | ect schemas and swagger
object schemas.
"""
from cornice_swagger.converters.schema import TypeConversionDispatcher
from cornice_swagger.converters.parameters import ParameterConversionDispatcher
def convert_schema(schema_node):
dispatcher = TypeConversionDispatcher()
converted = dispatcher(schema_node)
... | d = dispatcher(location, schema_node)
return converted
|
loopCM/chromium | chrome/test/chromedriver/run_java_tests.py | Python | bsd-3-clause | 10,860 | 0.009024 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs the WebDriver Java acceptance tests.
This script is called from chrome/test/chromedriver/run_all_tests.py and reports
resu... | time = test.getAttribute('time')
failure = None
error_nodes = test.getElementsByTagName('error')
failure_nodes = test.getElementsByTagName('failure')
if error_nodes:
failure = error_nodes[0].childNodes[0].nodeValue
elif failure_nodes:
failure = failure_nodes[0].childN... | t_props = ['printsummary="yes"',
'fork="yes"',
'haltonfailure="no"',
'haltonerror="no"']
if verbose:
junit_props += ['showoutput="yes"']
ant_file = open(os.path.join(test_dir, 'build.xml'), 'w')
ant_file.write(_CreateBuildConfig(
test_class, 'results',... |
Tayamarn/socorro | socorro/unittest/external/es/test_analyzers.py | Python | mpl-2.0 | 1,852 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from socorro.lib import datetimeutil
from socorro.unittest.external.es.base import (
ElasticsearchTestCase,
Supe... | s.
# import logging
# logging.getLogger('elasticsearch').setLevel(logging.ERROR)
# logging.getLogger('requests').setLevel(logging.ERROR)
class IntegrationTestAnalyzers(ElasticsearchTestCase):
"""Test the custom analyzers we create in our indices. """
def setUp(self):
super(IntegrationTestAnalyzers, s... | """Test the analyzer called `semicolon_keywords`.
That analyzer creates tokens (terms) by splitting the input on
semicolons (;) only.
"""
self.index_crash({
'date_processed': self.now,
'app_init_dlls': '/path/to/dll;;foo;C:\\bar\\boo',
})
... |
jruberg/Pyty | test/unit_tests_core.py | Python | mit | 5,812 | 0.004646 | import unittest
import ast
import sys
import logging
from datetime import datetime
import ast
# Include src in the Python search path.
sys.path.insert(0, '../src')
from ast_extensions import TypeDecASTModule
from check import (check_expr, check_mod, expr_template, call_function)
from parse_file import parse_type_decs... | ted, result, text.strip('\n')))
except err:
pass
except AssertionError | as e:
self.fail(e)
except Exception as e:
self.fail("Should have raised %s, but instead raised %s (%s):\n%s" %
(expected, e.__class__.__name__, e, text.strip('\n')))
##### Generated unit tests will go below here
##### Generated unit tests w... |
mnishida/PyMWM | src/pymwm/cylinder/__init__.py | Python | mit | 26,692 | 0.000525 | from __future__ import annotations
import cmath
import numpy as np
import psutil
import ray
import scipy.special as ssp
from pymwm.utils import cylinder_utils
from pymwm.waveguide import Database, Sampling, Waveguide
from .samples import Samples, SamplesForRay, SamplesLowLoss, SamplesLowLossForRay
class Cylinder(... | phas["h"].append(alpha)
alphas["v"].append(alpha)
return alphas
def betas_convs_samples(self, params: dict) -> tuple[dict, dict, Samples]:
im_factor = self.clad.im_factor
self.clad.im_factor = 1.0
self.clad_params["im_factor"] = 1.0
p_modes = params["modes"].... | ]
betas: dict = {}
convs: dict = {}
success = False
catalog = Database().load_catalog()
num_n_max = catalog["num_n"].max()
num_m_max = catalog["num_m"].max()
if not np.isnan(num_n_max):
for num_n, num_m in [
(n, m)
for n... |
xtiankisutsa/MARA_Framework | tools/qark/qark/lib/blessed/sequences.py | Python | lgpl-3.0 | 21,604 | 0.000231 | " This sub-module provides 'sequence awareness' for blessed."
__author__ = 'Jeff Quast <contact@jeffquast.com>'
__license__ = 'MIT'
__all__ = ['init_sequence_patterns', 'Sequence', 'SequenceTextWrapper']
import functools
import textwrap
import warnings
import math
import re
_BINTERM_UNSUPPORTED = ('kermit', 'avatar... | bility, term)
return set([
# carriage_return
re.escape(term.cr),
# column_address: Horizontal position, absolute
bnc(cap='hpa'),
# row_address: Vertical position #1 absolute
| bnc(cap='vpa'),
# cursor_address: Move to row #1 columns #2
bnc(cap='cup', nparams=2),
# cursor_down: Down one line
re.escape(term.cud1),
# cursor_home: Home cursor (if no cup)
re.escape(term.home),
# cursor_left: Move left one space
re.escape(term... |
tristan-hunt/UVaProblems | sdi.py | Python | gpl-3.0 | 1,195 | 0.057741 | import sys
#seq = list()
def memo_lis(i, memo = 0):
if memo == 0:
memo = dict()
if i == 0:
if i not in memo: #if memo[i] == None:
memo[i] = ([seq[i]])
return([seq[i]])
else:
ans = [seq[i]]
for j in range(0, i):
if seq[i] > seq[j]: # We can add seq[i] after seq[j]
if j not in memo... | o[j] = memo_lis(j, memo)
if len(memo[j])+1 > len(ans):
ans = memo[j][::1]
ans.append(seq[i])
memo[i] = ans
return(memo[i])
def print_max():
best = [seq[0]]
memo = dict()
for i in range(0, len(seq)):
if (len(memo_lis(i, memo)) > len(best)):
best = memo_lis(i, memo)
sys.stdout.write("Max... | )
def load():
this_seq = list()
next(sys.stdin) #eat the blank line
while(1):
a = next(sys.stdin)
if a == '\n':
if len(this_seq) == 0: # Handling blank newline cases
this_seq = [0]
yield(this_seq)
this_seq = list()
else:
a = int(a)
this_seq.append(a)
cases = int(next(sys.stdin))
c = 0
... |
greghaynes/dib2cloud | dib2cloud/cmd.py | Python | apache-2.0 | 2,959 | 0 | import argparse
import json
imp | ort sys
from dib2cloud import app
# This gives us a convenient place to monkeypatch for testing
def output(out):
print(out)
def upload_summary_dict(upload):
status = 'uploading'
if upload.glance_uuid is not None:
status = 'completed'
retu | rn {
'upload_name': upload.upload_name,
'glance_uuid': upload.glance_uuid,
'status': status
}
def dib_summary_dict(dib, status_str=None):
if status_str is None:
status = dib.succeeded()
if status[0] is True:
status_str = 'completed'
else:
... |
mwrlabs/veripy | contrib/rfc3633/dr/renew_message.py | Python | gpl-3.0 | 1,596 | 0.008772 | from contrib.rfc3315.constants import *
from contrib.rfc3633.dhcpv6_pd import DHCPv6PDHelper
from scapy.all import *
from veripy.assertions import *
class RenewMessageTestCase(DHCPv6PDHelper):
"""
Requesting Router Initi | ated: Renew Message
Verify that a device can properly | interoperate while using DHCPv6-PD
@private
Source: IPv6 Ready DHCPv6 Interoperability Test Suite (Section 4.2)
"""
def run(self):
prefix, p = self.do_dhcpv6_pd_handshake_as_client(self.target(1), self.node(1))
self.logger.info("Acquired the prefix %s from the DR (T1=%d)." % (... |
Osndok/zim-desktop-wiki | zim/applications.py | Python | gpl-2.0 | 11,848 | 0.026671 | # -*- coding: utf-8 -*-
# Copyright 2009,2014 Jaap Karssenberg <jaap.karssenberg@gmail.com>
'''This module contains helper classes for running external applications.
See L{zim.gui.applications} for classes with desktop integration for
applications defined in desktop entry files.
'''
import sys
import os
import logg... | ring.
If C{None} will default to C{cmd} or the first item of C{cmd}.
@param enco | ding: the encoding to use for commandline args
if known, else falls back to system default
'''
if isinstance(cmd, basestring):
cmd = split_quoted_strings(cmd)
else:
assert isinstance(cmd, (tuple, list))
assert tryexeccmd is None or isinstance(tryexeccmd, basestring)
self.cmd = tuple(cmd)
self.tryexe... |
ctaylo37/OTM2 | opentreemap/treemap/migrations/0079_convert_species_null_values_to_empty_strings.py | Python | gpl-3.0 | 22,255 | 0.007953 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for field in ('species', 'cultivar', 'other', 'gender', 'bloom_period',
'fruit_period', 'fact_sheet... | ackwards methods here."
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permis... | },
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
... |
mikr/xcodeprojer | examples/gidhistograms.py | Python | mit | 9,342 | 0.002141 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Michael Krause ( http://krause-software.com/ ).
# You are free to use this code under the MIT license:
# http://opensource.org/licenses/MIT
"""Show some histograms for a directory a Xcode project files."""
from __future__ import print_function
imp... | consider was limited to %d, this can be changed with --max-firstnames" % max_firstnames_limited)
def prin | t_names(args, users_per_year, emoji=False):
userhashes = defaultdict(list)
max_firstnames = args.max_firstnames
if max_firstnames is None:
max_firstnames = DEFAULT_FIRSTNAMES
max_firstnames_limited = None
with codecs.open(rel('firstnames.txt'), 'r', encoding='utf-8') as f:
firstnames... |
bgris/ODL_bgris | lib/python3.5/site-packages/Sphinx-1.5.1-py3.5.egg/sphinx/environment/managers/toctree.py | Python | gpl-3.0 | 25,403 | 0.000512 | # -*- coding: utf-8 -*-
"""
sphinx.environment.managers.toctree
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Toctree manager for sphinx.environment.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from six import iteritems
from docutils import n... | included file is rebuilt, this one must be
# too (since the TOC of the included file could have changed)
self.files_to_rebuild.setdefault(includefile, set()).add(docname)
self.toctree_includes.setdefault(docname, []).extend(includefiles)
def get_toc_for(self, docname, builder):
... | th', 0)
try:
toc = self.tocs[docname].deepcopy()
self._toctree_prune(toc, 2, tocdepth)
except KeyError:
# the document does not exist anymore: return a dummy node that
# renders to nothing
return nodes.paragraph()
process_only_nodes(toc... |
meejah/AutobahnPython | examples/twisted/websocket/echo_service/setup.py | Python | mit | 1,892 | 0 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# 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 with... | ight notice and this permission notice shall be | included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT... |
petewarden/tensorflow | tensorflow/python/keras/engine/input_layer.py | Python | apache-2.0 | 16,362 | 0.004462 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | not ops.executing_eagerly_outside_functions():
raise ValueError('Creating Keras inputs from a type_spec is only '
'supported when eager execution is enabled.')
input_tensor = keras_tensor.keras_tensor_from_type_spec(type_spec)
if isinstance(input_tensor, keras_tensor.Sparse... | self.ragged = True
self.is_placeholder = True
try:
self._batch_input_shape = tuple(input_tensor.sha |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.