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 |
|---|---|---|---|---|---|---|---|---|
AlexRiina/django-s3direct | example/example/settings.py | Python | mit | 4,212 | 0.000237 | """
Django settings for hello project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# B... | ngs/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ ... | static/'
# If AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not defined,
# django-s3direct will attempt to use the EC2 instance profile instead.
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '')
AWS_STORAGE_BUCKET_NAME = os.environ.get('A... |
lcy-seso/models | fluid/image_classification/caffe2fluid/kaffe/custom_layers/__init__.py | Python | apache-2.0 | 2,996 | 0.001335 | """
"""
from .register import get_registered_layers
#custom layer import begins
import axpy
import flatten
import argmax
import reshape
import roipooling
import priorbox
import permute
import detection_out
import normalize
import select
import crop
import reduction
#custom layer import ends
custom_layers = get_regi... | kwargs[arg_name] = params[arg_name]
if node is not None and len(node.metadata):
kwargs.update(node.metadata)
return arg_list, kwargs
def has_layer(kind):
""" test whether this layer exists in custom layer
"""
| return kind in custom_layers
def compute_output_shape(kind, node):
assert kind in custom_layers, "layer[%s] not exist in custom layers" % (
kind)
shape_func = custom_layers[kind]['shape']
parents = node.parents
inputs = [list(p.output_shape) for p in parents]
arg_names, kwargs = set_arg... |
anarang/robottelo | tests/foreman/ui/test_location.py | Python | gpl-3.0 | 34,753 | 0 | # -*- encoding: utf-8 -*-
"""Test class for Locations UI"""
from fauxfactory import gen_ipaddr, gen_stri | ng
from nailgun import entities
from robottelo.config import settings
from robottelo.datafactory import generate_strings_list, invalid_values_list
from robottelo.decorators import run_only_on, tier1, tier2
from robottelo.constants import (
ANY_CONTEXT,
INSTALL_MEDIUM_URL,
LIBVIRT_RESOURCE_URL,
OS_TEMPLA... | om robottelo.ui.locators import common_locators, locators, tab_locators
from robottelo.ui.session import Session
def valid_org_loc_data():
"""Returns a list of valid org/location data"""
return [
{'org_name': gen_string('alpha', 10),
'loc_name': gen_string('alpha', 10)},
{'org_name': ... |
Linkid/numpy | numpy/core/tests/test_regression.py | Python | bsd-3-clause | 78,626 | 0.002073 | from __future__ import division, absolute_import, print_function
import copy
import pickle
import sys
import platform
import gc
import copy
import warnings
import tempfile
from os import path
from io import BytesIO
from itertools import chain
import numpy as np
from numpy.testing import (
run_module_suite, Te... | =[('x', np.int64)])
def test_pickle_transposed(self,level=rlevel):
"""Ticket #16"""
a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]]))
f = BytesIO()
pickle.dump(a, f)
f.s | eek(0)
b = pickle.load(f)
f.close()
assert_array_equal(a, b)
def test_typeNA(self,level=rlevel):
"""Ticket #31"""
assert_equal(np.typeNA[np.int64], 'Int64')
assert_equal(np.typeNA[np.uint64], 'UInt64')
def test_dtype_names(self,level=rlevel):
"""Ticket #... |
EduJGURJC/elastest-service-manager | src/esm/models/binding_request.py | Python | apache-2.0 | 6,152 | 0.004714 | # coding: utf-8
from __future__ import absolute_import
#
from esm.models.bind_resource import BindResource
from .base_model_ import Model
from ..util import deserialize_model
class BindingRequest(Model):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class ... | ce
@classmethod
def from_dict(cls, dikt) -> 'BindingRequest':
"""
Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The BindingRequest of this BindingRequest.
:rtype: BindingRequest
"""
return deserialize_model(dikt, cls)
... | ociated with the binding to be created. If present, MUST be a non-empty string.
:return: The app_guid of this BindingRequest.
:rtype: str
"""
return self._app_guid
@app_guid.setter
def app_guid(self, app_guid: str):
"""
Sets the app_guid of this BindingRequest.... |
carlvlewis/detective.io | app/detective/management/commands/parseowl.py | Python | lgpl-3.0 | 16,471 | 0.006982 | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from lxml import etree
from app.detective.utils import to_class_name, to_camelcase, to_underscores
import re
# Defines the owl and rdf namespaces
namespaces = {
'owl': 'http://www.w3.org/2002/07/owl#',
'rdf': 'http://www.... | re is a property defined in the subclass
elif restriction.find("owl:onDataRange", namespaces) is not None or restriction.find("owl:someValuesFrom", namespaces) is not None:
| propertyTypeElement = restriction.find("owl:onProperty", namespaces)
propertyTypeURI = propertyTypeElement.attrib["{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource"]
propertyType = propertyTypeURI.split("#")[1]
... |
les69/calvin-base | calvin/calvinsys/events/timer.py | Python | apache-2.0 | 2,309 | 0.002599 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson 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 ... | actor_id))
self._triggered = True
if self.repeats:
self.reset()
self.trigger_loop(actor_ids=[self._actor_id])
class TimerHandler(object):
def __init__(self, node, actor):
super(TimerHandler, self).__init__()
self._actor = actor
self.node = node
def ... | peat(self, delay):
return TimerEvent(self._actor.id, delay, self.node.sched.trigger_loop, repeats=True)
def register(node, actor, events=None):
"""
Registers is called when the Event-system object is created.
Place an object in the event object - in this case the
nodes only timer ob... |
Mr-Robots/Gesture-controlled-surveillance-vehicle | Ti_Monitor/Gesture_serial.py | Python | gpl-2.0 | 251 | 0.015936 | import serial
ser = serial.Serial('/dev/ttyUSB2',38400)
while True:
try:
x = ser.read()
f=open('gesture_command.txt','w')
f.write(x)
f.close()
except:
print "Gesture serial : port error!"
brea | k
| |
praekelt/molo-iogt | iogt/migrations/0003_convert_recomended_articles.py | Python | bsd-2-clause | 2,316 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from molo.core.models import ArticlePage, ArticlePageRecommendedSections
from wagtail.wagtailcore.blocks import StreamValue
def create_recomended_articles(main_article, article_list):
'''
Creates recommended arti... | PageRecommendedSections.objects.filter(page=main_article).delete()
for hyperlinked_article in article_list:
ArticlePageRecommendedSections(
page=main_article,
recommended_article=hyperlinked_article).save()
# re-create existing recommended articles
for article in existing_r... | cle=article).save()
def convert_articles(apps, schema_editor):
'''
Derived from https://github.com/wagtail/wagtail/issues/2110
'''
articles = ArticlePage.objects.all().exact_type(ArticlePage)
for article in articles:
stream_data = []
linked_articles = []
for block in artic... |
eayunstack/neutron | neutron/pecan_wsgi/hooks/policy_enforcement.py | Python | apache-2.0 | 11,798 | 0.000085 | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | cable 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 Lice | nse.
import copy
from oslo_log import log as logging
from oslo_policy import policy as oslo_policy
from oslo_utils import excutils
from pecan import hooks
import webob
from neutron._i18n import _
from neutron.common import constants as const
from neutron.extensions import quotasv2
from neutron import manager
from ne... |
jcurbelo/networkx | networkx/algorithms/traversal/breadth_first_search.py | Python | bsd-3-clause | 3,994 | 0.002754 | """
====================
Breadth-first search
====================
Basic algorithms for breadth-first searching the nodes of a graph.
"""
import networkx as nx
from collections import defaultdict, deque
__author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>'])
__all__ = ['bfs_edges', 'bfs_tree', 'bfs_prede... | f bfs_tree(G, source, reverse=False):
"""Return an oriented tree constructed from of a breadth-first-search
starting at source.
Parameters
----------
G : NetworkX graph
source : node
Specify starting node for breadth-first search and return edges in
the component reachable from s... | An oriented tree
Examples
--------
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(list(nx.bfs_edges(G,0)))
[(0, 1), (1, 2)]
Notes
-----
Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
by D. Eppstein, July 2004.
"""
T = nx.DiGraph()
T.add_node(source)
... |
tredly/tredly | tests/testobjects/firewallchecks.py | Python | mit | 2,018 | 0.007433 | # Performs network checks
from subprocess import Popen, PIPE
from includes.output import *
class FirewallChecks:
# C | onstructor
def __init__(self, uuid = None):
# if uuid == None then check the host
self.uuid = uuid
def checkIpfwRule(self, permission, fromIP, toIP, toPort, direction):
cmd = ['ipfw', 'list']
# add the jexec command if we're dealing with a container
if (self.uui... | pen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdOut, stdErr = process.communicate()
stdOutString = stdOut.decode('utf-8')
stdErrString = stdErr.decode('utf-8')
for line in stdOutString.splitlines():
words = line.split()
# chcek against thi... |
ThiefMaster/sqlalchemy | lib/sqlalchemy/orm/attributes.py | Python | mit | 57,173 | 0.000122 | # orm/attributes.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Defines instrumentation for class attributes and their interaction
with instanc... | .comparator.of_type(cls),
self._parentent | ity,
of_type=cls)
def label(self, name):
return self._query_clause_element().label(name)
def operate(self, op, *other, **kwargs):
return op(self.comparator, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs):
return op(other, self.comparator, **kwargs)
... |
olkku/tf-info | manager/tests.py | Python | bsd-3-clause | 3,567 | 0.001402 | from django.test import TestCase
from manager.models import Page
from datetime import datetime, timedelta
from django.utils import timezone
class PageTestCase(TestCase):
def setUp(self):
now = timezone.now()
Page.objects.create(url="testurl", description="test description")
def test_regular_page_... | time()
self.assertFalse(page.is_active(now))
# Set time to be past start time
now = now.replace(hour=14)
self.assertTrue(page.is_active(now))
# Set end time in the future, still active
page.active_time_end = now.replace(hour=15).time()
self.assertTrue(page.is_ac... | eplace(hour=16)
self.assertFalse(page.is_active(now))
# Set start time in the future but bigger than end-time
page.active_time_start = now.replace(hour=17).time()
self.assertFalse(page.is_active(now))
# Time bigger than start time in the evening
now = now.replace(hour=1... |
Tinkerforge/brickv | src/brickv/plugin_system/plugins/red/red_tab_settings_brickd.py | Python | gpl-2.0 | 14,059 | 0.003272 | # -*- coding: utf-8 -*-
"""
RED Plugin
Copyright (C) 2014 Ishraq Ibne Ashraf <ishraq@tinkerforge.com>
Copyright (C) 2014 Olaf Lüke <olaf@tinkerforge.com>
Copyright (C) 2014-2015 Matthias Bolte <matthias@tinkerforge.com>
red_tab_settings_brickd.py: RED settings brickd tab implementation
This program is free software; ... |
def tab_on_focus(self):
self.brickd_conf_rfile = REDFile(self.session)
self.slot_brickd_refresh_clicked()
def tab_off_focus(self):
pass
def tab_destroy(self):
pass
def brickd_button_refr | esh_enabled(self, state):
self.pbutton_brickd_refresh.setEnabled(state)
if state:
self.pbutton_brickd_refresh.setText('Refresh')
else:
self.pbutton_brickd_refresh.setText('Refreshing...')
def brickd_button_save_enabled(self, state):
self.pbutton_brickd_save.... |
mayankjohri/LetsExplorePython | Section 2 - Advance Python/Chapter S2.04 - Database/code/sqlalchemy/runbook.py | Python | gpl-3.0 | 2,255 | 0.01155 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 17 05:52:09 2016
@author: hclqaVirtualBox1
"""
from object_test import session
import random
import string
import model
test_page = model.Page()
N = 5
test_page.title = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
test... | ssion API, ensuring that the pageid field contained the value 1
# so that the comment was associated with the correct page via a foreign key.
#
# The Object-Relational API provides a much better approach:
#"""
#
#comment1 = model.Comment()
#comment1.name= u'James'
#comment1.email = u'james@example.com'
#com... | t1)
#page.comments.append(comment2)
#session.commit()
|
shimniok/rockblock | mtrecv.py | Python | mit | 576 | 0.006944 | #!/usr/bin/env python
##################################################################################################
## mtrecv.py
##
## Receive message via RockBLOCK over serial
################# | #################################################################################
import sys
import os
from rbControl import RockBlockCon | trol
if __name__ == '__main__':
if len(sys.argv) == 1:
# TODO: configurable serial device
RockBlockControl("/dev/ttyUSB0").mt_recv()
else:
print "usage: %s" % os.path.basename(sys.argv[0])
exit(1)
|
cjaymes/pyscap | src/scap/model/xal_2_0/EndorsementLineCodeType.py | Python | gpl-3.0 | 987 | 0.002026 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | scap.Model import Model
import logging
logger = logging.getLogger(__name__)
class EndorsementLineCodeType(Model):
MODEL_MAP = {
| 'tag_name': 'EndorsementLineCode',
'attributes': {
'Type': {},
'Code': {}, # from grPostal
'*': {},
}
}
|
jtk1rk/xsubedit | view.py | Python | gpl-3.0 | 14,528 | 0.00351 | import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
gi.require_version('GObject', '2.0')
from gi.repository import Gtk, Gdk, GObject
from gcustom.audioWidget import cAudioWidget
from gcustom.progressBar import cProgressBar
class TimedStatusBar(Gtk.Statusbar):
def __init__(self, timeout):
... | tk.SeparatorToolItem()
self.widgets['undoTB'] = Gtk.ToolButton()
self | .widgets['undoTB'].set_tooltip_text('Undo')
self.widgets['undoTB'].set_stock_id(Gtk.STOCK_UNDO)
self.widgets['redoTB'] = Gtk.ToolButton()
self.widgets['redoTB'].set_tooltip_text('Redo')
self.widgets['redoTB'].set_stock_id(Gtk.STOCK_REDO)
self.widgets['preferencesTB'] = Gtk.ToolBu... |
thinkAmi-sandbox/Django_separate_model_file-sample | myproject/settings.py | Python | unlicense | 3,216 | 0.001244 | """
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
... | definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.myapp',
'apps.outsideapp',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.Secu... | leware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT... |
emehrkay/Gizmo | gizmo/test/integration/tinkerpop.py | Python | mit | 1,104 | 0.001812 | import asyncio
import unittest
import random
from gremlinpy import Gremlin
from . import ConnectionTestCases, EntityTestCases, Mapper | TestCases
from gizmo import Mapper, Request, Collection, Vertex, Edge
from gizmo.mapper import EntityMapper
class BaseTests(unittest.TestCase):
def setUp(self):
self.request = Request('localhost', port=8182)
self.gremlin = Gremlin('gizmo_testing')
self.mapper = Mapper(self.request, self.g... | _event_loop()
super(BaseTests, self).setUp()
def tearDown(self):
super(BaseTests, self).tearDown()
async def purge(self):
script = "%s.V().map{it.get().remove()}" % self.gremlin.gv
res = await self.mapper.query(script=script)
return res
class ConnectionTests(BaseTes... |
vivescere/yajuu | yajuu/extractors/season_extractor.py | Python | gpl-3.0 | 1,048 | 0.000954 | from yajuu.extractors.extractor import Extractor
from yajuu.media.sources.source_list import SourceList
class SeasonExtractor(Extractor):
|
def __init__(self, media, season, range_):
super().__init__(media)
self.seasons = {}
self.season = season
self.start, self.end = range_
# Overwrite
self.sources = {}
def _should_process(self, episode_identifier):
try:
episode_number = int(ep... | _source(self, identifier, source):
if identifier not in self.sources:
self.sources[identifier] = SourceList()
self.sources[identifier].add_source(source)
return True
def _add_sources(self, identifier, sources):
returned = []
if sources is None:
ret... |
UNINETT/nav | tests/unittests/smsd/dispatcher_test.py | Python | gpl-2.0 | 2,660 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 as published by the Free
# Software Foundation.
#
# This program is... | eType('fakedispatcher')
fakemodule.FakeDispatcher = FakeDispatcher
return fakemodule
class FakeDispatcher(object):
def __init__(self, *args, **kwargs):
self.lastfailed = None
pass
def sendsms(self, phone, msgs):
print("got phone %r and msgs %r" % (phone, msgs))
| if phone == 'failure':
raise dispatcher.DispatcherError('FakeDispatcher failed')
elif phone == 'unhandled':
raise Exception('This exception should be unknown')
return (None, 1, 0, 1, 1)
|
scikit-rf/scikit-rf | skrf/media/tests/test_media.py | Python | bsd-3-clause | 11,278 | 0.011601 | # -*- coding: utf-8 -*-
import unittest
import os
import numpy as npy
from skrf.media import DefinedGammaZ0, Media
from skrf.network import Network
from skrf.frequency import Frequency
import skrf
class DefinedGammaZ0TestCase(unittest.TestCase):
def setUp(self):
self.files_dir = os.path.join(
... | the form:
[ 1 0 ]
[ Y 1 ]
"""
R = 1.0 # Ohm
ntw = self.dummy_media.shunt(self.dummy_media.resistor(R)**self.dummy_media.sho | rt())
npy.testing.assert_array_almost_equal(ntw.a[:,0,0], 1.0)
npy.testing.assert_array_almost_equal(ntw.a[:,0,1], 0.0)
npy.testing.assert_array_almost_equal(ntw.a[:,1,0], 1.0/R)
npy.testing.assert_array_almost_equal(ntw.a[:,1,1], 1.0)
def test_abcd_series_shunt_elements(se |
google/grr | grr/server/grr_response_server/gui/api_call_router_test.py | Python | apache-2.0 | 4,408 | 0.006352 | #!/usr/bin/env python
"""Tests for API call routers."""
from absl import app
from grr_response_core.lib.rdfvalues import structs as rdf_structs
from grr_response_core.lib.util import compatibility
from grr_response_proto import tests_pb2
from grr_response_server import access_control
from grr_response_server.gui impo... | def CreateFlow(self, args, context=None):
pass
class SingleMethodDummyApiCallRouterChild(SingleMethodDummyApiCallRouter):
pass
class EmptyRouter(api_call_router.ApiCallRouterStub):
pass
class ApiCallRouterTest(test_lib.GRRBaseTest):
"""Tests for ApiCallRouter."""
def testAllAnnotatedMethodsAreNotIm... | with self.assertRaises(NotImplementedError):
getattr(router, name)(None, context=None)
def testGetAnnotatedMethodsReturnsNonEmptyDict(self):
methods = api_call_router.ApiCallRouterStub.GetAnnotatedMethods()
self.assertTrue(methods)
def testGetAnnotatedMethodsReturnsMethodsFromAllClassesInMroChai... |
tomprince/txgithub | txgithub/scripts/tests/test_gist.py | Python | mit | 8,506 | 0 | """
Tests for L{txgithub.scripts.gist}
"""
import io
from collections import namedtuple
from twisted.python import usage
from twisted.trial.unittest import SynchronousTestCase
from twisted.internet.defer import Deferred, succeed
from txgithub.scripts import gist
from . _options import (_OptionsTestCaseMixin,
... | nt()
self.gists = FakeGistsEndpoint(self.gists_recorder)
self.api_recorder = RecordsFakeGithubAPI()
s | elf.fake_api = FakeGithubAPI(self.api_recorder, self.gists)
self.content = u"content"
self.stdin = io.StringIO(self.content)
self.open_calls = []
self.open_returns = io.StringIO(self.content)
self.print_calls = []
self.patch(gist, "getToken", self.fake_getToken)
... |
heidi666/WorldsAtWar | wawmembers/apps.py | Python | mit | 136 | 0 | from __future__ import unicode_literals
from django.apps imp | ort AppConfig
class WawmembersConfig(AppConfig):
name = 'wawmembers | '
|
ajdawson/eofs | doc/conf.py | Python | gpl-3.0 | 9,234 | 0.00574 | # -*- coding: utf-8 -*-
#
# eofs documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 5 15:47:55 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | _directive',]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
| # The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'eofs'
copyright = '2013-{} Andrew Dawson'.format(time.localtime().tm_year)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places... |
bks/veusz | veusz/utils/formatting.py | Python | gpl-2.0 | 7,914 | 0.002654 | # Copyright (C) 2010 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... | ates
_formaterror = 'FormatError'
# a format statement in a string
_format_re = re.compile(r'%([-#0-9 +.hlL]*?)([diouxXeEfFgGcrs%])')
def localeFormat(totfmt, args, locale=None):
"""Format using fmt statement fmt, qt QLocale object locale and
arguments to formatting args.
* arguments are not supported i... | alues for statement
"""
# substitute all format statements with string format statements
newfmt = _format_re.sub("%s", totfmt)
# do formatting separately for all statements
strings = []
i = 0
for f in _format_re.finditer(totfmt):
code = f.group(2)
if code == '%':
... |
googleapis/python-area120-tables | samples/generated_samples/area120tables_v1alpha1_generated_tables_service_list_tables_async.py | Python | apache-2.0 | 1,496 | 0.000668 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license | s/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under t... | ifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-area120-tables
# [START area120tables_v1alpha1_generated_TablesService_ListTables_async]
from google.area120 import tables_v1alpha1
async def sample_list_tables():
... |
c2nes/javalang | javalang/test/test_java_8_syntax.py | Python | mit | 8,702 | 0.000115 | import unittest
from pkg_resources import resource_string
from .. import parse, parser, tree
def setup_java_class(content_to_add):
""" returns an example java class with the
given content_to_add contained within a method.
"""
template = """
public class Lambda {
public static void main(Strin... | up_java_class("x -> x.length();"),
setup_jav | a_class("y -> { y.boom(); };"),
]
for test_class in test_classes:
clazz = parse.parse(test_class)
self.assert_contains_lambda_expression_in_m(clazz)
def test_parameter_with_type_expression_body(self):
""" tests support for lambda with parameters with formal types. ""... |
ms83/pydevp2p | devp2p/tests/test_kademlia_protocol.py | Python | mit | 13,421 | 0.000522 | # -*- coding: utf-8 -*-
import random
import time
from devp2p.utils import int_to_big_endian
from devp2p import kademlia
import pytest
import gevent
random.seed(42)
class WireMock(kademlia.WireInterface):
messages = [] # global messages
def __init__(self, sender):
assert isinstance(sender, kademli... | o add won't split
wire = proto.wire
# get a full bucket
full_buckets = [b for b in proto.routing.buckets if b.is_full and not b.should_split]
assert full_buckets
bucket = full_buckets[0]
assert not bucket.should_split
assert len(bucket) == kademlia.k_bucket_size
bucket_nodes = bucket.no... | to insert
node = random_node()
node.id = bucket.start + 1 # should not split
assert bucket.in_range(node)
assert bucket == proto.routing.bucket_by_node(node)
# insert node
proto.update(node)
# expect bucket was not split
assert len(bucket) == kademlia.k_bucket_size
# expect bucke... |
nanfeng1101/Seq2Seq | pytorch_models/models/beam_search.py | Python | mit | 4,237 | 0.001652 | # -*- coding:utf-8 -*-
__author__ = 'chenjun'
import torch
from torch.autograd import Variable
from utils.util import *
"""Beam search module.
Beam search takes the top K results from the model, predicts the K results for
each of the previous K result, getting K*K results. Pick the top K results from
K*K results, an... | :return:
"""
# This length normalization is only effective for the final results.
if normalize:
return sorted(hypothesis, key=lambda h: h.log_prob/len(h.tokens), reverse=True)
else:
return sorted(hypothesis, key=lambda h: h.log_prob, reverse=True)
def varia... | urn:
"""
return Variable(torch.LongTensor([[token]]))
def beam_search(self, inputs):
"""
beam search to generate sequence.
:param inputs: list of decoder outputs, (decoder_out, decode_state)
:return:
"""
all_hypothesis = []
for i, (input, stat... |
aehlke/epywing | src/epywing/utils/test.py | Python | gpl-3.0 | 527 | 0.009747 | # -*- coding: utf-8 -*-
import subprocess
import os
cmd=['/Users/jehlke/workspace/epywing/src/epywing/utils/mecab/bin/mecab',
'-Owakati', '--dicdir=mecab/dic/ | ipadic']
#cmd = ['mecab', '-Owakati', '--dicdir=../dic/ipadic']
a = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
a.stdin.write(u'何~これですか what is that HUH OK I SEE ?\n\n'.encode('utf8'))
a.stdin.flush()
b = | unicode(a.stdout.readline().decode('utf8'))
print 'test'
print b.strip()#.split()
print 'test'
|
RaD/django-south | south/migration/migrators.py | Python | apache-2.0 | 12,278 | 0.001547 | from __future__ import print_function
from copy import copy, deepcopy
import datetime
import inspect
import sys
import traceback
from django.core.management import call_command
from django.core.management.commands import loaddata
from django.db import models
import south.db
from south import exceptions
from south.db... | dry_run = DryRunMigrator(migrator=self, ignore_fail=False)
dry_run.run_migration(migration, database)
return self.run_migration(migration, database)
def send_ran_migration(self, migration, database):
ran_migration.send(None,
app=migration.app_label(),
... | method=self.__class__.__name__.lower(),
verbosity=self.verbosity,
interactive=self.interactive,
db=database)
def migrate(self, migration, database):
"""
Runs the specified migration forwards/backwards, in order... |
vandys/nowplaying | reports/disptime.py | Python | unlicense | 107 | 0.009346 | #!/usr/b | in/python
import sys, time
for ts | in sys.argv[1:]:
print ts, time.ctime(float(ts))
sys.exit(0)
|
MelissaChan/Crawler_Facebook | Crawler/facebook_mysql.py | Python | mit | 1,040 | 0.021236 | # __author__ = | MelissaChan
# -*- coding: utf-8 | -*-
# 16-4-16 下午10:53
import MySQLdb
def connect(id,name,gender,region,status,date,inter):
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd=' ',port=3306)
cur = conn.cursor()
# cur.execute('create database if not exists PythonDB')
conn.select_db('Facebook')
... |
pyrocko/pyrocko | maintenance/docstring_cop.py | Python | gpl-3.0 | 543 | 0.01105 | import sys, re
for fn in sys.argv[1:]:
with open(fn, 'r') as f:
s = f | .read()
xx = re.findall(r'([^\n]+)\s+\'\'\'(.*?)\'\'\'', s, re.M|re.S)
for (obj, doc) in xx:
s = re.findall('[^:`]\B(([`*])[a-zA-Z_][a-zA-Z0-9_]*\\2)\B', doc)
if s:
print '-'*50
print fn, obj
print '.'*50
pr | int doc
print '.'*50
print [ss[0] for ss in s]
# for vim:
# :s/\([^`:]\)\([`*]\)\([a-zA-Z0-9_]\+\)\2/\1``\3``/
|
apanda/modeling | tests/examples/AclContentCacheTest.py | Python | bsd-3-clause | 1,990 | 0.011055 | import components
def AclContentCacheTest ():
"""ACL content cache test"""
ctx = components.Context (['a', 'b', 'c', 'd', 'cc', 'f'],\
['ip_a', 'ip_b', 'ip_c', 'ip_d', 'ip_cc', 'ip_f | '])
net = components.Network (ctx)
a = components.EndHost(ctx.a, net, ctx)
b = components.EndHost(ctx.b, net, ctx)
c = components.EndHost(ctx.c, net, ctx)
d = components.EndHost(c | tx.d, net, ctx)
cc = components.AclContentCache(ctx.cc, net, ctx)
f = components.AclFirewall(ctx.f, net, ctx)
net.setAddressMappings([(a, ctx.ip_a), \
(b, ctx.ip_b), \
(c, ctx.ip_c), \
(d, ctx.ip_d), \
... |
ltowarek/budget-supervisor | third_party/saltedge/test/test_rates_response.py | Python | mit | 900 | 0 | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_cl... | lient.models.rates_response import RatesResponse # noqa: E501
from swagger_client.rest import ApiException
class TestRatesResponse(unittest.TestCase):
"""RatesResponse unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testRatesResponse(self):
"""Test Rat... | oqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
dudakp/rasPi_systemInfo | lib_si1145/lib_si1145.py | Python | mit | 2,472 | 0.045307 | #!/usr/bi | n/python
from ops_i2cbase import I2CBase
# ===========================================================================
# SI1145 Class
#
# Ported from github.com/adafruit/Adafruit_SI1145_Library/
# ===========================================================================
class SI1145:
i2c = None
# SI1145 Addre... | 145_PARAM_I2CADDR = 0x00
SI1145_PARAM_CHLIST = 0x01
SI1145_PARAM_CHLIST_ENUV = 0x80
SI1145_PARAM_CHLIST_ENAUX = 0x40
SI1145_PARAM_CHLIST_ENALSIR = 0x20
SI1145_PARAM_CHLIST_ENALSVIS = 0x10
SI1145_PARAM_CHLIST_ENPS1 = 0x01
SI1145_PARAM_CHLIST_ENPS2 = 0x02
SI1145_PARAM_CHLIST_ENPS3 = 0x04
# Registers
SI1145_REG... |
asterick/pytari | Palettes.py | Python | gpl-2.0 | 5,212 | 0.13891 | #
# This is the container for the palettes. To change them
# simply edit this.
#
from numpy import *
NTSC = array([
[0x00,0x00,0x00],[0x40,0x40,0x40],[0x6C,0x6C,0x6C],[0x90,0x90,0x90],
[0xB0,0xB0,0xB0],[0xC8,0xC8,0xC8],[0xDC,0xDC,0xDC],[0xEC,0xEC,0xEC],
[0x44,0x44,0x00],[0x64,0x64,0x10],[0x... | ,0xD0,0x50],[0xE8,0xE8,0x5C],[0xFC,0xFC,0x68],
[0x70,0x28,0x00],[0x84,0x44,0x14],[0x98,0x5C,0x28],[0xAC,0x78,0x3C],
[0xBC,0x8C,0x4C],[0xCC,0xA0,0x5C],[0xDC,0xB4,0x68],[0xEC,0xC8,0x78],
[0x84,0x18,0x00],[0x98,0x34,0x18],[0xAC,0x50,0x30],[0xC0,0x68,0x48],
[0xD0,0x80,0x5C],[0xE0,0x94,0x70],[0xEC,0xA8,0... | 3C],[0xC0,0x58,0x58],
[0xD0,0x70,0x70],[0xE0,0x88,0x88],[0xEC,0xA0,0xA0],[0xFC,0xB4,0xB4],
[0x78,0x00,0x5C],[0x8C,0x20,0x74],[0xA0,0x3C,0x88],[0xB0,0x58,0x9C],
[0xC0,0x70,0xB0],[0xD0,0x84,0xC0],[0xDC,0x9C,0xD0],[0xEC,0xB0,0xE0],
[0x48,0x00,0x78],[0x60,0x20,0x90],[0x78,0x3C,0xA4],[0x8C,0x58,0xB8],
... |
morissette/devopsdays-hackathon-2016 | venv/bin/rst2pseudoxml.py | Python | gpl-3.0 | 635 | 0.001575 | #!/home/mharris/Projects/DevOpsDays/venv/bin/python2
# $Id: rst2pseudoxml.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Go | odger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing pseudo-XML.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, defau | lt_description
description = ('Generates pseudo-XML from standalone reStructuredText '
'sources (for testing purposes). ' + default_description)
publish_cmdline(description=description)
|
Acebulf/HockeyPythonScripts | schedule.py | Python | mit | 3,298 | 0.006064 | #Schedule-generator for LHL use written by Acebulf (acebulf at gmail.com)
#Current version 1.0 -- Jan 16 2014
#Copyrighted under the MIT License (see License included in the github repo)
import random
import time
while 1:
print "Starting random-schedule generation process..."
starttime = time.time()
kill ... | ms_2)
teams_3 = list(teams_2)
teams_3.remove(team3)
matchups=[]
for x in teams_3:
matchups.append((team3,x))
team4 = random.choice(teams_3)
teams_4 = list(teams_3)
teams_4.remove(team4)
for x in teams_4:
matchups.append((team4,x))
matchups.append | ((teams_4[0],teams_4[1]))
for x in days2games:
for y in matchups:
if not playing_day(y[0],x) and not playing_day(y[1],x):
x.append(y)
newmatchups = []
for x in matchups:
newmatchups.append(x)
newmatchups.append(x)
random.shuffle(newmatchups)
pri... |
royalharsh/grpc | src/python/grpcio_tests/tests/unit/_empty_message_test.py | Python | bsd-3-clause | 5,056 | 0.000198 | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | ndorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTI... | RIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT L... |
beni55/sentry | src/sentry/plugins/sentry_useragents/models.py | Python | bsd-3-clause | 2,383 | 0.00042 | """
sentry.plugins.sentry_useragents.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import httpagentparser
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plu... | get_tag_from_ua(ua)
if not result:
return []
return [result]
class Browse | rPlugin(UserAgentPlugin):
"""
Automatically adds the 'browser' tag from events containing interface data
from ``sentry.interfaes.Http``.
"""
slug = 'browsers'
title = _('Auto Tag: Browsers')
tag = 'browser'
tag_label = _('Browser Name')
def get_tag_from_ua(self, ua):
if 'bro... |
TribeMedia/synapse | tests/events/test_utils.py | Python | apache-2.0 | 8,591 | 0.000582 | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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... | )
def test_basic_keys(self):
self.run_test(
{
'type': 'A',
'room_id': '!1:domain',
'sender': '@2:domain',
'event_id': '$3:domain',
'origin': 'domain',
| },
{
'type': 'A',
'room_id': '!1:domain',
'sender': '@2:domain',
'event_id': '$3:domain',
'origin': 'domain',
'content': {},
'signatures': {},
'unsigned': {},
}
... |
PACKED-vzw/scoremodel | example_config.py | Python | gpl-2.0 | 1,348 | 0.002967 | import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = False
##
# Database settings
##
DB_HOST = 'localhost'
DB_NAME = 'scoremodel'
DB_USER = 'scoremodel'
DB_PASS = 'scoremodel'
##
# MySQL SSL connections
##
use_ssl = False
SSL_CA = '/etc/mysql/certs/ca-cert.pem'
SSL_KEY = '/etc/mysql/keys/client-key... | pdf', 'png', 'jpg', 'jpeg', 'gif')
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB
##
# Logger
##
LOG_FILENAME = 'logs/scoremodel.log'
if use_ssl is True:
SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://{user}:{passw}@{host}/{db}?ssl_key={ssl_key}&ssl_cert={ssl_cert}'.format(
user=DB_USER, passw=DB_P... | =SSL_KEY, ssl_cert=SSL_CERT)
else:
SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://{user}:{passw}@{host}/{db}'.format(user=DB_USER, passw=DB_PASS,
host=DB_HOST, db=DB_NAME)
|
MitchTalmadge/Emoji-Tools | src/main/resources/PythonScripts/fontTools/misc/macRes.py | Python | gpl-3.0 | 6,563 | 0.026512 | """ Tools for reading Mac resource forks. """
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import struct
from fontTools.misc import sstruct
from collections import OrderedDict
try:
from collections.abc import MutableMapping
except ImportError:
from UserDict import... | seek offset ('offset' is too large)")
if self.file.tell() != offset:
raise ResourceError('Failed to seek offset (reached EOF)')
try:
data = self.file.read(numBytes)
except OverflowError:
raise ResourceError("Cannot read resource ('numBytes' is too large)")
if len(data) != numBytes:
raise ResourceE... | sourceForkHeader, headerData, self)
# seek to resource map, skip reserved
mapOffset = self.mapOffset + 22
resourceMapData = self._read(ResourceMapHeaderSize, mapOffset)
sstruct.unpack(ResourceMapHeader, resourceMapData, self)
self.absTypeListOffset = self.mapOffset + self.typeListOffset
self.absNameListOffs... |
lw7360/dailyprogrammer | Intermediate/226/226.py | Python | mit | 1,541 | 0.00584 | # https://www.reddit.com/r/dailyprogrammer/comments/3fva66/20150805_challenge_226_intermediate_connect_four/
import sys, string
xmoves = open(sys.argv[1]).read().translate(None, string.ascii_lowercase + ' \n')
omoves = open(sys.argv[1]).read().translate(None, string.ascii_uppercase + ' \n')
board = [[' ' for x in ra... | br | eak
|
liweitianux/atoolbox | python/msvst_starlet.py | Python | mit | 23,422 | 0.003074 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# References:
# [1] Jean-Luc Starck, Fionn Murtagh & Jalal M. Fadili
# Sparse Image and Signal Processing: Wavelets, Curvelets, Morphological Diversity
# Section 3.5, 6.6
#
# Credits:
# [1] https://github.com/abrazhe/image-funcut/blob/master/imfun/atrous.py
#
# A... | e array index is the same as the decompositio | n scale.
filters = []
phi = None # wavelet scaling function (2D)
level = 0 # number of transform level
decomposition = None # decomposed coefficients/images
reconstruction = None # reconstructed image
# convolution boundary condition
boundary = "symm"
d... |
allembedded/python_web_framework | WebApplication/Views/PageView.py | Python | gpl-3.0 | 781 | 0.008963 | """
Page view class
"""
import os
from Server.Importer import ImportFromModule
class PageView(ImportFromModule("Server.PageViewBase", "PageViewBase")):
"""
Page view class.
"""
_PAGE_TITLE = "Python Web Framework"
def __init__(sel | f, htmlToLoad):
"""
| Constructor.
- htmlToLoad : HTML to load
"""
self.SetPageTitle(self._PAGE_TITLE)
self.AddMetaData("charset=\"UTF-8\"")
self.AddMetaData("name=\"viewport\" content=\"width=device-width, initial-scale=1\"")
self.AddStyleSheet("/css/styles.css")
self.AddJavaS... |
Geoportail-Luxembourg/geoportailv3 | geoportal/LUX_alembic/versions/17fb1559a5cd_create_table_for_hierarchy_of_accounts.py | Python | mit | 2,012 | 0.000994 | """create table for hierarchy of accounts
Revision ID: 17fb1559a5cd
Revises: 3b7de32aebed
Create Date: 2015-09-16 14:20:30.972593
"""
# revision identifiers, used by Alembic.
revision = '17fb1559a5cd'
down_revision = '3b7de32aebed'
branch_labels = None
depends_on = None
from alembic import op, context
import sqlalc... | ather VARCHAR;"
"res_login_father VARCHAR;"
"c_father Cursor (p_login VARCHAR) FOR "
"Select login_father From %( | schema)s.lux_user_inheritance Where "
"login = p_login;"
"BEGIN "
"cur_login_father := child_login;"
"LOOP "
"OPEN c_father(cur_login_father);"
"FETCH FIRST FROM c_father into res_login_father;"
"IF FOUND THEN "
"cur_login_father := res_login_father;"
... |
miurahr/seahub | seahub/related_files/models.py | Python | apache-2.0 | 2,806 | 0.002495 | # -*- coding: utf-8 -*-
import os
from django.db import models
from django.db.models import Q
from seahub.tags.models import FileUUIDMap
from seahub.utils import normalize_file_path
class RelatedFilesManager(models.Manager):
def get_related_files_uuid(self, uuid):
related_files_uuid = super(RelatedFi... | ted_id):
try:
return super(RelatedFilesManager, self).get(pk=related_id)
except self.model.DoesNotExist:
return None
def delete_related_file_uuid(self, related_id):
try:
file_related = super(RelatedF | ilesManager, self).get(pk=related_id)
file_related.delete()
return True
except self.model.DoesNotExist:
return False
class RelatedFiles(models.Model):
o_uuid = models.ForeignKey(FileUUIDMap, db_index=True, on_delete=models.CASCADE, related_name='o_uuid')
r_uuid = m... |
rwl/PyCIM | CIM14/ENTSOE/StateVariables/StateVariables/SvShuntCompensatorSections.py | Python | mit | 2,935 | 0.002726 | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... | the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WA | RRANTY 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 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWIS... |
schoolie/bokeh | examples/howto/layouts/dashboard.py | Python | bsd-3-clause | 2,816 | 0.002131 | import numpy as np
from bokeh.layouts import layout
from bokeh.models import CustomJS, Slider, ColumnDataSource, WidgetBox
from bokeh.plotting import figure, output_file, show
output_file('dashboard.html')
tools = 'pan'
def bollinger():
# Define Bollinger Bands.
upperband = np.random.random_integers(100, 1... | et_slider)
return [widgets, plot]
def linked_panning():
N = 100
x = np.linspace(0, 4 * np.pi, N)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) + np.cos(x)
s1 = figure(tools=tools)
s1.circle(x, y1, color="navy", size=8, alpha=0.5)
s2 = figure(tools=tools, x_range=s1.x_range, y_range... | s2.circle(x, y2, color="firebrick", size=8, alpha=0.5)
s3 = figure(tools='pan, box_select', x_range=s1.x_range)
s3.circle(x, y3, color="olive", size=8, alpha=0.5)
return [s1, s2, s3]
l = layout([
bollinger(),
slider(),
linked_panning(),
], sizing_mode='stretch_both')
show(l)
|
zenodo/invenio | invenio/modules/formatter/format_elements/bfe_arxiv_link.py | Python | gpl-2.0 | 1,776 | 0.002815 | # This file is part of Invenio.
# Copyright (C) 2014 CERN.
#
# Invenio 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.
#
# Invenio is d... | e(target, True),
escape(_("This article on arXiv.org"), True),
escape(arxiv_id))
return ""
def escape_values(bf | o):
"""
Called by BibFormat in order to check if output of this element
should be escaped.
"""
return 0
|
CAST-projects/Extension-SDK | samples/analyzer_level/mainframe/mainframe.quality_rule/empty_paragraph_end.py | Python | mit | 1,192 | 0.012584 | from cast.analysers import log, mainframe
class EmptyParagraphEndOfSection(mainframe.Extension):
def __init__(self):
self.program = None
def start_program(self, program):
self.program = program
def end_program(self, _):
self.program = None
def start_section(self... |
kind = children[0].get_kind()
if kind not in ['exit', 'stop_run', 'goback']:
self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
else:
| # violation test_ko1
self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
|
c-PRIMED/puq | test/CustomParameter_test.py | Python | mit | 7,647 | 0.024062 | #! /usr/bin/env python
'''
Testsuite for the CustomParameter class
'''
from __future__ import absolute_import, division, print_function
import numpy as np
from puq import *
def _hisplot(y, nbins):
n, bins = np.histogram(y, nbins, normed=True)
mids = bins[:-1] + np.diff(bins) / 2.0
return mids, n
def compa... | rozero():
a = np.array([0, 0, 0])
c = CustomParameter('x', 'unknown', pdf=ExperimentalPDF(a))
assert | c.pdf.mean == 0
assert c.pdf.dev == 0
assert c.pdf.mode == 0
def test_custom_pdf_zerozerozero_fit():
a = np.array([0, 0, 0])
c = CustomParameter('x', 'unknown', pdf=ExperimentalPDF(a, fit=True))
assert c.pdf.mean == 0
assert c.pdf.dev == 0
assert c.pdf.mode == 0
def test_custom_pdf_const... |
PandaWei/tp-libvirt | libvirt/tests/src/guest_kernel_debugging/nmi_test.py | Python | gpl-2.0 | 3,444 | 0.000871 | import logging
from virttest import virsh
from provider import libvirt_version
from autotest.client.shared import error
def run_cmd_in_guest(vm, cmd):
"""
Run command in the guest
:params vm: vm object
:params cmd: a command needs to be ran
"""
session = vm.wait_for_login()
status, output... | check Non-maskable interrupts times
if real_nmi_times != expected_nmi_times:
raise error.TestFail("NMI times aren't expected %s:%s",
real_nmi_times, expec | ted_nmi_times)
|
LMescheder/AdversarialVariationalBayes | avb/inputs.py | Python | mit | 4,913 | 0.002239 | import numpy as np
import tensorflow as tf
import os
def get_inputs(split, config):
split_dir = config['split_dir']
data_dir = config['data_dir']
dataset = config['dataset']
split_file = os.path.join(split_dir, dataset, split + '.lst')
filename_queue = get_filename_queue(split_file, os.path.join(d... | t8)
# The first bytes represent the label, which we convert from uint8->int32.
label = tf.cast(record[0], tf.int32)
# The remaining bytes after the label represent the image, which we reshape
# from [depth * height * width] to [depth, height, width].
#tf.strided_slice(record, [label_bytes], [label... | age = tf.cast(image, tf.float32)/255.
# Convert from [depth, height, width] to [height, width, depth].
image = tf.transpose(image, [1, 2, 0])
return image
def get_filename_queue(split_file, data_dir):
with open(split_file, 'r') as f:
filenames = f.readlines()
filenames = [os.path.join(data... |
mikehankey/fireball_camera | scan-stills2.py | Python | gpl-3.0 | 42,716 | 0.043426 | #!/usr/bin/python3
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from sklearn.cluster import KMeans
from sklearn import datasets
from PIL import Image, ImageChops
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
from random ... |
line_group = []
orphan_lines = []
if len(sorted_lines) > 0:
| for segment in sorted_lines:
dist,angle,x1,y1,x2,y2 = segment
if last_ang != 0 and (angle -5 < last_ang < angle + 5) and dist < 100:
#print ("Line Segment Part of Existing Group: ", segment)
line_group.append((dist,angle,x1,y1,x2,y2))
else:
#print ("New... |
anomen-s/programming-challenges | coderbyte.com/easy/Multiplicative Persistence/solve.py | Python | gpl-2.0 | 820 | 0.02439 | '''
Using the Python l | anguage, have the function MultiplicativePersistence(num)
take the num parameter being passed which will always be a positive integer
and return its multiplicative persistence which is the number of times
you must multiply the digits in num until you reach a single digit.
For example: if num is 39 then your progra... | n 3
because 3 * 9 = 27 then 2 * 7 = 14 and finally 1 * 4 = 4 and you stop at 4.
'''
def MultiplicativePersistence(num):
steps = 0
while num > 9:
snum = str(num)
sdigits = list(snum)
num = 1
for snum in sdigits:
n = int(snum)
num = num * n
steps = steps + 1
return ste... |
OCA/OpenUpgrade | openupgrade_scripts/scripts/sale/14.0.1.1/pre-migration.py | Python | agpl-3.0 | 1,334 | 0.001499 | # Copyright 2021 ForgeFlow S.L. <https://www.forgeflow.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
_xmlid_renames = [
(
"sale.access_product_product_attribute_cu | stom_value",
"sale.access_product_product_attribute_custom_value_sale_manager",
),
("sale.account_move_see_all", "sale.account_invoice_rule_see_all"),
("sale.account_move_personal_rule", "sale.account_invoice_rule_see_personal"),
("sale.account_move_line_see_all", "sale. | account_invoice_line_rule_see_all"),
(
"sale.account_move_line_personal_rule",
"sale.account_invoice_line_rule_see_personal",
),
]
def fast_fill_sale_order_currency_id(env):
if not openupgrade.column_exists(env.cr, "sale_order", "currency_id"):
openupgrade.logged_query(
... |
MarcoDalFarra/semseg | DataGenerators.py | Python | mit | 48,218 | 0.001307 | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import IPython
import os
import threading
import warnings
import scipy.ndimage as ndi
import cv2
import random
try:
from PIL import Image as pil_image
except ImportError:
pil_image = None
from keras import backend... | s a random sp | atial shear of a Numpy image tensor.
# Arguments
x: Input tensor. Must be 3D.
intensity: Transformation intensity.
row_axis: Index of axis for rows in the input tensor.
col_axis: Index of axis for columns in the input tensor.
channel_axis: Index of axis for channels in the in... |
davelab6/pyfontaine | fontaine/charsets/internals/google_extras.py | Python | gpl-3.0 | 372 | 0.016129 | # -*- cod | ing: utf-8 -*-
class Charset:
common_name = u'Google Fonts: Extras'
native_name = u''
def glyphs(self):
glyphs = [0xe0ff] # PUA: Font logo
glyphs += [0xeffd] # PUA: Font version number
glyphs += [0xf000] # PUA: font ppem size indicator: run `ftview -f 1255 10 Ubuntu | -Regular.ttf` to see it in action!
return glyphs
|
DiUS/Physiognomy | python/align_faces.py | Python | mit | 4,189 | 0.020769 | #!/usr/bin/env python
# Software License Agreement (BSD License) |
#
# Copyright (c) 2012, Philipp Wagner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must reta | in the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Ne... |
claashk/python-config | tests/context/attribute.py | Python | gpl-3.0 | 3,198 | 0.014071 | # -*- coding: utf-8 -*-
import unittest
from config.context import Attribute, | attr
class Data(object):
pass
class AttributeTestCase(unittest.TestCase):
def setUp(self):
self.data= Data()
self.data.int2= 1
self.integer= 3
self.int1= Attribute("int1", destObj= self.data, valueType=int)
self.int2= Attribute("int2", | destObj= self.data)
self.int3= Attribute("integer", destObj= self)
self.flt1= Attribute("flt",
destObj= self.data,
destName="float",
valueType=float )
self.flt2= Attribute("value", valueType= float)
... |
luistorresm/sale-workflow | sale_exceptions/__openerp__.py | Python | agpl-3.0 | 2,062 | 0 | # -*- coding: u | tf-8 -*-
#
#
# OpenERP, Open Source Management Solution
# Authors: Raphaël Valyi, Renato Lima
# Copyright (C) 2011 Akretion LTDA.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software F... | .
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affer... |
bhermanmit/openmc | examples/python/boxes/build-xml.py | Python | mit | 4,480 | 0.000446 | import numpy as np
import openmc
###############################################################################
# Simulation Input File Parameters
###############################################################################
# OpenMC simulation parameters
batches = 15
inactive = 5
particles = ... | d_element('H', 2.)
moderator.add_element('O', 1.)
moderator.add_s_alpha_beta('c_H_in_H2O')
# Instant | iate a Materials collection and export to XML
materials_file = openmc.Materials([fuel1, fuel2, moderator])
materials_file.export_to_xml()
###############################################################################
# Exporting to OpenMC geometry.xml file
############################################... |
ez-p/madness | tournament/engine/region.py | Python | gpl-3.0 | 2,088 | 0.005747 | """
Copyright 2016, Paul Powell, All rights reserved.
"""
import team
import round
class Region:
def __init__(self, name, teams, algorithm):
self.initialize(name, teams)
self.name = name
self.rounds = []
self.algorithm = algorithm
self.final = None
def __call__(self, ma... | elf.name, 1, madness, self.algorithm, self.matchups)
round2 = round1.go()
round3 = round2.go()
round4 = round3.go()
self.rounds = [round1, round2, round3, round4]
# Special hacks for final round
self.final = self.algorithm(round4.games[0], madness)
round4.winner ... | ze(self, name, teams):
# Looks like [((1,16), (8,9)), ((5,12), (4,13)), ((6,11), (3,14)), ((7,10), (2,15))]
sregion = name
game1 = (team.Team(teams[1], sregion, 1), team.Team(teams[16], sregion, 16))
game2 = (team.Team(teams[8], sregion, 8), team.Team(teams[9], sregion, 9))
game3... |
autosportlabs/RaceCapture_App | autosportlabs/racecapture/views/status/statusview.py | Python | gpl-3.0 | 14,474 | 0.002418 | #
# Race Capture App
#
# Copyright (C) 2014-2017 Autosport Labs
#
# This file is part of the Race Capture App
#
# This 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 ... | 'OK',
'Good',
'Good',
'Good',
'Good',
'Good',
'Excellent',
'Excel | lent',
'Excellent',
'Excellent',
'Excellent',
'Excellent',
'Excellent',
'Excellent',
'Excellent',
'Excellent',
'Excellent'
]
},
'b... |
jhprinz/openpathsampling | openpathsampling/visualize.py | Python | lgpl-2.1 | 92,760 | 0.000571 | import openpathsampling.pathmover_inout
import svgwrite as svg
from svgwrite.container import Group
import openpathsampling as paths
import os
import ujson
from collections import namedtuple, OrderedDict, Counter
# TODO: Move TreeRenderer and Builder to a different file ???
class TreeRenderer(svg.Drawing):
"""
... | tend_left:
group.add(self.circle(
center=self.xy(x - 0.5, y),
r=self.w(padding)
| ))
if extend_right:
group.add(self.circle(
center=(self.xy(x + w - 0.5, y)),
r=self.w(padding)
))
if extend_top:
group.add(self.circle(
center=self.xy(x, y - 0.3),
r=self.w(padding)
... |
akaszynski/vtkInterface | examples/01-filter/boolean-operations.py | Python | mit | 3,395 | 0.000884 | """
Boolean Operations
~~~~~~~~~~~~~~~~~~
Perform boolean operations with closed surfaces (intersect, cut, etc.).
Boolean/topological operations (intersect, cut, etc.) methods are implemented
for :class:`pyvista.PolyData` mesh types only and are accessible directly from
any :class:`pyvista.PolyData` mesh. Check out :... | boolean_cut`
* :func:`pyvista.PolyDataFilters.boolean_difference`
* :func:`pyvista.PolyDataFilters.boolean_union`
For merging, the ``+`` operator can be used between any two meshes in PyVista
which simply calls the ``.merge()`` filter to combine any two meshes.
Similarly, the ``-`` operator can be used between any two... | mpy as np
def make_cube():
x = np.linspace(-0.5, 0.5, 25)
grid = pv.StructuredGrid(*np.meshgrid(x, x, x))
return grid.extract_surface().triangulate()
# Create to example PolyData meshes for boolean operations
sphere = pv.Sphere(radius=0.65, center=(0, 0, 0))
cube = make_cube()
p = pv.Plotter()
p.add_mesh... |
conda-forge/conda-forge.github.io | scripts/update_teams.py | Python | bsd-3-clause | 4,482 | 0.00357 | #!/usr/bin/env conda-execute
# conda execute
# env:
# - python 2.7.*
# - conda-smithy
# - pygithub 1.*
# - six
# - conda-build
# channels:
# - conda-forge
# run_with: python
from __future__ import print_function
import argparse
import collections
import os
import six
from github import Github
import github
im... | t('recipe-maintainers', [])
if not isinstance(contributors, list):
# Deal with a contribution list which has dashes but no spaces
| # (e.g. https://github.com/conda-forge/pandoc-feedstock/issues/1)
contributors = [contributors.lstrip('-')]
contributors = set(handle.lower() for handle in contributors)
all_members.update(contributors)
# If the team already exists, get hold of it.
team = teams.get(package_name)
if no... |
rsalmaso/django-cms | cms/admin/forms.py | Python | bsd-3-clause | 49,683 | 0.001751 | from django import forms
from django.apps import apps
from django.contrib.auth import get_permission_codename, get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core.exceptions import Objec... | rious page_types
descendants = root_page.get_descendant_pages().filter(is_page_type=True)
titles = Title.objects.filter(page__in=descendants, language=self._language)
choices = [('', '---------')]
choices.extend((title.page_id, title.title) for title in titles)
... | choices = []
if len(choices) < 2:
source_field.widget = forms.HiddenInput()
def clean(self):
data = self.cleaned_data
if self._errors:
# Form already has errors, best to let those be
# addressed first.
return data
parent_node =... |
digifant/eMonitor | emonitor/signals.py | Python | bsd-3-clause | 1,692 | 0.002364 | from blinker import Namespace
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class MySignal:
def __init__(self):
self.signals = {}
self.signal = Namespace()
def init_app(self, app):
| pass
def addSignal(self, classname, option):
logger.debug('add signal {}.{}'.format(classname, opti | on))
if '{}.{}'.format(classname, option) not in self.signals.keys():
self.signals['{}.{}'.format(classname, option)] = self.signal.signal('{}.{}'.format(classname, option))
def send(self, classname, option, **extra):
logger.debug('send signal {}.{} with: {}'.format(classname, option, e... |
takearest118/coconut | common/hashers.py | Python | gpl-3.0 | 1,030 | 0.000971 | # -*- coding: utf-8 -*-
import re
import string
import random
import pbkdf2
HASHING_ITERATIONS = 400
ALLOWED_IN_SALT = string.ascii_letters + string.digits + './'
ALLOWD_PASSWORD_PATTERN = r'[A-Za-z0-9@#$%^&+=]{8,}'
def generate_random_string(len=12, allowed_chars=string.ascii_letters+string.digits):
return ''.... | lt = generate_random_string(len=32, allowed_chars=ALLOWED_IN_SALT)
return pbkdf2.crypt(password, salt=salt, iterations=HASHING_ITERATIONS)
def check_password(password, hashed_password):
return hashed_password == pbkdf2.crypt(password, hashed_password)
def validate_password(password=None):
"""
ALLOWE... | """
if password is None:
raise ValueError('password is required')
if re.match(ALLOWD_PASSWORD_PATTERN, password):
return True
return False
|
AutorestCI/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/partition_health.py | Python | mit | 2,612 | 0.002297 | # 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 ... | : 'HealthEvents', 'type': '[HealthEvent]'},
'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[Health | EvaluationWrapper]'},
'health_statistics': {'key': 'HealthStatistics', 'type': 'HealthStatistics'},
'partition_id': {'key': 'PartitionId', 'type': 'str'},
'replica_health_states': {'key': 'ReplicaHealthStates', 'type': '[ReplicaHealthState]'},
}
def __init__(self, aggregated_health_stat... |
joegomes/deepchem | examples/chembl/chembl_graph_conv.py | Python | mit | 1,974 | 0.00152 | """
Script that trains graph-conv models on ChEMBL dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from chembl_datasets import load_che... | 1e-5, mode=1) | )
graph_model.add(dc.nn.GraphPool())
# Gather Projection
graph_model.add(dc.nn.Dense(256, 128, activation='relu'))
graph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))
graph_model.add(dc.nn.GraphGather(batch_size, activation="tanh"))
model = dc.models.MultitaskGraphRegressor(
graph_model,
len(chembl... |
pcmoritz/ray-1 | rllib/agents/dreamer/dreamer_model.py | Python | apache-2.0 | 19,097 | 0.000052 | import numpy as np
from typing import Any, List, Tuple
from ray.rllib.models.torch.misc import Reshape
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.framework import TensorType
torch, nn = try_import_torch()
if torch:
from ... | self.act(),
Conv2d(4 * self.depth, 8 * self.depth, 4, stride=2),
self.act(),
]
self.model = nn.Sequential(*self.layers)
def forward(self, x):
# Flatten to [batch*horizon, 3, 64, 64] in loss f | unction
orig_shape = list(x.size())
x = x.view(-1, *(orig_shape[-3:]))
x = self.model(x)
new_shape = orig_shape[:-3] + [32 * self.depth]
x = x.view(*new_shape)
return x
# Decoder, part of PlaNET
class ConvDecoder(nn.Module):
"""Standard Convolutional Decoder for Dr... |
aykol/mean-square-displacement | xdatcar2xyz.1.04.py | Python | mit | 2,939 | 0.008166 | # The MIT License (MIT)
#
# Copyright (c) 2014 Muratahan Aykol
#
# 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, m... | R ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
import numpy as np
xdatcar = open('XDATCAR', 'r')
xyz = open('XDATCAR.xyz', 'w')
xyz_fract = open('XDATCAR_fract.xyz'... |
system = xdatcar.readline()
scale = float(xdatcar.readline().rstrip('\n'))
print scale
#get lattice vectors
a1 = np.array([ float(s)*scale for s in xdatcar.readline().rstrip('\n').split() ])
a2 = np.array([ float(s)*scale for s in xdatcar.readline().rstrip('\n').split() ])
a3 = np.array([ float(s)*scale for s in xdat... |
joewashear007/jazzy | jazzy/functions/OutputFunc.py | Python | mit | 462 | 0.008658 | __all__ = ['jazPrint', 'jazShow']
class jazPrint:
def __init__(self):
| self.command = "print";
def call(self, | interpreter, arg):
return interpreter.GetScope().GetStackTop()
class jazShow:
def __init__(self):
self.command = "show";
def call(self, interpreter, arg):
return arg;
# A dictionary of the classes in this file
# used to autoload the functions
Functions = {'jazShow': jazShow, 'jazPri... |
pyfisch/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/webdriver_server.py | Python | mpl-2.0 | 8,378 | 0.001432 | import abc
import errno
import os
import platform
import socket
import time
import traceback
import mozprocess
__all__ = ["SeleniumServer", "ChromeDriverServer", "EdgeChromiumDriverServer", "OperaDriverServer",
"GeckoDriverServer", "InternetExplorerDriverServer", "EdgeDriverServer",
"ServoDrive... | "to --webdriver-binary argument")
self.logger = logger
self.binary = binary
self.host = host
if base_path == "":
self.base_path = self.default_base_path
else:
self.base_path = base_path
self.env = os.environ.copy() if env is None else env
... | f args is not None else []
self._proc = None
@abc.abstractmethod
def make_command(self):
"""Returns the full command for starting the server process as a list."""
def start(self, block=False):
try:
self._run(block)
except KeyboardInterrupt:
self.stop... |
oneandoneis2/dd-agent | checks.d/sqlserver.py | Python | bsd-3-clause | 17,085 | 0.002341 | '''
Check the performance counters from SQL Server
See http://blogs.msdn.com/b/psssql/archive/2013/09/23/interpreting-the-counter-values-from-sys-dm-os-performance-counters.aspx
for information on how to report the metrics available in the sys.dm_os_performance_counters table
'''
# stdlib
import traceback
# 3rd party... | collect(self, instance, custom_metrics):
"""
Store the list of metrics to collect by instance_key.
Will also create and cache cursors to query the db.
| """
metrics_to_collect = []
for name, counter_name, instance_name in self.METRICS:
try:
sql_type, base_name = self.get_sql_type(instance, counter_name)
metrics_to_collect.append(self.typed_metric(name,
... |
JshWright/home-assistant | homeassistant/components/media_player/webostv.py | Python | apache-2.0 | 12,114 | 0 | """
Support for interface with an LG webOS Smart TV.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.webostv/
"""
import logging
import asyncio
from datetime import timedelta
from urllib.parse import urlparse
import voluptuous as vol
import... | st in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING[host], 'Failed to pair, please try again.')
return
# pylint: disable=unused-argument
def lgtv_configuration_callback(data):
"""Handle configuration changes."""
setup_tv(host, mac, name, customize, config, h... | on your TV.',
description_image='/static/images/config_webos.png',
submit_caption='Start pairing request'
)
class LgWebOSDevice(MediaPlayerDevice):
"""Representation of a LG WebOS TV."""
def __init__(self, host, mac, name, customize, config):
"""Initialize the webos device."""
... |
makiwara/onemoretime | settings/db_settings_sample.py | Python | mit | 267 | 0.003745 | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'PUTPASSWORDHER | E',
'HOST': '127.0.0.1',
'PORT': ' | 5432',
}
} |
JohnCremona/bianchi-progs | FD/H3.py | Python | gpl-3.0 | 72,028 | 0.008872 | # Functions for working with H3 and hemispheres etc.
from itertools import chain
from sage.all import (Infinity, Matrix, ZZ, QQ, RR, CC, NumberField,
Graph, srange, Set, sign, var, implicit_plot3d, NFCusp, Integer, oo,
infinity, polygen, point, line, circle)
from utils imp... | pheres(P, 'exact')
def properly_covering_hemispheres(P):
return covering_hemispheres(P, | 'strict')
d |
dsaldana/roomba_sensor_network | localization_artrack/camera_controller/scripts/frame_broadcaster.py | Python | gpl-3.0 | 678 | 0.042773 | #!/usr/bin/env python
import roslib
roslib.load_manifest('camera_controller')
import rospy
import tf
if __name__ == '__main__':
rospy.init_node('frame_broadcaster')
| br = tf.TransformBroadcaster()
rate = rospy.Rate(10.0)
target_frame = rospy.get_param("~target_frame")
# Camera position
# Translation
x = rospy.get_param("~x",0)
y = rospy.get_param("~y",0)
z = rospy.get_param("~z",0)
# Pose quaternion
qm = rospy.get_param("~qm",0)
qx = rospy.get_param("~qx",0)
qy = rosp... | = rospy.get_param("~qz",1)
while not rospy.is_shutdown():
br.sendTransform((x,y,z), (qm, qx, qy, qz), rospy.Time.now(), target_frame, "world")
rate.sleep()
|
arielalmendral/ert | python/python/ert/test/test_run.py | Python | gpl-3.0 | 5,315 | 0.023518 | # Copyright (C) 2013 Statoil ASA, Norway.
#
# The file 'test_run.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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, teither version 3 of... | self.workflows = []
if name:
| self.name = name
else:
self.name = config_file.replace("/" , ".")
while True:
if self.name[0] == ".":
self.name = self.name[1:]
else:
break
self.name += "/%08d" % random.ra... |
lsbardel/flow | flow/db/instdata/pricers/future.py | Python | bsd-3-clause | 158 | 0.031646 | from equity import EquityP | ricer
class FuturePricer | (EquityPricer):
def __init__(self):
super(FuturePricer,self).__init__()
|
raonyguimaraes/mendelmd | individuals/views.py | Python | bsd-3-clause | 23,385 | 0.008766 | import gzip
import json
import os
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.core.paginator import Paginator
from django.db.mode... | View(DeleteView):
model = Individual
def delete(self, request, *args, **kwargs):
"""
This does not actually delete the file, only the database record. But
that is easy to implement.
"""
self.objec | t = self.get_object()
individual_id = self.object.id
if self.object.user:
username = self.object.user.username
else:
username = 'public'
#delete files
if self.object.vcf_file:
self.object.vcf_file.delete()
# if self.object.st... |
dymkowsk/mantid | Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/sans/SANSCreateWavelengthAndPixelAdjustmentTest.py | Python | gpl-3.0 | 7,906 | 0.004048 | from __future__ import (absolute_import, division, print_function)
import unittest
import mantid
import os
import numpy as np
from sans.test_helper.test_director import TestDirector
from sans.state.wavelength_and_pixel_adjustment import get_wavelength_and_pixel_adjustment_builder
from sans.common.enums import (RebinTy... | " 7.00000 5.000000e-01 5.000000e-01\n"
" 9.00000 5.000000e-01 5.000000e-01\n"
" | 11.00000 5.000000e-01 5.000000e-01\n")
full_file_path = os.path.join(mantid.config.getString('defaultsave.directory'), file_name)
if os.path.exists(full_file_path):
os.remove(full_file_path)
with open(full_file_path, 'w') as f:
f.write(test_file)
retur... |
OrlyMar/gasistafelice | gasistafelice/rest/views/blocks/order.py | Python | agpl-3.0 | 7,205 | 0.010548 | from django.utils.translation import ugettext as _, ugettext_lazy as _lazy
from django.core import urlresolvers
from gasistafelice.rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction
from gasistafelice.consts import CREATE, EDIT, EDIT_MULTIPLE, VIEW
from gasistafelice.lib.shortcuts import render_to_x... | ithRequest
from django.forms.formsets import formset_factory
import logging
log = logging.getLogger(__name__)
#----------------------------------- | -------------------------------------------#
# #
#------------------------------------------------------------------------------#
class Block(BlockSSDataTables):
# COMMENT fero: name of this block should be
# something different from... |
randyhook/knynet | simulator/sensors/SimAudioSensor.py | Python | mit | 325 | 0.006154 | from simulator.sensors.SimSensor import SimSensor
from environment.SensoryData import SensoryData
class | SimAudioSensor(SimSensor):
def __init__(self, parentBot, name):
super().__init__('Audio', parentBot, name)
def receiveAudio(self, audio):
return Sensor | yData(self.name, 'Audio', audio)
|
dedeco/cnddh-denuncias | cnddh/decorators.py | Python | apache-2.0 | 593 | 0.005059 | # coding=latin-1
from flask import request, g
from flask import abort, flash
from functools import wra | ps
def checa_permissao(permissao):
def decorator(f):
@wraps(f)
def inner(*args, **kwargs):
if g.user and g.user.checa_permissao(permissao):
return f(*args, **kwargs)
else:
flash(u'Atenção você não possui a permissão: %s. Se isto não e... | ando esta permissão.' % permissao.upper(),u'notice')
abort(401)
return inner
return decorator
|
JeffRoy/mi-dataset | mi/dataset/driver/velpt_ab/dcl/velpt_ab_dcl_recovered_driver.py | Python | bsd-2-clause | 2,466 | 0.003244 | #!/usr/bin/env python
"""
@package mi.dataset.driver.velpt_ab.dcl
@file mi-dataset/mi/dataset/driver/velpt_ab/dcl/velpt_ab_dcl_recovered_driver.py
@author Joe Padula
@brief Recovered driver for the velpt_ab_dcl instrument
Release notes:
Initial Release
"""
from mi.dataset.dataset_parser import DataSetDriverConfigKe... | d, \
VelptAbDclInstrumentDataParticleRecovered, \
VelptAbDclDiagnosticsHeaderParticleRecovered
from mi.core.versioning im | port version
@version("15.7.0")
def parse(basePythonCodePath, sourceFilePath, particleDataHdlrObj):
"""
This is the method called by Uframe
:param basePythonCodePath This is the file system location of mi-dataset
:param sourceFilePath This is the full path and filename of the file to be parsed
:pa... |
Architektor/PySnip | venv/lib/python2.7/site-packages/twisted/test/test_stdio.py | Python | gpl-3.0 | 13,157 | 0.001216 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet.stdio}.
@var properEnv: A copy of L{os.environ} which has L{bytes} keys/values on POSIX
platforms and native L{str} keys/values on Windows.
"""
from __future__ import absolute_import, division
import os
impo... |
def __init__(self):
self.onConnection = defer.Deferred()
self.onCompletion = defer.Deferred()
self.data = {}
def conn | ectionMade(self):
self.onConnection.callback(None)
def childDataReceived(self, name, bytes):
"""
Record all bytes received from the child process in the C{data}
dictionary. Fire C{onDataReceived} if it is not C{None}.
"""
self.data[name] = self.data.get(name, b'') ... |
andaviaco/tronido | src/syntax/types/integer.py | Python | mit | 370 | 0.002703 | from lexer import lang
from ..tree import Node
class Integer(Node):
datatype = lang.SEMANTIC_INT_TYPE
"""docstring for Integer."""
def __init__(self, symbol, token):
super().__ini | t__(symbol, token)
def generate_code(self, **cond):
array, line = Node.assignated_array()
Node.array_append(array, f'{line} LIT {self.symbol}, 0')
| |
ambitioninc/django-tour | setup.py | Python | mit | 1,710 | 0.003509 | # import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = 'tour/version.py'... | ngo-tour',
author='Wes Okes',
author_email='wes.okes@gmail.com',
keywords='',
p | ackages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.