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 |
|---|---|---|---|---|---|---|---|---|
wavelets/keras | keras/datasets/reuters.py | Python | mit | 3,237 | 0.003089 | # -*- coding: utf-8 -*-
from data_utils import get_file
import string
import random
import cPickle
def make_reuters_dataset(path='datasets/temp/reuters21578/', min_samples_per_topic=15):
import os
import re
from preprocessing.text import Tokenizer
wire_topics = []
topic_counts = {}
wire_bodies... | ': ' + str(x[1])
if x[1] >= min_samples_per_topic:
kept_topics.add(x[0])
print '-'
print 'Kept topics:', len(kept_topics)
# filter wires with rare topics
kept_wires = []
labels = []
topic_indexes = {}
for t, b in zip(wire_topics, wire_bodies):
if t in kept_topics... | else:
topic_index = topic_indexes[t]
labels.append(topic_index)
kept_wires.append(b)
# vectorize wires
tokenizer = Tokenizer()
tokenizer.fit(kept_wires)
X = tokenizer.transform(kept_wires)
print 'Sanity check:'
for w in ["banana", "oil", "chocolate", "... |
enthought/pyside | tests/QtWebKit/webframe_test.py | Python | lgpl-2.1 | 899 | 0.002225 | import unittest
import sys
from PySide.QtCore import QObject, SIGNAL, QUrl
from PySide.QtWebKit import *
from PySide.QtNetwork import QNetworkRequest
from helper import adjust_filename, UsesQApplication
class TestWebFrame(UsesQApplication):
def load_finished(self, ok):
self.assert_(ok)
page = s... | f.assert_(page)
frame = page.mainFrame()
self.assert_(frame)
met | a = frame.metaData()
self.assertEqual(meta['description'], ['PySide Test METADATA.'])
self.app.quit()
def testMetaData(self):
self.view = QWebView()
QObject.connect(self.view, SIGNAL('loadFinished(bool)'),
self.load_finished)
url = QUrl.fromLocalFile(... |
Elico-Corp/odoo-addons | multiprice_to_product_form/__openerp__.py | Python | agpl-3.0 | 1,385 | 0 | # -*- coding: utf-8 -*-
######################################## | ######################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-2015 Elico Corp (<http://www.elico-corp.com>)
# Authors: Siyuan Gu
#
# This program is free software: you can redistribute it and/or modif | y
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implie... |
NUKnightLab/slackdice | app.py | Python | mit | 1,779 | 0.003373 | from flask import Flask, request, jsonify
import random
import re
import sys
app = Flask(__name__)
SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$')
HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private')
USAGE = 'USAGE:\n' \
'`/roll [n]d[x] [options]`\n' \
'where:\n' \
' n == number of dice\n' \
... | f flag in HIDDEN else 'in_channel'
}
if num == 1:
data['text'] = str(vals[0])
else:
data['text'] = '%s = %d' % (
' + '.join( | [str(v) for v in vals]), sum(vals))
return data
@app.route("/", methods=['GET', 'POST'])
def roll():
try:
if request.method == 'POST':
spec = request.form['text']
else:
spec = request.args['spec']
return jsonify(do_roll(spec))
except:
return jsonify(... |
bfontaine/p7ldap | p7ldap/connection.py | Python | mit | 619 | 0.004847 | # -*- coding: UTF-8 -*-
import ldap
class Connection:
def __init__(self, url='ldap://annuaire.math.univ-paris-diderot.fr:389', \
base='ou=users, | dc=chevaleret,dc=univ-paris-diderot,dc=fr'):
self.base = base
self.url = url
self.con = ldap.initialize(self.url)
self.con.bind_s('', '')
def __del__(self):
self.con.unbind()
def search(self, kw, field='cn'):
| """
Search someone in the LDAP directory using a keyword
"""
qry = "%s=*%s*" % (field, kw)
return self.con.search_s(self.base, ldap.SCOPE_SUBTREE, qry, None)
|
chriskoz/OctoPrint | src/octoprint/plugins/softwareupdate/updaters/python_updater.py | Python | agpl-3.0 | 565 | 0.008881 | # coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
def can_perform_update(targ... | ater"] is not None
def perform_update(target, check, target_version, log_cb=None):
return check["python_updater"].perform_update(target, check, target_versio | n, log_cb=None)
|
oudalab/phyllo | phyllo/extractors/asconiusDB.py | Python | apache-2.0 | 2,970 | 0.005051 | import sqlite3
import urllib
import re
from urllib.request impor | t urlopen
from bs4 import BeautifulSoup
from phyllo.phyllo_logger import logger
# | Note: The original ordering of chapters and verses was extremely complex.
# As a result, chapters are the bold headers and subsections are each p tag.
# Case 1: Sections split by numbers (Roman or not) followed by a period, or bracketed. Subsections split by <p> tags
def parsecase1(ptags, c, colltitle, title, auth... |
mitzvotech/honorroll | lib/cleanup.py | Python | mit | 1,317 | 0.001519 | from pymongo import MongoClient
import os
from bson import json_util
from numpy import unique
client = MongoClient(os.environ.get("MONGOLAB_URI"))
db = client[os.environ.get("MONGOLAB_DB")]
class Organization:
def __init__(self):
self.orgs = self.get_orgs()
self.count = len(self.orgs)
def g... | get_attorneys()
self.count = len(self.attorneys)
def get_attorneys(self):
out = []
for org in db.attorneys.find():
| out.append(org)
return out
def get_unique_orgs(self):
out = []
for attorney in self.attorneys:
try:
out.append(attorney["organization_name"].strip())
except:
pass
return unique(out)
if __name__ == "__main__":
org = Or... |
MoarCatz/chat-server | installer.py | Python | gpl-3.0 | 2,510 | 0.001195 | import os, psycopg2, rsa
from urllib.parse import urlparse
class Installer:
def connect(self):
self.url = urlparse(os.environ["DATABASE_URL"])
self.db = psycopg2.connect(database=self.url.path[1:],
user=self.url.username,
... | ursor()
c.execute('''CREATE TABLE users (name text PRIMARY KEY,
password text,
friends text ARRAY,
favorites text ARRAY,
blacklist text ARR... | REFERENCES users(name),
status text,
email text,
birthday bigint,
about text,
... |
thuydang/ocrfeeder | src/ocrfeeder/odf/office.py | Python | gpl-3.0 | 3,311 | 0.028399 | # -*- coding: utf-8 -*-
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at you... | return StyleRefElement(qname = (OFFICENS,'annotation'), **args)
def AutomaticStyles(**args):
return Element(qname = (OFFICENS, 'automatic-styles'), **args)
def BinaryData(**args):
return Element(qname = (OFFICENS,'binary-data'), **args)
def Body(**args):
return Element(qname = (OFFICENS, 'body'), **ar... | = (OFFICENS,'chart'), **args)
def DdeSource(**args):
return Element(qname = (OFFICENS,'dde-source'), **args)
def Document(**args):
return Element(qname = (OFFICENS,'document'), **args)
def DocumentContent(version="1.0", **args):
return Element(qname = (OFFICENS, 'document-content'), version=version, **ar... |
jdepoix/goto_cloud | goto_cloud/test_assets/remote_host_patch_metaclass.py | Python | mit | 1,494 | 0.004016 | from unittest.mock import patch
def mocked_execute(remote_executor, command, *args, **kwargs):
from .test_assets import TestAsset
return TestAsset.REMOTE_HOST_MOCKS[remote_executor.hostname].execute(
command
)
class PatchRemoteHostMeta(type):
"""
can be used as a metaclass for a TestCase ... | patch('remote_execution.remote_execution.SshRemoteExecutor.connect', lambda self: None)(self)
patch('remote_execution.remote_execution.SshRemoteExecutor.close', lambda self: None)(self)
patch('remote_execution.remote_execution.SshRemoteExecutor.is_connected', lambda self: True)(self)
patch(
... | )(self)
class PatchTrackedRemoteExecutionMeta(PatchRemoteHostMeta):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.executed_commands = set()
def tracked_mocked_execute(remote_host, command, *args, **kwargs):
self.executed_commands.add(command)
... |
anehx/anonboard-backend | core/models.py | Python | mit | 2,696 | 0.006677 | from django.db import models
from django.utils import timezone
from user.models import User
from adminsortable.models import SortableMixin
class Topic(SortableMixin):
'''
Model to define the behaviour of a topic
| '''
class Meta:
'''
Meta options for topic model
Defines the default ordering
'''
ordering = [ 'order' ]
name = models.CharField(max_length=50, unique=True)
identifier = models.SlugField(max_length=50, unique=True)
description = models.CharField(max_l... | t=0,
editable=False,
db_index=True
)
@property
def threads_last_day(self):
'''
Counts the amount of threads in this topic
created in the last 24 hours
:return: The amount of threads
:rtype: int
'''
last_day = timezone.now() - timezon... |
swirlingsand/deep-learning-foundations | play/multi-layer.py | Python | mit | 771 | 0.001297 | import numpy as np
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-x))
# Network size
N_input = 4
N_hidden = 3
N_output = 2
np.random.seed(42)
# Make some fake data
X = np.random.randn(4)
weights_input_to_hidden = np.random.normal(
0, scale=0.1, size=(N_input, N_hidden))
weigh... | t(X, weights_input_to_hidden)
hidden_layer_out = sigmoid(hidden_layer_in)
print('Hidden-layer Output:')
print(hidden_layer_out)
| output_layer_in = np.dot(hidden_layer_out, weights_hidden_to_output)
output_layer_out = sigmoid(output_layer_in)
print('Output-layer Output:')
print(output_layer_out)
|
cysuncn/python | spark/crm/PROC_O_FIN_FIN_PRODAREAINFO.py | Python | gpl-3.0 | 7,144 | 0.012726 | #coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_O_FIN_FIN_PRODAREAINFO').setMaster(sys.argv[2])
sc = SparkContext(conf = conf... | --备用1:src.NOTE1
,DST.NOTE2 --备用2:src.NOTE2
,DST.NOTE3 | --备用3:src.NOTE3
,DST.NOTE4 --备用4:src.NOTE4
,DST.NOTE5 --备用5:src.NOTE5
,DST.FR_ID --法人代码:src.FR_ID
,DST.ODS_ST_DATE -... |
bbarrows89/CSC110_Projects | fahrenheit.py | Python | mit | 341 | 0.01173 | # Bryan Barrows |
# CSC 110 - Winter 17
# fahrenheit.py
# The purpose of this program is to convert a user input tempera | ture from celsius to fahrenheit.
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = (9/5) * celsius + 32
print("The temperature is ",fahrenheit," degrees Fahrenheit.")
main()
|
dataplumber/edge | src/main/python/plugins/slcp/indicator/Writer.py | Python | apache-2.0 | 2,746 | 0.003277 | import logging
import urllib
import json
from edge.writer.proxywriter import ProxyWriter
class Writer(ProxyWriter):
def __init__(self, configFilePath):
super(Writer, self).__init__(configFilePath)
def _generateUrl(self, requestHandler):
url = self._configuration.get('solr', 'url')
par... | value in response.headers.iteritems():
logging.debug('header: '+name+':'+value)
self.requestHandler.set_header(name, value)
self.requestHandler.set_header('Access-Control-Allow-Origin', '*')
solrJson = json.loads(response.body)
if len(solrJson['respon... | ponse']['start'] = solrJson['response']['start']
solrJsonClone['response']['numFound'] = solrJson['response']['numFound']
solrJsonClone['response']['docs'] = []
indicators = {}
for doc in solrJson['response']['docs']:
indicators[doc['i... |
mitocw/edx-platform | openedx/tests/settings.py | Python | agpl-3.0 | 3,886 | 0.001544 | """
Minimal Django settings for tests of common/lib.
Required in Django 1.9+ due to imports of models in stock Django apps.
"""
import sys
import tempfile
from django.utils.translation import ugettext_lazy as _
from path import Path
# TODO: Remove the rest of the sys.path modification here and in (cms|lms)/envs/com... | : '',
'HOST': '',
'PORT': '' | ,
}
}
PROCTORING_BACKENDS = {
'DEFAULT': 'mock',
'mock': {},
'mock_proctoring_without_rules': {},
}
FEATURES = {}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'djcelery',
'django_sites_extensions',
... |
emundus/v6 | plugins/fabrik_visualization/fusionchart/libs/fusioncharts-suite-xt/integrations/django/samples/fusioncharts/samples/dynamic_chart_resize.py | Python | gpl-2.0 | 1,972 | 0.010649 | from django.shortcuts import render
from django.http import HttpResponse
# Include the `fusioncharts.py` file which has required functions to embed the charts in html page
from ..fusioncharts import FusionCharts
# Loading Data from a Static JSON String
# It is a example to show a Column 2D chart where data is passed ... | using the FusionCharts class constructor
column2d = FusionCharts("column2d", "ex1", '100%', '100%', "chartContainer", "json",
# The chart data is passed as a string to the `dataSource` parameter.
"""{
"chart":
{
"cap | tion": "Countries With Most Oil Reserves [2017-18]",
"subcaption": "In MMbbl = One Million barrels",
"xaxisname": "Country",
"yaxisname": "Reserves (MMbbl)",
"numbersuffix": "K",
"theme": "fusion"
},
"data": [{
... |
AdvancedClimateSystems/python-modbus | tests/system/responses/test_succesful_responses.py | Python | mpl-2.0 | 2,290 | 0 | import pytest
from umodbus import conf
from umodbus.client import tcp
@pytest.fixture(scope='module', autou | se=True)
def enable_signed_values(request):
""" Use signed values when running tests it this module. """
tmp = conf.SIGNED_VALUES
conf.SIGNED_VALUES = True
def fin():
conf.SIGNED_VALUES = tmp
request.addfinalizer(fin)
@pytest.mark.parametrize('function', [
tcp.read_coils,
tcp.rea... | """
slave_id, starting_address, quantity = (1, 0, 10)
req_adu = function(slave_id, starting_address, quantity)
assert tcp.send_message(req_adu, sock) == [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
@pytest.mark.parametrize('function', [
tcp.read_holding_registers,
tcp.read_input_registers,
])
def test_respons... |
thejeshgn/quest | quest/admin.py | Python | gpl-3.0 | 213 | 0.037559 | from .models import *
fr | om django.contrib import admin
class PingLogAdmin(admin.ModelAdmin):
list_display = ('id','hash_key','url','ip_address','user_agent','time')
admin.site.register( | PingLog, PingLogAdmin) |
Azure/azure-sdk-for-python | sdk/scheduler/azure-mgmt-scheduler/azure/mgmt/scheduler/models/_models_py3.py | Python | mit | 48,388 | 0.002232 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | sage: Gets or sets the storage queue message.
:type queue_message: ~azure.mgmt.scheduler.models.StorageQueueMessage
:param service_bus_queue_message: Gets or sets the service bus queue messa | ge.
:type service_bus_queue_message: ~azure.mgmt.scheduler.models.ServiceBusQueueMessage
:param service_bus_topic_message: Gets or sets the service bus topic message.
:type service_bus_topic_message: ~azure.mgmt.scheduler.models.ServiceBusTopicMessage
:param retry_policy: Gets or sets the retry policy.
... |
mykonosbiennale/mykonosbiennale.github.io | tasks.py | Python | apache-2.0 | 552 | 0.018116 | from invoke import task
@task
def runserver(c):
| c.run("PYTHONHTTPSVERIFY=0; ./manage.py runserver --settings=mykonosbiennale.offline_settings")
def export_artists(c):
c.run("PYTHONHTTPSVERIFY=0; ./manage.py export_artists - -settings = mykonosbiennale.offline_settings") |
def export_filmfestival(c):
c.run("PYTHONHTTPSVERIFY=0; ./manage.py export_filmfestival - -settings = mykonosbiennale.offline_settings")
def staticsitegen(c):
c.run("PYTHONHTTPSVERIFY=0; ./manage.py staticsitegen --settings=mykonosbiennale.offline_settings")
|
sora7/listparse | OLD/lp2/listparse.py | Python | gpl-2.0 | 77,022 | 0.006116 | #!/usr/bin/env python2
## PYTHON 2!!!!!!!!!!!!!!!!!!!
# -*- coding: utf-8 -*-
#======== | =================================================================== | ===#
import os
import sys
import re
import StringIO
import shutil
# import tkFileDialog
import HTMLParser
import re
import base64
import Tkinter
import ttk
#------------------------------------------------------------------------------#
MODULES_DIR = 'modules'
WH_DIR = 'wh'
INFO_DIR = 'info'
M_DIR = 'M'
N_DIR = 'N'
... |
TaliesinSkye/evennia | src/commands/default/comms.py | Python | bsd-3-clause | 38,986 | 0.003283 | """
Comsystem command module.
Comm commands are OOC commands and intended to be made available to
the Player at all times (they go into the PlayerCmdSet). So we
make sure to homogenize self.caller to always be the player object
for easy handling.
"""
from django.conf import settings
from src.comms.models import Chann... | s = ["aliaschan","chanalias"]
help_category = "Comms"
locks = "cmd:not pperm(channel_banned)"
def func(self):
"Implement the command"
caller = self.caller
args | = self.args
player = caller
if not args:
self.msg("Usage: addcom [alias =] channelname.")
return
if self.rhs:
# rhs holds the channelname
channelname = self.rhs
alias = self.lhs
else:
channelname = self.args
... |
bjornt/PyGlow | examples/bin_clock.py | Python | mit | 1,233 | 0 | #!/usr/bin/env python2
#####
#
# PyGlow
#
#####
#
# Python module to control Pimoronis PiGlow
# [http://shop.pimoroni.com/products/piglow]
#
# * bin_clock.py - binary clock by Jiri Tyr
#
#####
from __future__ import print_function
from datetime import datetime
from PyGlow import PyGlow, ARM_LED_LIST, BOTH
from sys ... | = []
for arm_index, arm_bin in enumerate(bin_time[0:3]):
for led_index, c in enumerate("%0.6d" % arm_ | bin):
if c == '1':
lst.append(ARM_LED_LIST[arm_index][led_index])
pg.set_leds(lst).update_leds()
def main():
print(' %5s | %6s | %6s' % ('Hour', 'Minute', 'Second'))
pg = PyGlow(brightness=150, pulse=True, speed=1000, pulse_dir=BOTH)
try:
while True:
... |
wisfern/vnpy | beta/gateway/korbitGateway/__init__.py | Python | mit | 245 | 0.004082 | # encoding: UTF-8
from vnpy.tr | ader import vtConstant
from korbitGateway import korbitGateway
gatewayClass = korbitGateway
gatewayName = 'KORBIT'
gateway | DisplayName = u'KORBIT'
gatewayType = vtConstant.GATEWAYTYPE_BTC
gatewayQryEnabled = True
|
SripriyaSeetharam/tacker | tacker/vm/drivers/heat/heat.py | Python | apache-2.0 | 17,136 | 0.000117 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2015 Intel Corporation.
# Copyright 2015 Isaku Yamahata <isaku.yamahata at intel com>
# <isaku.yamahata at gmail com>
# All Rights Reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not u... | ttributes'].copy()
vnfd_yaml = attributes.pop('vnfd' | , None)
fields = dict((key, attributes.pop(key)) for key
in ('stack_name', 'template_url', 'template')
if key in attributes)
for key in ('files', 'parameters'):
if key in attributes:
fields[key] = jsonutils.loads(attributes.pop(key)... |
beav/pulp | devel/pulp/devel/unit/server/base.py | Python | gpl-2.0 | 2,511 | 0.003584 | import os
import unittest
import mock
from pulp.server.db import connection
class PulpWebservicesTests(unittest.TestCase):
"""
Base class for tests of webservice controllers. This base is used to work around the
authentication tests for each each method
"""
def setUp(self):
connection.in... | h(self, *args):
"""
:param object_id: the id of the object to get the uri for |
:type object_id: str
"""
return os.path.join('/mock', *args) + '/' |
tallstreet/jaikuenginepatch | join/tests.py | Python | apache-2.0 | 4,711 | 0.005731 | import Cookie
import os
from django.conf import settings
from common.tests import ViewTestCase
from common import api
from common import clean
from common import util
class JoinTest(ViewTestCase):
def setUp(self):
super(JoinTest, self).setUp()
self.form_data = {'nick': 'johndoe',
'fi... | vite': ''
}
def tearDown(self):
self.form_data = None
def assert_join_validation_error(self, response, content):
self.assertContains(response, content)
self.assertTemplateUsed(response, 'join.html')
self.assertTemplateUsed(response, 'form_error.html')
def test_join_page(sel... | = self.client.post('/join', self.form_data)
r = self.assertRedirectsPrefix(r, '/welcome')
def test_join_with_invalid_email(self):
self.form_data['email'] = 'invalid'
r = self.client.post('/join', self.form_data)
self.assert_join_validation_error(r, 'supply a valid email address')
def test_join_wit... |
SUSE/azure-sdk-for-python | azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2017_06_01_preview/models/regenerate_credential_parameters.py | Python | mit | 1,115 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 06_01_preview.models.PasswordName>`
"""
_validation = {
'name': {'required': True},
}
_attribute_map = | {
'name': {'key': 'name', 'type': 'PasswordName'},
}
def __init__(self, name):
self.name = name
|
google/nerfactor | third_party/xiuminglib/xiuminglib/io/np.py | Python | apache-2.0 | 1,973 | 0.000507 | from os.path import dirname
import numpy as np
from ..os import open_file, exists_isdir, makedirs
from ..log import get_logger
logger = get_logger()
def read_or_write(data_f, fallback=None):
"""Loads the data file if it exists. Otherwise, if fallback is provided,
call fallback and save its return to disk.
... | dings. It should not take argume | nts, but if yours requires taking
arguments, just wrap yours with::
fallback=lambda: your_fancy_func(var0, var1)
Returns:
Data loaded if ``data_f`` exists; otherwise, ``fallback``'s return
(``None`` if no fallback).
Writes
- Return by the fallback, if provi... |
sequana/sequana | sequana/utils/singleton.py | Python | bsd-3-clause | 329 | 0.015198 |
# a singleton to avoid loading specific classes such as
# sequana.taxonomy.Taxonomy
class | Singleton(type):
_instances = {}
de | f __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
|
vguerci/Deluge.app | deluge/ui/tracker_icons.py | Python | gpl-3.0 | 19,201 | 0.002187 | #
# tracker_icons.py
#
# Copyright (C) 2010 John Garland <johnnybg+deluge@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any l... | lparse import urljoin, urlparse
from tempfile import mkstemp
from twisted.intern | et import defer, threads
from twisted.web.error import PageRedirect
try:
from twisted.web.resource import NoResource, ForbiddenResource
except ImportError:
# twisted 8
from twisted.web.error import NoResource, ForbiddenResource
from deluge.component import Component
from deluge.configmanager import get_con... |
davidyezsetz/kuma | kuma/contentflagging/utils.py | Python | mpl-2.0 | 1,154 | 0.000867 | import hashlib
from kuma.core.utils import get_ip
def get_unique(content_type, object_pk, request=None, ip=None, user_agent=None, user=None):
"""Extract a set of unique identifiers from the request.
This set will be made up of one of the following combinations, depending
on what's available:
* user... | ent_type.pk, object_pk, ip, user_agent,
(user and user.pk or 'None')
))
unique_hash = hashlib.md5(h | ash_text).hexdigest()
return (user, ip, user_agent, unique_hash)
|
fadawar/infinit-lunch | main.py | Python | gpl-3.0 | 2,316 | 0.001727 | #!/usr/bin/env python3
import asyncio
import os
from datetime import datetime
import aiohttp
from aiohttp import web
from raven import Client
from restaurants import (FormattedMenus, SafeRestaurant, OtherRestaurant,
AvalonRestaurant, TOTORestaurant, TOTOCantinaRestaurant,
... | ther restaurants first, will be in header.
menus = [await SafeRestaurant(OtherRestaurant()).retrieve_menu()]
for future in asyncio.as_completed(futures):
menus.append(await future)
return menus
async def index(request):
if is_work_day():
async with aiohttp.ClientSession() as session:
... | d_send_to_slack(secret_key):
await Channel(SLACK_HOOK, session).send(menus)
return web.Response(text=str(menus))
return web.Response(text='Come on Monday-Friday')
sentry_client = Client() # credentials is taken from environment variable SENTRY_DSN
app = web.Application(debu... |
pacoqueen/ginn | extra/scripts/ipython_session_obra_su_almacen.py | Python | gpl-2.0 | 1,431 | 0.006289 | # coding: utf-8
# %save en ipython is wonderful. Cargar con ipython -i para continuar.
from framework import pclases
a = pclases.Obra.selectBy(nombre = "SU ALMACEN")[0]
len(a.clientes)
for c in a.clientes:
print c.nombre
vacidas = [o for o in pclases.Obra.select() if not o.clientes]
len(vacidas)
for o in vacid... |
c.sync()
ref = pclases.Cliente.select(pclases.Cliente.q.nombre.contains("REFRESCO I"))[0]
oref = ref.get_obra_generica()
for c in a.contactos:
c.removeObra(a)
c.addObra(oref)
c.sync()
len(a.presupuestos)
| len(a.facturasVenta)
len(a.pedidosVenta)
|
spillai/procgraph | src/procgraph_mplayer/depth_buffer.py | Python | lgpl-3.0 | 1,391 | 0.008627 | import numpy as np
from procgraph import Block
from contracts import contract
class DepthBuffer(Block):
Block.alias('depth_buffer')
Block.input('rgba')
Block.output('rgba')
Block.output('line')
Block.output('depth')
def init(self):
self.depth = None
def update(s... | gba = self.input.rgba
if self.depth is None:
H, W = rgba.shape[0:2]
self.depth = np.zeros((H, W))
self.depth.fill(0)
d = get_depth(rgba)
mask = rgba[:, :, 3] > 0
closer = np.logical_and(self.depth < d, mask)
| farther = np.logical_not(closer)
self.depth[closer] = d
rgba = rgba.copy()
rgba[farther, 3] = 0
with_line = rgba[:, :, 0:3].copy()
with_line[d, :, 0] = 255
with_line[d, :, 1] = 55
depth = self.depth.copy()
depth[depth == 0... |
CrowdStrike/mellon | mellon/factories/git/file.py | Python | mit | 4,601 | 0.00739 | import os.path
from zope import component
from zope import interface
from zope.component.factory import Factory
from sparc.configuration import container
import mellon
from mellon.factories.filesystem.file import MellonByteFileFromFilePathAndConfig
from mellon.factories.filesystem.file import \
... | commit,
path,
self.config)
else:
yield component.createObject(\
u'mellon.factories.git.unicode_file_from_commit_path_and_config',
| commit,
path,
self.config)
MellonFileProviderForGitReposBaseDirectoryFactory = Factory(MellonFileProviderForGitReposBaseDirectory)
interface.alsoProvides(MellonFileProviderForGitReposBaseDirectoryFactory, mellon.IMellonFileProviderFactory) |
tdtrask/ansible | lib/ansible/modules/network/aci/aci_switch_leaf_selector.py | Python | gpl-3.0 | 10,067 | 0.002384 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Bruno Calogero <brunocalogero@hotmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_... | 'from', 'to']]
]
)
| description = module.params['description']
leaf_profile = module.params['leaf_profile']
leaf = module.params['leaf']
leaf_node_blk = module.params['leaf_node_blk']
leaf_node_blk_description = module.params['leaf_node_blk_description']
from_ = module.params['from']
to_ = module.params['to']
p... |
unho/translate | translate/storage/test_directory.py | Python | gpl-2.0 | 2,774 | 0 | """Tests for the directory module"""
import os
from translate.storage import directory
class TestDirectory:
"""a test class to run tests on a test Pootle Server"""
def setup_method(self, method):
"""sets up a test directory"""
print("setup_method called on", self.__class__.__name__)
... | os.rmdir(os.path.join(dirpath, name))
if os.path.exists(dirname):
os.rmdir(dirname)
assert not os.path.exists(dirname)
def touchfiles(self, dir, filenames, content=None):
for filename in filenames:
with open(os.path.join(dir, filename), "w") as fh:
... | self.testdir, dir))
def test_created(self):
"""test that the directory actually exists"""
print(self.testdir)
assert os.path.isdir(self.testdir)
def test_basic(self):
"""Tests basic functionality."""
files = ["a.po", "b.po", "c.po"]
files.sort()
self.tou... |
amwelch/a10sdk-python | a10sdk/core/vrrp/vrrp_a_state_stats.py | Python | apache-2.0 | 19,224 | 0.00515 | from a10sdk.common.A10BaseClass import A10BaseClass
class Stats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param sync_tx_create_ext_bit_counter: {"description": "Conn Sync Create with Ext Sent counter", "format": "counter", "type": "number", "oid": "29", "optional"... | sync_rx_persist_update_age_counter: {"description": "Conn Sync Update Persist Age Pkts Received counter", "format": "counter", "type": " | number", "oid": "11", "optional": true, "size": "2"}
:param sync_rx_type_invalid: {"description": "Conn Sync Type Invalid", "format": "counter", "type": "number", "oid": "57", "optional": true, "size": "8"}
:param sync_rx_ext_rtsp: {"description": "Conn Sync Ext RTSP", "format": "counter", "type": "number", "oi... |
Ebag333/Pyfa | eos/effects/shipbonuscarrierc4warfarelinksbonus.py | Python | gpl-3.0 | 1,348 | 0.007418 | # shipBonusCarrierC4WarfareLinksBonus
#
# Used by:
# Ship: Chimera
type = "passive"
def handler(fit, src, context):
fit.modules.filteredItemBoost(
lambda mod: mod.item.requiresSkill("Shield Command") or mod.item.requiresSkill("Information Command"),
"warfareBuff2Value", src.getModifiedItemAttr("sh... | Caldari Carrier")
fit.modules.filteredItemBoost(
lambda mod: mod.item.requiresSkill("Shield Command") or mod.ite | m.requiresSkill("Information Command"),
"warfareBuff1Value", src.getModifiedItemAttr("shipBonusCarrierC4"), skill="Caldari Carrier")
|
IndicoDataSolutions/IndicoIo-python | tests/etc/test_url.py | Python | mit | 467 | 0.002141 | i | mport unittest
from indicoio import config, fer
class TestBatchSize(unittest.TestCase):
def setUp(self):
self.api_key = config.api_key
if not self.api_key:
raise unittest.SkipTest
def test_url_support(self):
test_url = "https://s3-us-west-2.amazonaws.com/indico-test-data... | f.assertEqual(len(response.keys()), 6)
|
kohr-h/odl | odl/test/solvers/smooth/smooth_test.py | Python | mpl-2.0 | 5,137 | 0 | # Copyright 2014-2017 The ODL contributors
#
# This file is part of ODL.
#
# 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 https://mozilla.org/MPL/2.0/.
"""Test for the smooth solvers."""
from __f... | 5, -3],
[2, -3, 8]])
vector = space.element([1, 2, 3])
# Calibrate so that functional is zero in optimal point
constant = 1 / 4 * vector.inner(matrix.inverse(vector))
return odl.solvers.QuadraticForm(
operator=matrix, vector=vector, cons... | odl.solvers.RosenbrockFunctional(odl.rn(2), scale=2)
# Center at zero
return rosenbrock.translated([-1, -1])
else:
assert False
@pytest.fixture(scope="module", params=['constant', 'backtracking'])
def functional_and_linesearch(request, functional):
"""Return functional with optimum 0... |
Teagan42/home-assistant | tests/components/dyson/test_fan.py | Python | apache-2.0 | 30,624 | 0.000229 | """Test the Dyson fan component."""
import json
import unittest
from unittest import mock
import asynctest
from libpurecool.const import FanMode, FanSpeed, NightMode, Oscillation
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_cool_link import DysonPureCoolLink
from libpurecool.dyson_... | g = device.set_configuration
set_config.assert_called_with(
fan_mode=FanMode.FAN, fan_speed=FanSpeed.FAN_SPEED_1
)
component.set_speed("AUTO")
set_config = device.set_configuration
set_config.assert_called_with(fan_mode=FanMode.AUTO)
def test_dyson_turn_on(self)... | s, device)
assert not component.should_poll
component.turn_on()
set_config = device.set_configuration
set_config.assert_called_with(fan_mode=FanMode.FAN)
def test_dyson_turn_night_mode(self):
"""Test turn on fan with night mode."""
device = _get_device_on()
c... |
WikiWatershed/tr-55 | tr55/model.py | Python | apache-2.0 | 13,671 | 0.000658 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
"""
TR-55 Model Implementation
A mapping between variable/parameter names found in the TR-55 document
and variables used in this program are as follows:
* `precip` is referred to as P... | for modificat | ion in (census.get('modifications') or []):
for (orig_cell, subcensus) in modification['distribution'].items():
n = subcensus['cell_count']
soil1, land1 = orig_cell.split(':')
soil2, land2, bmp = modification['change'].split(':')
changed_cell = '%s:%s:%s' % (soil2... |
Mirantis/tempest | tempest/api/volume/admin/test_volume_quotas_negative.py | Python | apache-2.0 | 3,331 | 0 | # Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | uota_set(
self.demo_tenant_id,
**new_quota_set)
self.assertRaises(exceptions.OverLimit,
self.volumes_client.create_volume,
size=1)
new_quota_set = {'gigabytes': 2, 'volumes': 1, 'snapshots': 2}
resp, quota_set = self.qu... | t.update_quota_set(
self.demo_tenant_id,
**self.shared_quota_set)
self.assertRaises(exceptions.OverLimit,
self.snapshots_client.create_snapshot,
self.volume['id'])
class VolumeQuotasNegativeTestXML(VolumeQuotasNegativeTestJSON):
_... |
gangadharkadam/tailorerp | erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py | Python | agpl-3.0 | 2,666 | 0.026632 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
def execute(filters=None):
if not filters: filters = {}
columns = get_columns(fil... | batch in sorted(iwb_map[item][wh]):
qty_dict = iwb_map[item][wh][batch]
data.append([item, item_map[item]["item_name"],
item_map[item] | ["description"], wh, batch,
qty_dict.opening_qty, qty_dict.in_qty,
qty_dict.out_qty, qty_dict.bal_qty
])
return columns, data
def get_columns(filters):
"""return columns based on filters"""
columns = [_("Item") + ":Link/Item:100"] + [_("Item Name") + "::150"] + [_("Description") + "::150"] + \
[_("... |
imallett/MOSS | resources/bytemap font/echo as array.py | Python | mit | 923 | 0.021668 | f = open("font.txt","rb")
fontdata = f.re | ad()
f.close()
out = "static char font[128][5] = {"
for i in xrange(128):
out += "{"
#Encode these into 7 bit "byte"s, with MSB=0
#We don't save anything by using 8-bit bytes; the last five bits of the last byte spill over, so we still get 5 bytes/char
bits = []
for j in xr | ange(5*7):
bits.append( ord(fontdata[(5*7)*i+j])&0x01 )
## print bits
for j in xrange(5):
byte_bits = bits[7*j:7*j+7]
## print byte_bits
byte_bits = [byte_bits[i]<<(7-i-1) for i in xrange(7)]
## print byte_bits
byte = 0x00
for k in byte_bits: byte |=... |
P1R/freeMonoCrom | MM.py | Python | gpl-2.0 | 5,424 | 0.014381 | '''
Modulo Movimiento Nanometros
@author: P1R0
import ObjSerial, sys;
ObjSer = ObjSerial.ObjSerial(0,9600)
ObjSer.cts = True
ObjSer.dtr = True
ObjSer.bytesize = 8
'''
SxN = 59.71 #Constante de Calibracion del Motor
#Funcion para inicializar Monocromador
def init(ObjSer,A):
ObjSer.flushOutput()
ObjSe... | de("0M3\r\n"));
echo(ObjSer);
'''
if __name__ == "__main__":
N = 0;
LastPos = 0;
init(0);
while 1:
while type(N)!= float:
try:
N = raw_input("Ingresa Nanometros o quit para cerrar:");
if N == "quit":
ObjSer.close();
... | ;
except (ValueError, TypeError):
print "error, el valor debe ObjSer entero o flotante";
LastPos = Calcula(N,LastPos);
print "los microspasos totales son: %d" % LastPos;
N=0
''' |
lgarest/django_snippets_api | snippets/v3_0/urls.py | Python | gpl-2.0 | 353 | 0.002833 | from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
fro | m snippets.v3_0 import views
urlpatterns = patterns('',
url(r'^v3_0/snippets/$' | , views.SnippetList.as_view()),
url(r'^v3_0/snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
)
urlpatterns = format_suffix_patterns(urlpatterns)
|
gloaec/trifle | src/rdflib/plugins/serializers/turtle.py | Python | gpl-3.0 | 12,175 | 0.000903 | """
Turtle RDF graph serializer for RDFLib.
See <http://www.w3.org/TeamSubmission/turtle/> for syntax specification.
"""
from collections import defaultdict
from rdflib.term import BNode, Literal, URIRef
from rdflib.exceptions import Error
from rdflib.serializer import Serializer
from rdflib.namespace import RDF, RDF... | True
for subject in subjects_list:
if self.isDone(subject):
continue
if firstTime:
firstTime = False
| if self.statement(subject) and not firstTime:
self.write('\n')
self.endDocument()
stream.write(u"\n".encode('ascii'))
def preprocessTriple(self, triple):
super(TurtleSerializer, self).preprocessTriple(triple)
for i, node in enumerate(triple):
if no... |
lycheng/leetcode | tests/test_linked_list.py | Python | mit | 2,549 | 0 | # -*- coding: utf-8 -*-
import unittest
from linked_list import (delete_node, list_cycle, remove_elements,
reverse_list)
from public import ListNode
class TestLinkedList(unittest.TestCase):
def test_delete_node(self):
so = delete_node.Solution()
head = ListNode(1)
... | = reverse_list.Solution()
self.assertFalse(so.reverseList_iteratively(None))
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
self.assertEqual(so.reverseList_iteratively(head).val, 3)
self.assertFalse(so.reverseList_recursively(None))
head... | ode(3)
self.assertEqual(so.reverseList_recursively(head).val, 3)
|
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/urbansim/gridcell/total_improvement_value_per_residential_unit_within_walking_distance.py | Python | gpl-2.0 | 2,680 | 0.011194 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
from numpy import ma
from numpy import float32
class total_improvement_value_per_residentia... | 'residential_units': array([0, 0, 0, 0]),
},
'urbansim_constant':{
"walking_distance_circle_radius": array([150]),
'cell_si | ze': array([150]),
}
}
)
should_be = array([1800, 3100, 4600, 6000])
tester.test_is_equal_for_variable_defined_by_this_module(self, should_be)
if __name__=='__main__':
opus_unittest.main() |
slx-dev/digital-kanban | src/klopfer.py | Python | mit | 1,083 | 0 | import directory
import scanner
import mapper
import board
import os
class Klopfer(object):
def __init__(self, import_dir, export_dir):
self.import_dir = import_dir
self.export_dir = export_dir
print "Klopfer class"
def run(self):
# open dir and get oldest file with the given... | # open image
scan = scanner.Scanner(self.imagefile.name)
self.remove_image()
informations = scan.scan()
# load board_id and cards
mapping = mapper.Mapper(informations)
board_id = mapping.board_id
cards = mapping.get_cards()
# create board
curre... | # Uncomment in production version when multiple input files are present
# os.remove(self.imagefile.name)
pass
|
bashu/django-easy-seo | seo/south_migrations/0004_auto__del_url__del_unique_url_url_site.py | Python | gpl-3.0 | 2,904 | 0.00792 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Url', fields ['url', 'site']
db.delete_unique('seo_url', ['url', 'site_id']... |
},
'seo.seo': {
'Meta': {'unique_together': "(('content_t | ype', 'object_id'),)", 'object_name': 'Seo'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
'id': ('djan... |
ebukoz/thrive | erpnext/demo/user/manufacturing.py | Python | gpl-3.0 | 4,593 | 0.027433 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, random, erpnext
from datetime import timedelta
from frappe.utils.make_random import how_many
from frappe.desk import query_report
from e... | _materia | l_requests")
ppt.save()
ppt.submit()
ppt.run_method("raise_work_orders")
frappe.db.commit()
# submit work orders
for pro in frappe.db.get_values("Work Order", {"docstatus": 0}, "name"):
b = frappe.get_doc("Work Order", pro[0])
b.wip_warehouse = "Work in Progress - WPL"
b.submit()
frappe.db.commit()
# s... |
alexkolar/pyvmomi | tests/test_iso8601.py | Python | apache-2.0 | 4,117 | 0 | # VMware vSphere Python SDK
# Copyright (c) 2008-2015 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | if not correct_time_string(r.body):
return False
return True
my_vcr = vcr.VCR()
my_vcr.register_matcher('document', check_date_time_value)
# NOTE (hartsock): the `match_on` option is altered to use the
# look at the XML body sent to the server
... | res_path,
record_mode='once',
match_on=['method', 'scheme', 'host', 'port',
'path', 'query', 'document']):
si = connect.SmartConnect(host='vcsa',
user='my_user',... |
jansohn/pyload | module/plugins/hoster/OboomCom.py | Python | gpl-3.0 | 4,627 | 0.004322 | # -*- coding: utf-8 -*-
#
# Test links:
# https://www.oboom.com/B7CYZIEB/10Mio.dat
import re
from module.common.json_layer import json_loads
from module.plugins.internal.Hoster import Hoster
from module.plugins.captcha.ReCaptcha import ReCaptcha
class OboomCom(Hoster):
__name__ = "OboomCom"
__type__ =... | = self.load_url(apiUrl)
if result[0] == 200:
self.session_token = result[1]
else:
self.fail(_("Could not retrieve token for guest session. Error code: %s") % result[0])
def | solve_captcha(self):
recaptcha = ReCaptcha(self)
response, challenge = recaptcha.challenge(self.RECAPTCHA_KEY)
apiUrl = "http://www.oboom.com/1.0/download/ticket"
params = {'recaptcha_challenge_field': challenge,
'recaptcha_response_field': response,
... |
sbidoul/buildbot | worker/buildbot_worker/monkeypatches/testcase_assert.py | Python | gpl-2.0 | 2,243 | 0.001337 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | p = re.compile(expected_regexp)
if not expected_regexp.search(str(exception)):
self.fail('"%s" does not match "%s"' %
(expected_regexp.pattern, str(exception)))
def patch():
hasAssertRaisesRegexp = getattr(unittest.TestCase, "assertRaisesRegexp", None)
hasAssertRaisesRegex = get... | not hasAssertRaisesRegexp:
# Python 2.6
unittest.TestCase.assertRaisesRegexp = _assertRaisesRegexp
if not hasAssertRaisesRegex:
# Python 2.6 and Python 2.7
unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
|
china-x-orion/infoeye | tools/netstat.py | Python | mit | 966 | 0.024845 | #!/usr/bin/python
"""
Author: rockylinux
E-Mail: Jingzheng.W@gmail.com
"""
import commands
#display the living connections
#return a list containning living connections
class netstat:
def __init__(self):
self.__name = 'netstat'
def getData(self):
(status, output) = commands.getstatusou | tput('netstat -ntu | /usr/bin/awk \'NR>2 {sub(/:[^:]+$/, ""); print $5}\' | sort | uniq -c')
#return output.split('\n')
rst = [i.strip().split() for i in output.split("\n")]
if len(rst[0]) == 0:
print [["", ""]]
else:
print rst
#[i.strip().split... | nt i
else:
print test
if __name__ == '__main__':
a = netstat()
test = a.getData()
#a.testGetData(test)
|
cbrafter/TRB18_GPSVA | codes/sumoAPI/HybridVAControl_PROFILED.py | Python | mit | 14,996 | 0.005802 | #!/usr/bin/env python
"""
@file HybridVAControl.py
@author Craig Rafter
@date 19/08/2016
class for fixed time signal control
"""
import signalControl, readJunctionData, traci
from math import atan2, degrees
import numpy as np
from collections import defaultdict
class HybridVAControl(signalControl.signalContro... | ntSUMOtime() - self.lastCalled) < self.stageTi | me*1000:
# Before the period of the next stage
pass
else:
# Not active, not in offset, stage not finished
if len(self.junctionData.stages) != (self.lastStageIndex)+1:
# Loop from final stage to first stage
self.transitionObject.newT... |
Silvian/Reminders-App | reminders/urls.py | Python | gpl-3.0 | 1,236 | 0.000809 | """reminders URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... | ^admin/', admin.site.urls),
url(r'^login/', views.display_login, name='login'),
url(r'^logout/', views.logout_view, name='logout'),
url(r'^api/authenticate', views.authenticate_user, name='authenticate_user'),
url(r'^api/reminders', views.get_reminders, name='get_reminders'),
url(r'^api/add', views.... | ', views.remove_reminder, name='remove_reminder'),
url(r'^$', views.display_index, name='index'),
]
|
buchwj/xvector | client/xVClient/StartupScreen.py | Python | gpl-3.0 | 14,622 | 0.004514 | # xVector Engine Client
# Copyright (c) 2011 James Buchwald
# 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 pr... | '''This state shows nothing.'''
StartupState_Title = 1
'''This state shows the title menu.'''
StartupState_Metaserver = 2
'''This state allows a player to choose a server from the | list.'''
StartupState_PrivateServer = 3
'''This state allows a player to connect to a server by address.'''
StartupState_Settings = 4
'''This state allows a player to change the local settings.'''
StartupState_Updater = 5
'''This state retrieves updated files from the server.'''
##
... |
shackra/thomas-aquinas | summa/audio/system.py | Python | bsd-3-clause | 776 | 0 | # coding: utf-8
# This file is part of Thomas Aquinas.
#
# Thoma | s Aquinas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Thomas Aquinas is distributed in the hope that it will be useful,
# but W... | OR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Thomas Aquinas. If not, see <http://www.gnu.org/licenses/>.
#
# veni, Sancte Spiritus.
import ctypes
import logging
|
amolenaar/gaphor | packaging/make-script.py | Python | lgpl-2.1 | 2,017 | 0.000496 | import os
import subprocess
from pathlib import Path
import pyinstaller_versionfile
import tomli
packaging_path = Path(__file__).resolve().parent
def get_version() -> str:
project_dir = Path(__file__).resolve().parent.parent
f = project_dir / "pyproject.toml"
return str(tomli.loads(f.read_text())["tool"... | to
# end of the path, this removes it if it exists
file.write("import os\n")
file.write("if os.environ['PATH'][-1] == ';':\n")
| file.write(" os.environ['PATH'] = os.environ['PATH'][:-1]\n")
# Check for and remove two semicolons in path
file.write("os.environ['PATH'] = os.environ['PATH'].replace(';;', ';')\n")
plugins = toml["tool"]["poetry"]["plugins"]
for cat in plugins.values():
for entrypoi... |
jlopezbi/rhinoUnfolder | rhino_unwrapper/cutSelection/autoCuts.py | Python | gpl-3.0 | 3,550 | 0.006197 |
def auto_fill_cuts(myMesh,user_cuts,weight_function):
'''
fill in user_cut list (or if empty create new one) which
prefers edges with larger weight, given by the weight_function
NOTE: currently sets naked edges as cuts
'''
sorted_edges = get_edge_weights(myMesh,user_cuts,weight_function)
fo... | foldList.append(ed | geIdx)
if len(parentSets) == 0:
treeSets.append(setConnFaces)
elif len(parentSets) == 1:
treeSets[parentSets[0]].update(setConnFaces)
elif len(parentSets) == 2:
treeSets[parentSets[0]].update(treeSets[parentSets[... |
rcbops/horizon-buildpackage | horizon/middleware.py | Python | apache-2.0 | 2,838 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright | 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. Y... | red 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.
"""
Mi... |
PhilLidar-DAD/geonode | geonode/geoserver/helpers.py | Python | gpl-3.0 | 61,811 | 0.001052 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... | return None
def fixup_style(cat, resource, style):
logger.debug("Creating styles for layers associated with [%s]", resource)
layers = cat.get_layers(resource=resource)
logger.info("Found %d layers associated with [%s]", len(layers), resource)
for lyr in layers:
if lyr.default_style.name in... | lt style, generating a new one", lyr)
name = _style_name(resource)
if style is None:
sld = get_sld_for(lyr)
else:
sld = style.read()
logger.info("Creating style [%s]", name)
style = cat.create_style(name, sld)
lyr.de... |
silasb/flatcam | FlatCAMTool.py | Python | mit | 8,497 | 0.002942 | from PyQt4 import QtGui, QtCore
from shapely.geometry import Point
from shapely import affinity
from math import sqrt
import FlatCAMApp
from GU | IElements import *
from FlatCAMObj import FlatCAMGerber, FlatCAMExcellon
class FlatCAMTool(QtGui.QWidget):
toolName = "FlatCAM Generic Tool"
def __init__(self, app, parent=None):
"""
|
:param app: The application this tool will run in.
:type app: App
:param parent: Qt Parent
:return: FlatCAMTool
"""
QtGui.QWidget.__init__(self, parent)
# self.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
self.layout = QtGui.QVBox... |
blamed-cloud/PythonGames | fractoe.py | Python | mit | 10,693 | 0.041242 | #!/usr/bin/env python
#fractoe.py
from AISuite.game import Game as Game
import AISuite.player as player
from AISuite.alphabeta import UPPER_BOUND, LOWER_BOUND, shallowest_first
import AISuite.recorder as recorder
import AISuite.PythonLibraries.prgm_lib as prgm_lib
import fractoe_tictactoe as tictactoe
Tictactoe = ticta... | self.get_player_num()) + " (the computer) is thinking..."
| self.thinking = True
finished_playing = False
valid_moves = self.get_child_moves()
while not finished_playing:
if human:
if self.current_box != -1:
print "Current board is " + str(self.current_box)
self.grid[self.current_row][self.current_col].opg()
print "Player" + str(self.get_player_num()... |
barche/k3d | tests/bitmap/bitmap.modifier.BitmapAdd.py | Python | gpl-2.0 | 350 | 0.011429 | #python
import k3d
import testing
se | tup = testing.setup_bitmap_modifier_test("BitmapReader", "BitmapAdd")
setup.source.file = k3d.filesystem.generic_path(testing.source_path() + "/bitmaps/" + "test_ | rgb_8.png")
setup.modifier.value = 0.5
testing.require_similar_bitmap(setup.document, setup.modifier.get_property("output_bitmap"), "BitmapAdd", 0)
|
xiangke/pycopia | mibs/pycopia/mibs/HPR_IP_MIB_OID.py | Python | lgpl-2.1 | 1,140 | 0.015789 | # python
# This file is generated by a program (mib2py).
import HPR_IP_MIB
OIDMAP = {
'1.3.6.1.2.1.34.6.1.5': HPR_IP_MIB.hprIp,
'1.3.6.1.2.1.34.6.1.5.1.1.1': HPR_IP_MIB | .hprIpActiv | eLsLsName,
'1.3.6.1.2.1.34.6.1.5.1.1.2': HPR_IP_MIB.hprIpActiveLsAppnTrafficType,
'1.3.6.1.2.1.34.6.1.5.1.1.3': HPR_IP_MIB.hprIpActiveLsUdpPackets,
'1.3.6.1.2.1.34.6.1.5.2.1.1': HPR_IP_MIB.hprIpAppnPortName,
'1.3.6.1.2.1.34.6.1.5.2.1.2': HPR_IP_MIB.hprIpAppnPortAppnTrafficType,
'1.3.6.1.2.1.34.6.1.5.2.1.3': HPR_IP_MIB.... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_express_route_circuit_connections_operations.py | Python | mit | 19,491 | 0.005541 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | :type circuit_name: str
:par | am peering_name: The name of the peering.
:type peering_name: str
:param connection_name: The name of the express route circuit connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuatio... |
tbarrongh/cosc-learning-labs | src/learning_lab/05_acl_list.py | Python | apache-2.0 | 1,742 | 0.006889 | #!/usr/bin/env python2.7
# Copyright 2015 Cisco Systems, 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 applicabl... | ly the function to a network device.
Print the function output.
If no ACLs are found then retry with a different network device.
'''
from __future__ import print_function as _print_function
from pydoc import plain
from pydoc import render_doc as doc
from basics.context import sys_exit, EX_OK, EX_TEMPFAIL
from ... | st' to the specified device.
Return True if an ACL was found.
'''
print('acl_list(' + device_name, end=')\n')
result = acl_list(device_name)
print(result)
return bool(result)
def main():
''' Select a device and demonstrate.'''
print(plain(doc(acl_list)))
inventory = invento... |
tananaev/traccar | tools/test-trips.py | Python | apache-2.0 | 1,319 | 0.003033 | #!/usr/bin/python
import urllib
import httplib
import time
import datetime
id = '123456789012345'
server = 'localhost:5055'
points = [
('2017-01-01 00:00:00', 59.93211887, 30.33050537, 0.0),
('2017-01-01 00:05:00', 59.93266715, 30.33190012, 50.0),
('2017-01-01 00:10:00', 59.93329069, 30.33333778, 50.0),
... | , speed):
params = (('id', id), ('timestamp', int(time)), ('lat', lat), ('lon', lon), ('speed', speed))
conn.request('POST', '?' + urllib.urlencode(params))
conn.getresponse().read()
conn = httplib.HTTP | Connection(server)
for i in range(0, len(points)):
(moment, lat, lon, speed) = points[i]
send(conn, time.mktime(datetime.datetime.strptime(moment, "%Y-%m-%d %H:%M:%S").timetuple()), lat, lon, speed)
|
chrisvans/roastdoge | config/wsgi.py | Python | mit | 422 | 0 | """
WSGI config for roastdog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
from djan | go.core.wsgi import get_wsgi_application
from dj_static import Cling
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", " | settings.base")
application = Cling(get_wsgi_application())
|
wanghuafeng/spider_tools | decorator.py | Python | mit | 1,524 | 0.004076 | #!-*- coding:utf-8 -*-
import time
def retries(times=3, timeout=1):
"""对未捕获异常进行重试"""
def decorator(func):
def _wrapper(*args, **kw):
att, retry = 0, 0
while retry < times:
retry += 1
try:
return func(*args, **kw)
... | return _wrapper
return decorator
def use_logging(level):
"""带参数的装饰器"""
def decorator(func):
print func.__name__
def wrapper(*args, **kwargs):
if level == "warn":
print ("level:%s, %s is running" % (level, func.__name__))
elif level == "info":
... | unc.__name__))
return func(*args, **kwargs)
return wrapper
return decorator
if __name__ == "__main__":
@use_logging(level="warn")
def foo(name='foo'):
print("i am %s" % name)
foo() |
MyersGer/django-doubleoptin-contactform | doptincf/urls.py | Python | gpl-3.0 | 1,171 | 0.005978 | # This file is part of django-doubleoptin-contactform.
# django-doubleoptin-contactform 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 opt... | R PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License |
# along with Foobar. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
(r'^$', 'doptincf.views.contact'),
(r'^received/$', direct_to_template, {'template': 'contact/received.html'}),
... |
futurecolors/raven-harakiri | test_harakiri.py | Python | mit | 10,635 | 0.00489 | # coding: utf-8
example_traceback = """*** HARAKIRI ON WORKER 16 (pid: 2259, try: 1) ***
*** uWSGI Python tracebacker output ***
thread_id = Thread-2 filename = /home/project/.pythonz/pythons/CPython-2.6.8/lib/python2.6/threading.py lineno = 504 function = __bootstrap line = self.__bootstrap_inner()
thread_id = Thread... | ace.py lineno = 123 function = dynamic_wrapper line = return wr | apped(*args, **kwargs)
thread_id = MainThread filename = /home/project/envs/project_prod/lib/python2.6/site-packages/requests/sessions.py lineno = 335 function = request line = resp = self.send(prep, **send_kwargs)
thread_id = MainThread filename = /home/project/envs/project_prod/lib/python2.6/site-packages/requests/se... |
bcl/blivet | blivet/devices/md.py | Python | gpl-2.0 | 23,663 | 0.000887 | # devices/md.py
#
# Copyright (C) 2009-2014 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, or (at your option) any later version.
# This program is distributed in the... | sysfsPath=sysfsPath)
try:
self.level = level
except errors.DeviceError as e:
# Could not set the level, so set loose the parents that were
# added in superclass constructor.
for | dev in self.parents:
dev.removeChild()
raise e
self.uuid = uuid
self._totalDevices = util.numeric_type(totalDevices)
self.memberDevices = util.numeric_type(memberDevices)
self.chunkSize = mdraid.MD_CHUNK_SIZE
if not self.exists and not isinstance(me... |
pinax/pinax-forums | pinax/forums/tests/urls.py | Python | mit | 132 | 0 | from django.conf.urls import include, url
urlpatterns | = (
url(r"^", include("pinax.forums.urls", namespace="pinax_foru | ms")),
)
|
LeeKamentsky/CellProfiler | cellprofiler/gui/tests/__init__.py | Python | gpl-2.0 | 421 | 0 | """cellprofiler.gui.tests.__init__.py
CellPro | filer is distributed under the GNU General Public License.
See the accompanying file LICENSE for details.
Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2015 Broad Institute
All rights reserved.
Please see the AUTHORS file for credits.
Website: http://www.cellprofiler.org
"""
if __... | nose.main()
|
zencore-dobetter/zencore-redtask | src/scripts/zrts.py | Python | mit | 1,207 | 0.002486 | #!/usr/bin/env python
"""
Task message queue consumer server.
"""
import click
import logging
from zencore.conf import Settings
from zencore.redtask import server
from zencore.utils.debug import setup_simple_logger
CONFIG = Settings()
logger = logging.getLogger(__name__)
@click.group()
@click.option("-c", "--config"... | .command()
def start():
"""Start zencore-redtask consumer server.
"""
logger.debug("Server starting...")
server.start(CONFIG)
@zrts.command()
def stop():
"""Stop zencore-redtask consumer server.
"""
logger.debug("Server stopping...")
server.stop(CONFIG)
@zrts.command()
def reload():
... | load zencore-redtask consumer server.
"""
logger.debug("Server reloading...")
server.reload(CONFIG)
@zrts.command()
def status():
"""Get zencore-redtask consumer server's status.
"""
logger.debug("Server get status...")
server.status(CONFIG)
if __name__ == "__main__":
zrts()
|
after12am/expecto | machine_learning/kiki/kiki/settings.py | Python | mit | 2,210 | 0 | """
Django settings for kiki project.
For more information on this file, see
https://docs.dja | ngoproject.com/en/dev/topics/settings/
For the full list of settings and th | eir values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/ho... |
openstates/openstates | openstates/ne/bills.py | Python | gpl-3.0 | 10,305 | 0.001456 | import pytz
import urllib
from datetime import datetime
from pupa.scrape import Scraper, Bill, VoteEvent
from openstates.utils import LXMLMixin
TIMEZONE = pytz.timezone("US/Central")
VOTE_TYPE_MAP = {"yes": "yes", "no": "no"}
class NEBillScraper(Scraper, LXMLMixin):
def scrape(self, session=None):
if ... | on)
bill.add_version_link(
version_name, version_url, media_type="application/pdf"
)
soi | = self.get_nodes(bill_page, ".//a[contains(text(), 'Statement of Intent')]")
if soi:
bill.add_document_link(
"Statement of Intent", soi[0].get("href"), media_type="application/pdf"
)
comstmt = self.get_nodes(
bill_page, ".//a[contains(text(), 'Committe... |
citrix-openstack-build/ceilometer | tests/test_service.py | Python | apache-2.0 | 5,711 | 0.001576 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright © 2012 eNovance <licensing@enovance.com>
#
# Author: Julien Danjou <julien@danjou.info>
#
# 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 Lice... | def setUp(self):
super(ServiceRestartTest, self).setUp()
self.tempfile = self.temp_config_file_path()
self.pipeline_cfg_file = self.temp_config_file_path(name=
'pipeline.yaml')
shutil.c | opy(self.path_get('etc/ceilometer/pipeline.yaml'),
self.pipeline_cfg_file)
self.pipelinecfg_read_from_file()
policy_file = self.path_get('tests/policy.json')
with open(self.tempfile, 'w') as tmp:
tmp.write("[DEFAULT]\n")
tmp.write(
"rpc... |
mtb0/flightmodel | src/drivers/AnalysisDriver.py | Python | mit | 1,592 | 0.011935 | #!/usr/bin/env python
"""Plot scheduled flight times for AA flights between JFK and LAX.
For a given year and month, visualize dist vs sch time, run a regression,
and look at error. Filter based on whether the destination is in the Pacific,
and study the regression and error for each group."""
import | os
import sys
from analysis.filter import get_jetstream, get_pacific
from analysis.plot import plot_schtime, plot_reg | ression, plot_error, plot_regression_coef
from analysis.regression import regression
def main():
year = 2015
month = 1
os.system('mkdir -p graphs') #Create directory to place graphs, if it doesn't exist.
plot_schtime(12478, 12892, 'AA') #Plot sch flight time from JFK to LAX
plot_schtime(12892, 1... |
nomed/ebetl | ebetl/controllers/marketing.py | Python | artistic-2.0 | 12,560 | 0.017596 | # -*- coding: utf-8 -*-
"""Main Controller"""
import pylons
from tg import expose, flash, require, url, lurl, request, redirect, tmpl_context
from tg.i18n import ugettext as _, lazy_ugettext as l_
from tg import predicates
from ebetl import model
from ebetl.controllers.secure import SecureController
from ebetl.model im... | ))
from ebetl.lib.etl.b2b import B2bObj
b2bobj=B2bObj(config)
#b2bobj.write_out()
#if self.options.export:
print asyncjob_perform(testme, 2)
return redirect(url('/b2b/show/%s'%id))
@expose()
def book... | ks/id: Update an existing item"""
# Forms posted to this method should contain a hidden field:
# <input type="hidden" name="_method" value="PUT" />
# Or using helpers:
# h.form(url('stock', id=ID),
# method='put')
# url('stock', id=ID)
DBSession.qu... |
dawran6/zulip | zerver/webhooks/freshdesk/view.py | Python | apache-2.0 | 5,886 | 0.001019 | """Webhooks for external integrations."""
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from django.utils.translation import ugettext as _
from zerver.models import get_client, UserProfile
from zerver.lib.actions import check_send_message
from zerver.lib.response import json... |
# This is a property change event, like {status:{from:4,to:6}}. Pull out
# the property, from, and to states.
property, _, from_state, _, to_state | = data
return [property, property_name(property, int(from_state)),
property_name(property, int(to_state))]
def format_freshdesk_note_message(ticket, event_info):
# type: (TicketDict, List[str]) -> str
"""There are public (visible to customers) and private note types."""
note_type =... |
hacknashvillereview/review_application | review_app/review_app/urls.py | Python | mit | 1,606 | 0.004981 | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
# Un | comment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import api, foxycart
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^review/', TemplateView.as_view(template_name='base.html')),
url(r'^feedback/', Template... | iew_app/', include('review_app.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
#url(r'^api-auth/', include('r... |
rec/echomesh | code/python/experiments/ossaudiodev/GetFormats.py | Python | mit | 429 | 0.025641 | from __future__ import absolute_import, division, print_function, unicode_literals
import ossaudiode | v
def print_fmts(rw):
print(rw == 'r' and 'read' or 'write')
sound = ossaudiodev.open(rw)
fmts = sound.getfmts()
for name in dir(ossaudiodev):
if name.startswith('AFMT'):
attr | = getattr(ossaudiodev, name)
if attr & fmts:
print(name)
print()
sound.close()
print_fmts('w')
print_fmts('r')
|
surligas/gnuradio | gnuradio-runtime/python/gnuradio/gr/qa_random.py | Python | gpl-3.0 | 2,171 | 0.00783 | #!/usr/bin/env python
#
# Copyright 2006,2007,2010,2015 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 ... | GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with... | et,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest
import numpy as np
class test_random(gr_unittest.TestCase):
# NOTE: For tests on the output distribution of the random numbers, see gnuradio-runtime/apps/evaluation_random_numbers.py.
# Check for range [0,1) of uniform distributed rand... |
Southpaw-TACTIC/TACTIC | src/pyasm/prod/checkin/maya_checkin_test.py | Python | epl-1.0 | 1,267 | 0.008682 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | .command import Command
from pyasm.prod.biz import Asset
from pyams.prod.maya import *
from maya_checkin import * |
class MayaCheckinTest(unittest.TestCase):
def setUp(self):
batch = Batch()
def test_all(self):
# create a scene that will be checked in
asset_code = "prp101"
sid = "12345"
# create an asset
mel('sphere -n sphere1')
mel('circle -n circle1')
m... |
luiscberrocal/homeworkpal | homeworkpal_project/project_admin/migrations/0021_projectgoal_fiscal_year.py | Python | mit | 568 | 0.001761 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import mi | grations, models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('project_admin', '0020_project_fiscal_year'),
]
operations = [
migrations.AddField(
model_name='projectgoal',
name='fiscal_year',
field=models.CharF... | t='AF16'),
preserve_default=False,
),
]
|
gnott/bot-lax-adaptor | src/tests/test_validate.py | Python | gpl-3.0 | 1,558 | 0.001284 | from StringIO import StringIO
#import sys
import json
from os.path import join
from .base import BaseCase
import validate
import jsonschema
class TestArticleValidate(BaseCase):
def setUp(self):
self.doc_json = join(self.fixtures_dir, 'elife-09560-v1.xml.json')
def tearDown(self):
pass
def... | ticle = {'article': {'id': 12345, 'version': 2}}
expected = {
'article': {
'-patched': | True,
'id': 12345,
'version': 2,
'stage': 'published',
'versionDate': '2099-01-01T00:00:00Z',
'statusDate': '2099-01-01T00:00:00Z',
}}
validate.add_placeholders_for_validation(article)
self.assertEqual(article, ... |
luiscape/hdxscraper-violation-documentation-center-syria | tests/unit/test_setup.py | Python | mit | 1,648 | 0.018204 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# system
import os
import sys
dir = os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0]
sys.path.append(os.path.join(dir, 'scripts'))
# testing
import mock
import unittest
from mock import patch
# program
import setup | .load as Config
import setup.database as DB
#
# Global variables.
#
TEST_DATA = 'test_flood_portal_output.json'
class CheckConfigurationStructure(unittest.TestCase):
'''Unit tests for the configurat | ion files.'''
def test_that_load_config_fails_gracefully(self):
assert Config.LoadConfig('xxx.json') == False
## Object type tests.
def test_config_is_list(self):
d = Config.LoadConfig(os.path.join(dir, 'config', 'dev.json'))
assert type(d) is dict
def test_config_returns_a_table_list(self):
... |
johnrbnsn/Adafruit_Python_MAX31856 | Adafruit_MAX31856/test_MAX31856.py | Python | mit | 8,880 | 0.00732 | """
Copyright (c) 2019 John Robinson
Author: John Robinson
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 the rights
to use, copy, modify, merge,... | self.assertEqual(decimal_cj_temp, 28.390625)
# Check a couple values from the datasheet
msb = 0b01111111
lsb = 0b11111100
dec | imal_cj_temp = MAX31856._cj_temp_from_bytes(msb, lsb) # pylint: disable-msg=protected-access
self.assertEqual(decimal_cj_temp, 127.984375)
msb = 0b00011001
lsb = 0b00000000
decimal_cj_temp = MAX31856._cj_temp_from_bytes(msb, lsb) # pylint: disable-msg=protected-access |
simar7/build-mozharness | mozharness/mozilla/testing/unittest.py | Python | mpl-2.0 | 11,491 | 0.001653 | #!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# 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/.
# ***** END LICENSE BLOCK *****
import os
import re
from mozhar... | asize_fail_text = '<em class="testfail">%s</em>'
if pass_count < 0 or fail_count < 0 or \
(known_fail_count is not None and known_fail_count < 0):
summary = emphasi | ze_fail_text % 'T-FAIL'
elif pass_count == 0 and fail_count == 0 and \
(known_fail_count == 0 or known_fail_count is None):
summary = emphasize_fail_text % 'T-FAIL'
else:
str_fail_count = str(fail_count)
if fail_count > 0:
str_fail_count = emphasize_fail_text % st... |
ronaldahmed/robot-navigation | neural-navigation-with-lstm/MARCO/nltk_contrib/unimelb/tacohn/classifier/__init__.py | Python | mit | 21,922 | 0.003421 | ## Automatically adapted for numpy.oldnumeric May 17, 2011 by -c
# Natural Language Toolkit: Classifiers
#
# Copyright (C) 2001 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: __init__.py,v 1.2 2003/10/27... | ssifiers are required to implement two methods:
- C{classify}: determines which label is most appropriate for a
given text token, and returns a labeled text token with that
label.
- C{labels}: returns the list of category labels that | are used
by this classifier.
Classifiers are also encouranged to implement the following
methods:
- C{distribution}: return a probability distribution that
specifies M{P(label|text)} for a given text token.
- C{prob}: returns M{P(label|text)} for a given labeled text
token.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.