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 |
|---|---|---|---|---|---|---|---|---|
saidsef/cloudflare | lib/__init__.py | Python | mit | 67 | 0 | # | !/usr/bin/python
# -*- coding: utf-8 -*-
| __author__ = 'Said Sef'
|
RandallDW/Aruba_plugin | plugins/org.python.pydev/pysrc/_pydevd_bundle/pydevd_frame.py | Python | epl-1.0 | 33,951 | 0.006038 | import linecache
import os.path
import re
import sys
import traceback # @Reimport
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_dont_trace
from _pydevd_bundle import pydevd_vars
from _pydevd_bundle.pydevd_breakpoints import get_exception_breakpoint
from _pydevd_bundle.pydevd_comm import CMD_ST... | return self.trace_dispatch
return self.trace_exception
# IFDEF CYTHON
# def should_stop_on_exception(self, frame, str event, arg):
# cdef PyDBAdditionalThreadInfo info;
# cdef bint flag;
# ELSE
def should_stop_on_exception(self, frame, event, arg):
# ENDIF
... | , _thread = self._args
main_debugger = self._args[0]
info = self._args[2]
flag = False
if info.pydev_state != STATE_SUSPEND: #and breakpoint is not None:
exception, value, trace = arg
if trace is not None: #on jython trace is None on the first event
... |
ekasitk/sahara | sahara/plugins/vanilla/v1_2_1/run_scripts.py | Python | apache-2.0 | 4,367 | 0 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | ode == 0 and stdout and int(stdout) == count
def mysql_start(remote):
LOG.debug("Starting MySQL")
remote.execute_command("/opt/start-mysql.sh")
def oozie_create_db(remote):
LOG.debug("Creating Oozie DB Schema")
sql_script = files.get_file_text(
'plugin | s/vanilla/v1_2_1/resources/create_oozie_db.sql')
script_location = "create_oozie_db.sql"
remote.write_file_to(script_location, sql_script)
remote.execute_command('mysql -u root < %(script_location)s && '
'rm %(script_location)s' %
{"script_location": scr... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/rest_framework/tests/test_routers.py | Python | agpl-3.0 | 7,115 | 0.000703 | from __future__ import unicode_literals
from django.db import models
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from rest_framework import serializers, viewsets, permissions
from rest_framework.compat import include, patterns, url
from rest_framework.decorators import link,... | ewSet)
self.urls = self.router.urls
def test_urls_have_trailing_slash_by_default(self):
expected = ['^notes/$', '^notes/(?P<pk>[^/]+)/$']
for idx in range(len(expected)):
self.assertEqual(expected[idx], self.urls[idx].regex.pattern)
class TestTrailingSlashRemoved(TestCase):
... | SimpleRouter(trailing_slash=False)
self.router.register(r'notes', NoteViewSet)
self.urls = self.router.urls
def test_urls_can_have_trailing_slash_removed(self):
expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$']
for idx in range(len(expected)):
self.assertEqual(expected[id... |
MadManRises/Madgine | shared/assimp/test/regression/run.py | Python | mit | 11,801 | 0.006949 | #!/usr/bin/env python3
# -*- Coding: UTF-8 -*-
# --------- | ------------------------------------------------------------------
# Open Asset Import Library (ASSIMP)
# ---------------------------------------------------------------------------
#
# Copyright (c) 2006-2010, ASSIMP Development Team
#
# All rights reserved.
#
# Redistribution and use of this software in source and bi... | e code must retain 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 dist... |
nkoukou/University_Projects_Year_3 | EDM_Assembly/base_class.py | Python | mit | 11,366 | 0.006159 | '''
Defines the base class of an electric potential grid.
'''
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
from numba import jit
# Global dimensions (used for plots)
sqc_x = (2., 'cm') # unit length for SquareCable
sqc_u = (10., 'V') # unit potential for SquareCable
edm_x = (10., 'mm')... | V') # unit potential for Edm
# Plot parameters
font = {'family | ' : 'normal',
'weight' : 'normal'}
mpl.rc('font', **font)
mpl.rcParams['lines.linewidth'] = 5.
# Functions compiled just-in-time
@jit
def gen_sc_grid(b, t, u):
'''
Generates SquareCable grid.
'''
grid = np.full((b,b), u)
fix = np.ones((b,b))
grid = np.pad(grid, ((t-b)/2,), 'constant', ... |
Samael500/social-inspector | inspector/tests/test.py | Python | mit | 105 | 0 | import uni | ttest
class TestC | olor(unittest.TestCase):
def test(self):
self.assertTrue(True)
|
sipdbg/sipdbg | server/main_server.py | Python | gpl-2.0 | 6,551 | 0.020608 | import os
import sys
import random
import logging
import signal
main_path = os.path.abspath (os.path.dirname (__file__))
prev_path = main_path + "/.."
sys.path.append (prev_path)
from utils import _redis_connect, log_init
from command import *
from RedisHelper import RedisServer
from Config import Config
from sipcore ... | ger, _confi | g):
self.s_id = 0 # Identifier for RTP/SIP service
self.rr = 1 # round robin (server id)
self.instance_cnt = 1 # server count
self.rtp = {} # rtp instance
self.sip = {} # sip instance
self._redis = _redis
self._logger = _logger
... |
AnthonyDiGirolamo/todotxt-machine | todotxt_machine/todo.py | Python | gpl-3.0 | 38,728 | 0.003823 | #!/usr/bin/env python
# coding=utf-8
import re
import random
from datetime import date
class Todo:
"""Single Todo item"""
_priority_regex = re.compile(r'\(([A-Z])\) ')
def __init__(self, item, index,
colored="", priority="", contexts=[], projects=[],
creation_date="", du... | elif w in self.projects:
color_list[index] = ('project', w) if show_projects else ''
elif w == "due:" + self.due_date:
color_list[index] = ('due_date', w) | if show_due_date else ''
elif w == self.creation_date:
color_list[index] = ('creation_date', w)
if self.priority and self.priority in "ABCDEF":
color_list = ("priority_{0}".format(self.priority.lower()), color_list)
else:
... |
xmnlab/hermes | hermes/__init__.py | Python | mit | 120 | 0 | # -*- | coding: utf-8 -*-
__author__ = """Ivan Ogasawara"""
__email__ = 'ivan.ogasawara@gmail.com'
__version__ = '0.1 | .0'
|
coreycb/charms.openstack | unit_tests/pci_responses.py | Python | apache-2.0 | 10,045 | 0.005077 | import copy
# flake8: noqa
LSPCI = """
0000:00:00.0 "Host bridge" "Intel Corporation" "Haswell-E DMI2" -r02 "Intel Corporation" "Device 0000"
0000:00:03.0 "PCI bridge" "Intel Corporation" "Haswell-E PCI Express Root Port 3" -r02 "" ""
0000:00:03.2 "PCI bridge" "Intel Corporation" "Haswell-E PCI Express Root Port 3" -r0... | Inc" "Device 00db"
0000:0f:00.0 "VGA compatible controller" "Matrox Electronics Systems Ltd." "MGA G200e [Pilot] ServerEngines (SEP1)" -r02 "Cisco Systems Inc" "Device 0101"
0000:10:00.0 "Ethernet controller" "Intel Corporation" "I350 Gigabit Network Connection" -r01 "Cisco Systems Inc" "Device 00d6"
0000:10:00.1 "Eth... | controller" "Intel Corporation" "I350 Gigabit Network Connection" -r01 "Cisco Systems Inc" "Device 00d6"
0000:7f:08.0 "System peripheral" "Intel Corporation" "Haswell-E QPI Link 0" -r02 "Intel Corporation" "Haswell-E QPI Link 0"
"""
CONFD_CLI = """
NAME PHYS ADDRESS
-------------------------------... |
ragupta-git/ImcSdk | imcsdk/mometa/equipment/EquipmentLocatorLed.py | Python | apache-2.0 | 5,417 | 0.011076 | """This module contains the general information for EquipmentLocatorLed ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class EquipmentLocatorLedConsts:
ADMIN_STATE_INACTIVE = "inactive"
ADMIN_STATE_OFF = "off"
ADMI... | tyMeta. | INTERNAL, None, None, None, None, [], []),
"color": MoPropertyMeta("color", "color", "string", VersionMeta.Version151f, MoPropertyMeta.READ_ONLY, None, None, None, None, ["amber", "blue", "green", "red", "unknown"], []),
"id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version151f, MoPrope... |
birsoyo/conan | conans/test/functional/search_recorder_test.py | Python | mit | 10,512 | 0.00333 | import unittest
from conans.client.recorder.search_recorder import SearchRecorder
class SearchRecorderTest(unittest.TestCase):
def setUp(self):
self.recorder = SearchRecorder()
def empty_test(self):
info = self.recorder.get_info()
expected_result = {'error': False, 'results': []}
... | },
"packages": [
{
"id": "fake1_package_id1",
" | options": "fake1_options1",
"settings": "fake1_settings1",
"requires": "fake1_requires1",
"outdated": False
}
... |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/test/test_nis.py | Python | gpl-3.0 | 1,167 | 0.001714 | from test import support
import unittest
import sys
# Skip test if nis module does not exist.
nis = support.import_module('nis')
class NisTests(unittest.TestCase):
def test_maps(self):
try:
maps = nis.maps()
except nis.error as msg:
# NIS is probably not active, so this te... | t k:
continue
if nis.match(k, nismap) != v:
self.fail("NIS match failed f | or key `%s' in map `%s'" % (k, nismap))
else:
# just test the one key, otherwise this test could take a
# very long time
done = 1
break
if done:
break
if __name__ == '__main__':
unittest.main... |
tomreitsma/the-weird-science | tws_game/server.py | Python | mit | 3,918 | 0.00051 | from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol
from tws_game.lobby import Lobby
from tws_game.tetris import Tetris
from pprint import pprint
import json
class ClientConnection(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
def... | = json.loads(data)
return command, data
""" Basic game co | mmands
"""
def create_lobby(self, client, data):
if not 'game' in data and data['game'] in self.AVAILABLE_GAMES:
raise Exception('Game unavailable')
lobby = Lobby(self.AVAILABLE_GAMES[data['game']])
lobby.set_factory(self)
self._lobby_id_counter += 1
lobby... |
RCOS-Grading-Server/HWserver | migration/migrator/migrations/course/20200704004101_gradeable_access.py | Python | bsd-3-clause | 1,205 | 0.004149 | """Migration for a given Submitty course database."""
def up(config, database, semester, course):
"""
Run up migration.
:param config: Object holding configuration details | about Submitty
:type config: migrator.config.Config
:param database: Object for interacting with given database for environment
:type database: migrator.db.Database
:param semester: Semester of the course being migrated
:type semester: str
:param course: Code of course bei | ng migrated
:type course: str
"""
database.execute(
"""
CREATE TABLE IF NOT EXISTS gradeable_access (
id SERIAL NOT NULL PRIMARY KEY,
g_id character varying(255) NOT NULL REFERENCES gradeable (g_id) ON DELETE CASCADE,
user_id character varying(255) REFERENC... |
eicher31/compassion-modules | sbc_compassion/controllers/__init__.py | Python | agpl-3.0 | 426 | 0 | # -*- coding: utf-8 | -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# | @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from . import b2s_image
|
nicholasserra/sentry | src/sentry/web/urls.py | Python | bsd-3-clause | 18,988 | 0.003318 | """
sentry.web.urls
~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
__all__ = ('urlpatterns',)
from django.conf.urls import include, patterns, url
from django.conf import settings
from ... | _error_embed import DebugErrorPageEmbedView
from sentry.web.fronten | d.debug.debug_new_release_email import DebugNewReleaseEmailView
urlpatterns += patterns(
'',
url(r'^debug/mail/new-event/$',
sentry.web.frontend.debug.mail.new_event),
url(r'^debug/mail/new-note/$',
sentry.web.frontend.debug.mail.new_note),
url(r'^debug/mail/... |
Aneapiy/graph_visualization_Yelp | dataProcScripts/replaceLinesFull.py | Python | apache-2.0 | 698 | 0.018625 | ############################
## replaceLinesFull.py
############################
"""
Script for replacing special escape characters in the original yelp academic dataset files.
Special characters such as \n cause problems for | the JSON to CSV conversions.
If you want t | o include review text in the edge file, use this script to replace
special characters such as \n in the JSON review file. This script is much faster
than doing the replacement in R.
"""
with open("yelp_academic_dataset_review.json", "rt") as fin:
with open("reviewFullOut.json", "wt") as fout:
for line in fin:
... |
lepture/terminal | terminal/prompt.py | Python | bsd-3-clause | 3,060 | 0.000327 | # -*- coding: utf-8 -*-
"""
terminal.prompt
~~~~~~~~~~~~~~~
Prompt support on terminal.
:copyright: (c) 2013 by Hsiaoming Yang.
"""
import getpass
import sys
# Python 3
if sys.version_info[0] == 3:
string_type = str
else:
string_type = (unicode, str)
def pro | mpt(name, default=None):
"""
Grab user input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') a | nd ' ' or ': '
while True:
try:
rv = raw_input(prompt)
except NameError:
rv = input(prompt)
if rv:
return rv
if default is not None:
return default
def password(name, default=None):
"""
Grabs hidden (password) input from comma... |
webrecorder/webrecorder | webrecorder/auto_tests/runauto.py | Python | apache-2.0 | 4,145 | 0.003619 | import requests
import pytest
import subprocess
# ============================================================================
class TestAuto(object):
PREFIX = 'http://localhost:8089'
USER = 'testauto'
LIST_ID = ''
AUTO_ID = ''
NUM_BROWSERS = 2
@classmethod
def setup_class(cls):
c... | , **kwargs)
@classmethod
def delete(self, url, **kwargs):
full_url = self.PREFIX + url
return self.session.delete(fu | ll_url, **kwargs)
@pytest.mark.always
def test_create_user(self):
res = subprocess.run(['docker', 'exec', 'webrecorder_app_1', "python", "-m", "webrecorder.admin",
"-c", "testauto@example.com", "testauto", "TestTest123", "archivist", "Auto Test"],
... |
opcon/plutokore | setup.py | Python | mit | 588 | 0.003401 | from setuptools import setup, find_packages
setup(
name='plutokore',
packages=find_packages(),
version='0.10',
description='Python tool for analysing PLUTO simulation data',
author='Patrick Yates',
author_email='patrick.yates@utas.edu.au',
url='https://github.com/pmyates/plutokore',
ke... | yaml', 'scipy', 'contextlib2', 'future'],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'pytest-datafiles'],
| )
|
xtompok/uvod-do-prg | cv10/cv10.py | Python | mit | 886 | 0.01812 |
class Zvire(object):
def __init__(self,jmeno = "",druh = "",hmotnost =0):
self._jmeno = jmeno
self._druh = druh
self._hmotnost = hmotnost
@property
def jmeno(self):
return self._jmeno
@jmeno.setter
def jmeno(self,ajmeno):
s | elf._jmeno = ajmeno
@property
def druh(self):
return self._druh
@druh.setter
def druh(self,adruh):
| self._druh = adruh
@property
def hmotnost(self):
return self._hmotnost
@hmotnost.setter
def hmotnost(self,ahm):
self._hmotnost = ahm
def __str__(self):
return "Zvire {} druhu {} a hmotnosti {} kg".format(
self.jmeno,self.druh,self.hmotnost
)
k = ... |
udaykrishna/unCap | checks.py | Python | mit | 1,028 | 0.019455 | import socket as sk
from kivy.logger import Logger
def getWebsit | e():
return "www.google.com"
def getIpPort():
sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP)
return sock_info[0][-1]
def checkInternet():
sock=sk.socket()
sock.settimeout(1)
try:
sock.connect(getIpPort())
sock.send(b'GET /HTTP/1.0\r\n\r\n')
resp=sock.rec... | if(resp==b'HTTP/1.0'):
return True
else:
return False
except Exception as e:
Logger.error(e)
return False
def checkSpeed():
import psutil
import time
init=[psutil.net_io_counters().bytes_sent,psutil.net_io_counters().bytes_recv]
time.sleep(1)
fin... |
jessekl/flixr | fbone/modules/user/commands.py | Python | mit | 1,438 | 0.000695 | # -*- coding: utf-8 -*-
"""
fbone.modules.user
~~~~~~~~~~~~~~~~~~~~~~~~
user management commands
"""
from flask.ext.script import Command, prompt, prompt_pass
from werkzeug.datastructures import MultiDict
from .models import User
class CreateUserCommand(Command):
"""Create a user"""
"""!!!broke... | email = prompt('Email')
user = User.first(email=email)
if no | t user:
print 'Invalid user'
return
User.delete(user)
print 'User deleted successfully'
class ListUsersCommand(Command):
"""List all users"""
def run(self):
for u in User.all():
print 'User(id=%s email=%s)' % (u.id, u.email)
|
MagicSolutions/django-form-designer | form_designer/migrations/0010_auto__chg_field_formdefinitionfield_help_text.py | Python | bsd-3-clause | 10,400 | 0.008173 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'FormDefinitionField.help_text'
db.alter_column('form_d... | gner.fields.TemplateCharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'mail_subject': ('form_designer.fields.TemplateCharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'mail_to': ('form_de | signer.fields.TemplateCharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'mail_uploaded_files': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'message_template': ('form_designer.fields.TemplateTextField', [], {'null': 'True', 'blank': 'True'}),
... |
salv-orlando/MyRepo | nova/tests/test_vsa.py | Python | apache-2.0 | 7,062 | 0.000142 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | sa_api.update(self.context, vsa_ref['id'], **param)
self.assertEqual(vsa_ref['vc_count'], FLAGS.max_vcs_in_vsa)
param = {'vc_count': 2}
vsa_ref = self.vsa_api.update(self.context, vsa_ref['id'], **param)
self.assertEqual(vsa_ref['vc_count'], 2)
self.vsa_api.delete(self.context,... | est_vsa_generate_user_data(self):
FLAGS.vsa_multi_vol_creation = False
param = {'display_name': 'VSA name test',
'display_description': 'VSA desc test',
'vc_count': 2,
'storage': [{'drive_name': 'SATA_500_7200',
'num_drive... |
PawelPamula/who-are-you | webfest/extensions/cache/__init__.py | Python | mit | 178 | 0 | """Init Extension."""
from flask_cache import Cache
cache = Cache()
def setup_app(app):
"""Ini | t the extension with app context."""
cache.init_app(app)
| return app
|
teonlamont/mne-python | mne/gui/_kit2fiff_gui.py | Python | bsd-3-clause | 28,774 | 0 | """Mayavi/traits GUI for converting data from KIT systems."""
# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#
# License: BSD (3-clause)
from collections import Counter
import os
import sys
from warnings import warn
import numpy as np
from scipy.linalg import inv
from threading import Thread
from ..exter... | = apply_trans(self. | polhemus_neuromag_trans, pts)
return pts
@cached_property
def _get_fid_fname(self):
if self.fid_file:
return os.path.basename(self.fid_file)
else:
return '-'
@cached_property
def _get_head_dev_trans(self):
return inv(self.dev_head_trans)
@ca... |
mrambausek/PPFem | ppfem/__init__.py | Python | gpl-3.0 | 1,648 | 0.00182 | # PPFem: An educational finite element code
# Copyright (C) 2015 Matthias Rambausek
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | , FunctionEvaluator
from ppfem.fem.function_space | import FunctionSpace
from ppfem.fem.partial_differential_equation import PDE
__all__ = ["Mesh", "Point", "Line", "Vertex", "Face", "Cell", "Mapping", "FunctionSpace", "Functional",
"LinearForm", "BilinearForm", "FormCollection", "DefaultSystemAssembler", "FEFunction", "FunctionEvaluator",
"PDE"]... |
dbtsai/spark | dev/create-release/translate-contributors.py | Python | apache-2.0 | 12,628 | 0.003088 | #!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Li... | file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required | by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script transl... |
dudanogueira/microerp | microerp/solicitacao/models.py | Python | lgpl-3.0 | 6,439 | 0.006412 | # -*- coding: utf-8 -*-
"""This file is part of the microerp project.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
... | ettings
from django.db import models
from django.core.exceptions import ValidationError
SOLICITACAO_STATUS_CHOICES = (
('aberta', u'Solicitação Aberta'),
('analise', u'Solicitação em Análise'),
('contato', u'Solicitação em Contato'),
('visto', u'Solicitação em Visto'),
('resol | vida', u'Solicitação Resolvida'),
('naoresolvido', u'Solicitação Não Resolvida'),
)
SOLICITACAO_PRIORIDADE_CHOICES = (
(0, u'Baixa Prioridade'),
(5, u'Média Prioridade'),
(10, u'Alta Prioridade'),
)
class Solicitacao(models.Model):
def __unicode__(self):
return u"Solicitação ID#%d sta... |
DemocracyClub/UK-Polling-Stations | polling_stations/apps/data_importers/tests/stubs/stub_addressimport.py | Python | bsd-3-clause | 1,144 | 0.001748 | import os
from django.contrib.gis.geos import Point
from data_importers.management.commands import BaseCsvStationsCsvAddressesImporter
"""
Define a stub implementation of address importer we can run tests against
"""
class Command(BaseCsvStationsCsvAddressesImporter):
srid = 4326
council_id = "ABC"
addr... | "../fixtures/csv_importer"
)
def address_record_to_dict(self, record):
return {
"council": self.council,
"uprn": record.uprn,
"address": record.address,
"postcode": record.postcode,
"polling_station_id": record.polling_station,
}
... | rd_to_dict(self, record):
location = Point(float(record.lng), float(record.lat), srid=self.get_srid())
return {
"council": self.council,
"internal_council_id": record.internal_council_id,
"postcode": record.postcode,
"address": record.address,
... |
ACS-Community/ACS | LGPL/CommonSoftware/nctest/ws/test/pyStructureEventTest.py | Python | lgpl-2.1 | 1,355 | 0.030996 | #!/usr/bin/env python
from Acspy.Nc.CommonNC import CommonNC
from Acspy.Nc.Supplier import Supplier
import datacapEx
from datacapEx | import ExecBlockProcessedEvent, DataCapturerId, ExecBlockStartedEvent, ScanStartedEvent
import asdmEX
s = Supplier('pyTest-NC')
name = 'DATACAP1'
s.publishEvent(name)
sessionId = asdmEX.IDLEntityRef('SessionId','X1','SID','1.0')
sb = asdmEX.IDLEntityRef('SB1','X1','SB1','1.0')
dcId = DataCapturerId (name, 'a | rrayId', sessionId, sb)
execBlockId = asdmEX.IDLEntityRef('ExecBlockId','X1','SB1','1.0')
d = ExecBlockProcessedEvent( dcId, 'statu', execBlockId, 0)
s.publishEvent(d)
execId = asdmEX.IDLEntityRef('4','3','2', '1')
execBlockId = asdmEX.IDLEntityRef('1','2','3','4')
sse = ScanStartedEvent(execId, "something", 4, [data... |
vgrem/Office365-REST-Python-Client | office365/directory/licenses/service_plan_info.py | Python | mit | 1,595 | 0.004389 | from office365.runtime.client_value import ClientValue
class ServicePlanInfo(ClientValue):
"""Contains information about a service plan associated with a subscribed SKU. The servicePlans property of
the subscribedSku entity is a collection of servicePlanInfo."""
def __init__(self, _id=None, name=None, pr... | (for example, Intune_O365 service plan)
"PendingProvisioning" - Microsoft has added a new service to the product SKU and it has not been
activated in the tenant, yet.
:param str name: The name of the service plan.
:param str _id: The unique identifier of the servi... | tus = provisioning_status
self.appliesTo = applies_to
|
vlvkobal/netdata | collectors/python.d.plugin/python_modules/urllib3/packages/ssl_match_hostname/__init__.py | Python | gpl-3.0 | 719 | 0.001391 | # SPDX-License-Identifier: MIT
import sys
try:
# Our match_hostname function is the same as 3.5's, so we only want to
# import the match_hostname function if it's at least that good.
if sys.version_info < (3, 5):
raise ImportError("Fallback to vendored code")
from ssl import CertificateError, ... | CertificateError, match_hostname
# Not needed, but documenting what we provide.
__all__ = ('CertificateError', 'match_hostn | ame')
|
dcherian/pyroms | pyroms_toolbox/pyroms_toolbox/BGrid_GFDL/get_nc_BGrid_GFDL.py | Python | bsd-3-clause | 1,731 | 0.009821 | import numpy as np
import pyroms
from pyroms_toolbox.BGrid_GFDL import BGrid_GFDL
def get_nc_BGrid_GFDL(grdfile, name='GFDL_CM2.1_North_Pacific', \
# xrange=(80,189), yrange=(96,198)):
xrange=(60,175), yrange=(120, 190)):
"""
Bgrd = get_nc_BGrid_GFDL(gr... | except:
mask_t[:, j,i] = 0
# compute mask at uv-point
M_uv, L_uv = km | u.shape
N_uv = z_uv.shape[0]
mask_uv = np.zeros((N_uv, M_uv, L_uv))
for j in range(M_uv):
for i in range(L_uv):
try:
mask_uv[0:kmu[j,i], j,i] = 1
except:
mask_uv[:, j,i] = 0
return BGrid_GFDL(lon_t, lat_t, lon_uv, lat_uv, \
... |
meco-group/omg-tools | examples/p2p_3dquadrotor.py | Python | lgpl-3.0 | 2,057 | 0.000972 | # This file is part of OMG-tools.
#
# OMG-tools -- Optimal Motion Generation-tools
# Copyright (C) 2016 Ruben Van Parys & Tim Mercy, KU Leuven.
# All rights reserved.
#
# OMG-tools 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... | = Obstacle({'position': [-2, 0, -2]}, shape=Plate(Rectangle(5., 8.), 0.1,
orientation=[0., np.pi/2, 0.]), options={'draw': True})
obst2 = Obstacle({'position': [2, 0, 3.5]}, shape=Plate(Rectangle(5., 8.), 0 | .1,
orientation=[0., np.pi/2, 0.]),
simulation={'trajectories': trajectory}, options={'draw': True})
environment.add_obstacle([obst1, obst2])
# create a point-to-point problem
problem = Point2point(vehicle, environment, freeT=False, options={'horizon_time': 5.})
problem.init()
vehic... |
ChrisHirsch/robotframework | atest/testdata/keywords/DupeKeywords.py | Python | apache-2.0 | 372 | 0.016129 | from robot.api.deco import keyword
def defined_twice():
1/0
@keyword('Defined twice')
def this_time_using_custom_name():
| 2/0
def defined_thrice():
1/0
def definedThrice():
2/0
def Defined_Thrice():
3/0
@keyword('Embedded ${arguments} twice')
def embedded1(arg):
1/0
@keyword('Embedded ${arguments match} TWICE')
def embedded2(arg):
| 2/0
|
summanlp/gensim | gensim/scripts/glove2word2vec.py | Python | lgpl-2.1 | 2,742 | 0.002918 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Radim Rehurek <radimrehurek@seznam.cz>
# Copyright (C) 2016 Manas Ranjan Kar <manasrkar91@gmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
USAGE:
$ python -m gensim.scripts.glove2word2vec --input <GloVe ve... | art_open(word2vec_output_file, 'wb') as fout:
fout.write("{0} {1}\n".format | (num_lines, num_dims).encode('utf-8'))
with smart_open(glove_input_file, 'rb') as fin:
for line in fin:
fout.write(line)
return num_lines, num_dims
if __name__ == "__main__":
logging.basicConfig(format='%(asctime)s : %(threadName)s : %(levelname)s : %(message)s', level=logg... |
keurfonluu/StochOPy | stochopy/optimize/pso/_pso.py | Python | mit | 5,326 | 0.003192 | from .. import cpso
from .._helpers import register
__all__ = [
"minimize",
]
def minimize(
fun,
bounds,
x0=None,
args=(),
maxiter=100,
popsize=10,
inertia=0.7298,
cognitivity=1.49618,
sociability=1.49618,
seed=None,
xtol=1.0e-8,
ftol=1.0e-8,
constraints=None,
... |
The maximum number of generations over which the entire population is evolved.
popsize : int, optional, default 10
Total population size.
inertia : scalar, optional, default 0.7298
Inertial weight, denoted by w in the literature. It should be in the range [0, 1].
cognitivity : scala... | y: scalar, optional, default 1.49618
Sociability parameter, denoted by c2 in the literature. It should be in the range [0, 4].
seed : int or None, optional, default None
Seed for random number generator.
xtol : scalar, optional, default 1.0e-8
Solution tolerance for termination.
ftol... |
brosander/kettle-vertx-webapp | src/util/copyData.py | Python | apache-2.0 | 1,824 | 0.014254 | #!/usr/bin/python
import urllib2, base64
import shutil
import json
import json
import argparse
import os
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''
This script will copy the step/jobentry images from a running carte (with kthin-server) to the img folder
''', formatter_class = arg... | args.destination + '/' + entryPath, 'wb | ') as f:
f.write(data)
with open(args.destination + listFile, 'w') as f:
f.write(json.dumps(categories))
getListAndImages('kettle/kthin/stepList/', '/kettle/kthin/stepList', 'steps')
getListAndImages('kettle/kthin/jobEntryList/', '/kettle/kthin/jobEntryList', 'jobEntries')
|
LJMNilsson/memtran | src/tokens.py | Python | gpl-3.0 | 12,189 | 0.008696 | # Copyright (C) 2017 Martin Nilsson
# This file is part of the Memtran compiler.
#
# The Memtran compiler 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
# ... | .kind == Tok.RCURLYBRACKET:
print("}", end='')
elif self.kind == Tok.LSQUAREBRACKET:
print("[", end='')
elif self.kind == Tok.RSQUAREBRACKET:
print("]", end='')
elif self.kind == Tok.LPAREN:
print("(", end='')
elif self.kind == Tok.RPAREN:
... | k.COLON:
print(":", end='')
elif self.kind == Tok.SEMICOLON:
print(";", end='')
elif self.kind == Tok.PERIOD:
print(".", end='')
elif self.kind == Tok.COMMA:
print(",", end='')
elif self.kind == Tok.STRING:
print("\"" + self.t... |
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite | release_results/script/experiments_base.py | Python | lgpl-3.0 | 5,733 | 0.017966 | #!/usr/bin/python
#
# Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite
# contributors
#
# This file is part of EvoSuite.
#
# EvoSuite is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Public License as published by the
# Free Software Foundation, either vers... | os.path.abspath(sys.argv[1])
if not os.path.isdir(BASEDIR):
print "creating folder: " + BASEDIR
os.makedirs(BASEDIR)
else:
print "target folder already exists"
exit(1)
# Where to put stuff (default in subdirs of BASEDIR)
REPORTS="%s/reports" % BASEDIR
SCRIPTDIR="%s/scripts" % BASEDIR
LOGDIR="%s/logs"... | D = int(sys.argv[3])
MAX_JOBS = int(sys.argv[5])
# Initialize DB of target classes
CLASSES_FILE=sys.argv[4]
if not os.path.isfile(CLASSES_FILE):
print 'Could not find class file ' + sys.argv[4]
exit(1)
CLASSES = []
f = open(CLASSES_FILE)
for line in f:
entry = line.rstrip().split()
CLASSES.append(entry)
f.... |
goozbach/ansible | lib/ansible/inventory/expand_hosts.py | Python | gpl-3.0 | 4,357 | 0.00459 | # (c) 2012, Zettar Inc.
# Written by Chin Fang <fangchin@zettar.com>
#
# This | file is part of Ansible
#
# This module 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.
#
# This software is distributed in the hope t... | RCHANTABILITY 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 this software. If not, see <http://www.gnu.org/licenses/>.
#
'''
This module is for enhancing ansible's inventory parsing capabi... |
VitalPet/addons-onestein | hr_employee_display_own_info/tests/__init__.py | Python | agpl-3.0 | 192 | 0 | # -*- coding: | utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# Licen | se AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import test_employee_display_own_info
|
ooici/marine-integrations | mi/dataset/driver/ctdpf_ckl/mmp_cds/driver.py | Python | bsd-2-clause | 2,429 | 0.003705 | """
@package mi.dataset.driver.ctdpf_ckl.mmp_cds.driver
@file marine-integrations/mi/dataset/driver/ctdpf_ckl/mmp_cds/driver.py
@author Mark Worden
@brief Driver for the CtdpfCklMmpCds
Release notes:
initial release
"""
__author__ = 'Mark Worden'
__license__ = 'Apache 2.0'
from mi.core.log import get_logger
log = g... | exception_callback)
self._parser = None
@classmethod
def stream_config(cls):
return [CtdpfCklMmpCdsParserDataParticle.type()]
def _build_parser(self, parser_state, infile):
"""
Build and return the parser
"""
config = self._p... | DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.ctdpf_ckl_mmp_cds',
DataSetDriverConfigKeys.PARTICLE_CLASS: 'CtdpfCklMmpCdsParserDataParticle'
})
log.debug("My Config: %s", config)
self._parser = CtdpfCklMmpCdsParser(
config,
parser_state,
... |
SUSE/azure-sdk-for-python | azure-mgmt/tests/test_graphrbac.py | Python | mit | 1,961 | 0.002552 | # 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.
#---------------------------------------------------------------------... | )
user = self.graphrbac_client.users.get(user.object_id)
self.assertEqual(user.display_name, 'Test Buddy')
users = self.graphrbac_client.users.list(
filter="displayName eq 'Test Buddy'"
)
users = list(users)
self.assertEqual(len(users), 1)
self.asser... | qual(users[0].display_name, 'Test Buddy')
self.graphrbac_client.users.delete(user.object_id)
#------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
|
sileht/deb-openstack-nova | nova/db/sqlalchemy/migrate_repo/versions/026_add_agent_table.py | Python | apache-2.0 | 3,336 | 0.003897 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ,
assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('version',
String(length=255, convert_unic | ode=False,
assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('url',
String(length=255, convert_unicode=False,
assert_unicode=None,
unicode_error=None, _warn_o... |
alaudet/hcsr04sensor | hcsr04sensor/sensor.py | Python | mit | 8,573 | 0.001166 | """Measure the distance or depth with an HCSR04 Ultrasonic sound
sensor and a Raspberry Pi. Imperial and Metric measurements are available"""
# Al Audet
# MIT License
from __future__ import division
import time
import math
import warnings
import RPi.GPIO as GPIO
class Measurement(object):
"""Create a measurem... | GPIO.cleanup((self.trig_pin, self.echo_pin))
return sorted_sample[sample_size // 2]
def depth(self, median_reading, hole_depth):
"""Calculate the depth of a liquid. hole_depth is the
distance from the sensor to the bottom of the hole."""
if self.unit == "metric":
ret... | - median_reading
else:
return hole_depth - (median_reading * 0.394)
def distance(self, median_reading):
"""Calculate the distance from the sensor to an object."""
if self.unit == "imperial":
return median_reading * 0.394
else:
# don't need this m... |
nmatsui/wasted_energy_of_tv_iot | power_ir_send_server.py | Python | mit | 939 | 0.001065 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import SocketServer
from lib import const
class PowerIRSendHandler(SocketServer.StreamR | equestHandler):
def handle(self):
# print "connected from:", self.client_address
sent_data = ""
while True:
data = self.request.recv(1024)
if len(data) == 0:
break
sent_data += data
if sent_data == const.IR_SEND_MSG:
s... | server = SocketServer.ThreadingTCPServer(address, PowerIRSendHandler)
print "power_ir_send_server listening", server.socket.getsockname()
server.serve_forever()
except KeyboardInterrupt as err:
server.socket.close()
print "power_ir_send_server stop"
|
enthought/etsproxy | enthought/plugins/refresh_code/refresh_code_plugin.py | Python | bsd-3-clause | 118 | 0 | # pr | oxy module
from __future__ import absolute_import
from envisage.plugins.refresh_code.refresh_ | code_plugin import *
|
tamland/python-actors | actors/internal/messages.py | Python | apache-2.0 | 995 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2015 Thomas Amland
#
# Licensed under the Apache Lice | nse, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "... | See the License for the specific language governing permissions and
# limitations under the License.
from collections import namedtuple
Start = object()
Restart = object()
Resume = object()
Terminate = object()
Restart = "restart"
Terminate = "terminate"
Failure = namedtuple('Failure', ['ref', 'exception', 'traceb... |
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/aiohttp/log.py | Python | apache-2.0 | 326 | 0 | import logging
access_logger = logging.getLogger('aiohttp.access')
client_logger = logging.getLog | ger('aiohttp.client')
internal_logger = logging.getLogger('aiohttp.internal')
server_logger = logging.getLogger('aiohttp.server')
web_logger = logging.getLogger('aioht | tp.web')
ws_logger = logging.getLogger('aiohttp.websocket')
|
hoho/dosido | nodejs/tools/gyp/gyptest.py | Python | mit | 8,032 | 0.015065 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__doc__ = """
gyptest.py -- test runner for GYP tests.
"""
import os
import optparse
import shlex
import subprocess
import sys
class Comma... | = subprocess.PIPE
if stderr is sys.stderr:
# Same as passing sys.stderr, except python2.4 doesn't fail on it.
suberr = None
elif stderr is None:
# Merge with stdout if stderr isn't specified.
suberr = subprocess.STDOUT
else:
# Open pipe for anything else so Pop... | 'win32'),
stdout=subout,
stderr=suberr)
p.wait()
if stdout is None:
self.stdout = p.stdout.read()
elif stdout is not sys.stdout:
stdout.write(p.stdout.read())
if stderr not in (None, sys.stderr):
stderr.write(p.stderr.... |
chriszs/redash | redash/models/types.py | Python | bsd-2-clause | 3,048 | 0.000656 | import pytz
from sqlalchemy.types import TypeDecorator
from sqlalchemy.ext.indexable import index_property
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy_utils import EncryptedType
from redash.utils import json_dumps, json_loads
from redash.utils.configuration import ConfigurationContai | ner
from .base import db
class Configuration(TypeDecorator):
impl = db.Text
def process_bind_param(self, value, dialect):
return value.to_json()
def process_result_value(self, value, dialect):
retu | rn ConfigurationContainer.from_json(value)
class EncryptedConfiguration(EncryptedType):
def process_bind_param(self, value, dialect):
return super(EncryptedConfiguration, self).process_bind_param(value.to_json(), dialect)
def process_result_value(self, value, dialect):
return ConfigurationCon... |
lsp84ch83/PyText | UItestframework/run.py | Python | gpl-3.0 | 730 | 0.011204 | #coding=utf-8
import unittest
import HTMLTestRunner
import time
from config import globalparam
from public.common import sendmail
def run():
test_dir = './testcase'
| suite = unittest.defaultTestLoader.discover(start_dir=test_dir,pattern='test*.py')
now = time.strftime('%Y-%m-%d_%H_%M_%S')
reportname = globalparam.report_path + '\\' + 'TestResult' + now + '.html'
with open(reportname,'wb') as f:
| runner = HTMLTestRunner.HTMLTestRunner(
stream=f,
title='测试报告',
description='Test the import testcase'
)
runner.run(suite)
time.sleep(3)
# 发送邮件
mail = sendmail.SendMail()
mail.send()
if __name__=='__main__':
run() |
dougbenjamin/panda-harvester | pandaharvester/harvestermessenger/shared_file_messenger.py | Python | apache-2.0 | 35,562 | 0.002362 | import json
import os
import shutil
import datetime
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
try:
from os import scandir, walk
except ImportError:
from scandir import s... | ntStatusDumpXmlFile
# json for job request
jsonJobRequestFileName = harvester_config.payload_interaction.jobRequestFile
# json for job spec
jobSpecFileName = harvester_config.payload_interaction.jobSpecFile
# json for event request
jsonEventsRequestFileName = harvester_config.payload_interaction.eventRequestFile
# ... | ventsFeedFileName = harvester_config.payload_interaction.eventRangesFile
# json to update events
jsonEventsUpdateFileName = harvester_config.payload_interaction.updateEventsFile
# PFC for input files
xmlPoolCatalogFileName = harvester_config.payload_interaction.xmlPoolCatalogFile
# json to get PandaIDs
pandaIDsFile ... |
pivonroll/Qt_Creator | scripts/dependencyinfo.py | Python | gpl-3.0 | 8,279 | 0.002416 | #! /usr/bin/env python2
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in... | e, self.symbolDependencies[i])
def _parsePluginSpec(self, spec):
dirname = os.path.dirname(spec)
with open(spec) as f:
content = f.readlines()
for line in content:
| m = re.search('(plugin|dependency)\s+name="([^"]+)"(?:.*\stype="([^"]+)")?', line)
if not(m):
continue
if m.group(1) == 'plugin':
if self.name != '':
log.critical('Plugin name already set to "%s"!', self.name)
else:
... |
johnparker007/mame | 3rdparty/bgfx/3rdparty/spirv-cross/test_shaders.py | Python | gpl-2.0 | 29,937 | 0.008852 | #!/usr/bin/env python3
import sys
import os
import os.path
import subprocess
import tempfile
import re
import itertools
import hashlib
import shutil
import argparse
import codecs
import json
import multiprocessing
import errno
from functools import partial
class Paths():
def __init__(self, spirv_cross, glslang, s... | :
f, path = tempfile.mkstemp(suffix = suff)
os.close(f)
#print('Creating temporary:', path)
return path
def parse_stats(stats):
m = re.search('([0-9]+) work registers', stats)
registers = int(m.group(1)) if m else 0
m = re.search('([0-9]+) uniform registers', stats)
uniform_regs = int(... | _short = float(m_list[1][0]) if m_list else 0
ls_short = float(m_list[1][1]) if m_list else 0
tex_short = float(m_list[1][2]) if m_list else 0
alu_long = float(m_list[2][0]) if m_list else 0
ls_long = float(m_list[2][1]) if m_list else 0
tex_long = float(m_list[2][2]) if m_list else 0
return (r... |
mpetyx/pyrif | 3rdPartyLibraries/FuXi-master/test/OWLsuite.py | Python | mit | 20,462 | 0.002883 | import unittest
import os
import time
# import itertools
from pprint import (
pprint,
pformat
)
from FuXi.DLP import non_DHL_OWL_Semantics # , MapDLPtoNetwork
from FuXi.DLP.ConditionalAxioms import AdditionalRules
from FuXi.Horn.HornRules import HornFromN3
from FuXi.Horn.PositiveConditions import BuildUnit... | yntax-ns#',
'owl': OWL_NS,
'rdfs': RDFS,
}
nsMap = {
u'rdfs': RDFS,
u'rdf': RDF,
u'rete': RETE_NS,
u'owl': OWL_NS,
u'': TEST_NS,
u'otest': OWL_TEST,
u'rtest': RDF_TEST,
u'foaf': URIRef("http://xmlns.com/foaf/0.1/"),
u'math': URIRef("http://www.w3.org/2000/10/swap/math#"),
}
MANIFEST_QUERY = ... | tailmentTest;
otest:feature ?feature;
rtest:description ?descr;
rtest:status ?status;
rtest:premiseDocument ?premise;
rtest:conclusionDocument ?conclusion
]
}"""
PARSED_MANIFEST_QUERY = parse(MANIFEST_QUERY)
Features2Skip = [
URIRef('http://www.w3.org/2002/07/owl#sameClassAs'),
]
NonNaiveSki... |
xuleiboy1234/autoTitle | tensorflow/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler_test.py | Python | mit | 44,613 | 0.005828 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma | y obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License fo... | ermissions and
# limitations under the License.
# ==============================================================================
"""Test for checking stats accumulator related ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.b... |
molobrakos/home-assistant | homeassistant/components/cloud/const.py | Python | apache-2.0 | 1,006 | 0 | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'al... | TION_INFO_URL = 'subscription_info_url'
CONF_CLOUDHOOK_CREATE_URL = 'cloudhook_create_url'
CONF_REMOTE_API_URL = 'remote_api_url'
CONF_ACME_DIRECTORY_SERVER = 'acme_directory_server'
MODE_DEV = "development"
MODE_PROD = "production"
DISPATCHER_REMOTE_UPDATE = 'cloud_remote_update'
cla | ss InvalidTrustedNetworks(Exception):
"""Raised when invalid trusted networks config."""
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractTheevilduketranslationsBlogspotCom.py | Python | bsd-3-clause | 584 | 0.032534 |
def extractTheevilduketranslationsBlogspotCom(i | tem):
'''
Parser for 'theevilduketranslations.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', ... | me, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
terabyte/Jira-Commit-Acceptance-Plugin | src/main/resources/client/python/cvs/jira-client.py | Python | bsd-3-clause | 1,566 | 0.01341 | #!/usr/bin/python
# JIRA commit acceptance python client for CVS
# Author: istvan.vamosi@midori.hu
# $Id$
import sys
import urlparse
import xmlrpclib
# configure JIRA access
# ("projectKey" can contain multiple comma-separated JIRA project keys like "projectKey = 'TST,ARP'".
# If you specify multiple key... | ommitter passed as arg[1]
committer = sys.argv[1]
# slurp | log message from log message file passed as arg[2]
try:
f = open(sys.argv[2])
commitMessage = f.read()
f.close()
commitMessage = commitMessage.rstrip('\n\r')
except:
print 'Unable to open ' + sys.argv[2] + '.'
sys.exit(1)
# print arguments
print 'Committer: ' + committer
print 'Commit message: "' + c... |
rousseab/pymatgen | pymatgen/analysis/molecule_matcher.py | Python | mit | 24,855 | 0.000483 | # coding: utf-8
from __future__ import unicode_literals
"""
This module provides classes to perform fitting of molecule with arbitrary
atom orders.
This module is supposed to perform exact comparisons without the atom order
correspondence prerequisite, while molecule_structure_comparator is supposed
to do rough compa... | ob.OBConversion()
obconv.SetOutFormat(str("inchi"))
obconv.AddOption(str("a"), ob.OBConversion.OUTOPTIONS)
obconv.AddOption(str("X"), ob.OBConversion.OUTOPTIONS, str("DoNotAddH"))
inchi_text = obconv.WriteString(mol)
match = re.search("InChI=(?P<inchi>.+)\nAuxInfo=.+"
... | "/N:(?P<labels>[0-9,;]+)/(E:(?P<eq_atoms>[0-9,"
";\(\)]*)/)?", inchi_text)
inchi = match.group("inchi")
label_text = match.group("labels")
eq_atom_text = match.group("eq_atoms")
heavy_atom_labels = tuple([int(i) for i in label_text.replace(
'... |
pjryan126/solid-start-careers | store/api/zillow/venv/lib/python2.7/site-packages/pandas/tests/test_base.py | Python | gpl-2.0 | 38,533 | 0.000052 | # -*- coding: utf-8 -*-
from __future__ import print_function
import re
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import pandas.compat as compat
import pandas.core.common as com
import pandas.util.testing as tm
from pandas import (Series, Index, DatetimeIndex, Timedel... | rty(_get_foo, _set_foo, doc="foo property")
def bar(self, *args, **kwargs):
""" a test bar method """
| pass
class Delegate(PandasDelegate):
def __init__(self, obj):
self.obj = obj
Delegate._add_delegate_accessors(delegate=Delegator,
accessors=Delegator._properties,
typ='property')
Del... |
acehanks/projects | tripadvisor_scrapy/tripad/items.py | Python | mit | 285 | 0 | # -*- coding: utf-8 -*-
# Define here the mo | dels for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TripadItem(scrapy.Item):
# | define the fields for your item here like:
# name = scrapy.Field()
pass
|
Cito/sqlalchemy | test/orm/test_versioning.py | Python | mit | 27,671 | 0.003795 | import datetime
import sqlalchemy as sa
from sqlalchemy.testing import engines
from sqlalchemy import testing
from sqlalchemy import Integer, String, Date, ForeignKey, literal_column, \
orm, exc, select, TypeDecorator
from sqlalchemy.testing.schema import Table, Column
from sqlalchemy.orm import mapper, relationshi... | ersion id '\d+'",
s1.query(Foo).with_lockmode('read').get, f1s1.id
)
# reload it - this expires the old version first
s1.refresh(f1s1, lockmode='read')
# now assert version OK
s1.query(Foo).with_lockmo | de('read').get(f1s1.id)
# assert brand new load is OK too
s1.close()
s1.query(Foo).with_lockmode('read').get(f1s1.id)
@testing.emits_warning(r'.*does not support updated rowcount')
@engines.close_open_connections
@testing.requires.update_nowait
def test_versioncheck_for_update... |
DataViva/dataviva-api | app/models/cnes_professional.py | Python | mit | 2,123 | 0.000471 | from sqlalchemy import Column, Integer, String, func, Boolean
from app import db
class CnesProfessional(db.Model):
__tablename__ = 'cnes_professional'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
microregion ... | _professional',
'health_region',
'hierarchy_level',
]
@classmethod
def aggregate(cls, value):
return {
'professionals': func.count(),
'other_hours_worked': func.sum(cls.other_hours_worked),
'hospital_hour': func.sum(cls.hospital_hour),... | urs_worked', 'hospital_hour', 'ambulatory_hour']
|
doctori/PythonTDD | functional_tests/base.py | Python | gpl-2.0 | 1,832 | 0.027293 | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import sys
from .server_tools import reset_database
class FunctionalTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
for arg in sys.argv:... | eout=30).until( |
lambda b: b.find_element_by_id(element_id),
'Could not find element with id {}. Page text was:\n{}'.format(
element_id, self.browser.find_element_by_tag_name('body').text
)
)
def wait_to_be_logged_in(self, email):
self.wait_for_element_with_id('id_logout')
navbar = self.browser.find_element_by_cs... |
vmahuli/contrail-controller | src/vnsw/opencontrail-vrouter-netns/opencontrail_vrouter_netns/tests/test_vrouter_netns.py | Python | apache-2.0 | 3,842 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014 Cloudwatt
# 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/l... | 'http://localhost:9091/port',
headers={'content-type': 'application/json'},
data=('{"tx-vlan-id": -1, '
'"ip-address": "172.16.0.12", '
'"display-name": null, '
'"id": "%s", '
'"instance-id": "fake_vm_uuid", '
... | '"vm-project-id": "", '
'"type": 1, '
'"mac-address": "00-11-22-33-44-55", '
'"system-name": "tap1234"}') % NIC1_UUID)
def test_add_port_to_agent_fails(self):
self.assertRaises(ValueError,
self._add_port_to_agent,
... |
barnabytprowe/great3-public | inputs/galdata/make_fits_catalogs.py | Python | bsd-3-clause | 15,061 | 0.007503 | # Copyright (c) 2014, the GREAT3 executive committee (http://www.great3challenge.info/?q=contacts)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# 1. Redistributions of source code must retain... | RADIUS',
# 'FLUXERR_AUTO', 'KRON_RADIUS', 'MU_MAX', 'MU_CLASS', 'CLEAN', 'GOOD', 'FLAGS', 'SN',
# 'SN_NON_CORR', 'FWHM_IMAGE', 'ALPHA_J2000', 'DELTA_J2000', 'X_IMAGE', 'Y_IMAGE', 'A_IMAGE',
# 'B_IMAGE', 'THETA_IMAGE', 'PETRO_RADIUS', 'D', 'E1_R', 'E2_R', 'E1_RU', 'E2_RU', 'GAMMA1',
# 'GAMMA2', 'FOCUS_MO... | WEIGHT_FUNCT_RADIUS', 'VAR_E1', 'VAR_E2',
# 'BOX', 'SPECZ', 'SPECZ_MARA', 'SPECZ_CLASS', 'SPECZ_ORIGIN', 'GOOD_SPECZ', 'SPECZ_BL_AGN',
# 'FORS2_OBJECT_FLAG', 'MIPS_Z', 'MIPS_LOG_L', 'MIPS_MASS', 'ZEST_TYPE', 'ZEST_BULGE',
# 'ZEST_IRREGULARITY', 'ZEST_ELONGATION', 'ZEST_GINI', 'ZEST_M20', 'ZEST_CONCENTRATION... |
nicfit/nicfit.py | cookiecutter/{{cookiecutter.project_name}}/{{cookiecutter.py_module}}/__main__.py | Python | mit | 614 | 0.061889 | # -*- coding: utf-8 -*-
{%- if cook | iecutter.pyapp_type == "asyncio | " -%}
{%- set async = "async" -%}
{%- set appmod = "nicfit.aio" -%}
{%- else -%}
{%- set async = "" -%}
{%- set appmod = "nicfit" -%}
{%- endif %}
from {{ appmod }} import Application
from nicfit.console import pout
from . import version
{{ async }} def main(args):
pout("\m/")
app = Application(main, version=ve... |
ai-se/Tree-Learner | CROSSTREES.py | Python | unlicense | 7,714 | 0.012315 | #! /Users/rkrsn/anaconda/bin/python
from __future__ import print_function
from __future__ import division
from os import environ, getcwd
from pdb import set_trace
from random import uniform, randint, shuffle
import sys
# Update PYTHONPATH
HOME = environ['HOME']
axe = HOME + '/git/axe/axe/' # AXE
pystat = HOME + '/git... | h if b[0] == bb[0]])
l.dist = np.sqrt(np.sum(dist))
vals.append(l)
vals = sorted(vals, key=lambda F: F.DoC, reverse=False)
best = [v for v in vals if v.score < alpha * current.score]
if not len(best) > 0:
best = vals
# Get a list of DoCs (DoC -> (D)epth (o)f (C)orrespondence, btw..)
... | est]))) # A list of all DoCs..
for dd in unq:
bests.update(
{dd: sorted([v for v in best if v.DoC == dd], key=lambda F: F.dist)})
attr.update({dd: self.attributes(
sorted([v for v in best if v.DoC == dd], key=lambda F: F.score))})
if pos == 'near':
return attr[unq[-1]][0]... |
rglass/buddha-bum | listman.py | Python | gpl-3.0 | 711 | 0.001406 | # Copyright (c) 2007 Roman Glass
# See LICENSE for details.
"""Play around with different SortingAlgorithms"""
from zope.interface import Interface, implements
from interfaces impor | t IListManager
from baselist import *
from sortingalgorithms import *
from help import *
class ListM:
implements(IListManager)
def __init__(self):
self.n = NullList( | )
self.sort = SelectionSortV
def add(self, o):
self.n = NonNull(o, self.n)
def diff(self, o):
self.n = self.n.accept(DiffV(o))
def parse(self):
return self.n.accept(ParseV())
def sort(self):
self.n = self.n.accept(self.sort())
def changeSort(self, o):
... |
anokata/pythonPetProjects | surgame/src/mapGenerator.py | Python | mit | 1,097 | 0.004558 | import caveGenerate
import yaml
filename = 'data/cavegen.map'
def addObjects():
o = list()
o.append('floor')
o.append('ground')
o.append('apple')
o.append('cherry')
o.append('enemy_poringp')
o.append('enemy_poringb')
return o
def writeMap(fn, m):
data = yaml.dump(m, default_flow_s... | or = caveGenerate.init_matrix(50, cav | eGenerate.FLOOR)
map_str = caveGenerate.drawString(genmap)
map_floor = caveGenerate.drawString(floor)
m['layers_count'] = 2
m['layers'] = list()
m['layers'].append(map_floor)
m['layers'].append(map_str)
m['objects'] = addObjects()
return m
if __name__ == '__main__':
m = genMap()
... |
huaijiefeng/contact-sync-server | contactsync/settings.py | Python | apache-2.0 | 5,270 | 0.00038 | # Django settings for ssssss project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
import os
if 'SERVER_SOFTWARE' in os.environ:
from sae.const import (
MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB
)
else:
# Make `... | Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'e | n-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Dja... |
jonbrohauge/pySudokuSolver | board.py | Python | mit | 1,589 | 0.001259 | class Board(object):
"""This class defines the board"""
def __init__(self, board_size):
"""The initializer for the class"""
self.board_size = board_size
self.board = []
for index in range(0, self.board_size):
self.board.append(['0'] * self.board_size)
def is_on... | x_coordina | te-1)]) != '0')
|
oleg-chubin/let_me_play | let_me_app/migrations/0004_auto_20150713_2126.py | Python | apache-2.0 | 848 | 0.001179 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals |
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('let_me_app', '0003_auto_20150713_2051'),
]
operations = [
migrations.RemoveField(
model_name='site',
name='location',
... | igrations.RemoveField(
model_name='site',
name='location_lat',
),
migrations.RemoveField(
model_name='site',
name='location_lon',
),
migrations.AddField(
model_name='site',
name='geo_point',
field=django.... |
miniconfig/home-assistant | homeassistant/components/android_ip_webcam.py | Python | mit | 9,809 | 0 | """
Support for IP Webcam, an Android app that acts as a full-featured webcam.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/android_ip_webcam/
"""
import asyncio
import logging
from datetime import timedelta
import voluptuous as vol
from homeassista... | tion'): cv.string,
vol.Optional(CONF_SWITCHES, default=None):
vol.All(cv.ensure_list, [vol.In(SWITCHES)]),
vol.Optional(CONF_SENSORS, default=None):
vol.All(cv.ensure_list, [vol.In(SENSORS)]),
vol.Optional(CONF_MOTION_SENSOR, default=None): cv.boolean,
})])
}, extra=v... | coroutine
def async_setup(hass, config):
"""Setup the IP Webcam component."""
from pydroid_ipcam import PyDroidIPCam
webcams = hass.data[DATA_IP_WEBCAM] = {}
websession = async_get_clientsession(hass)
@asyncio.coroutine
def async_setup_ipcamera(cam_config):
"""Setup a ip camera."""
... |
pcejrowski/iwi | notebooks/calcs/rating.py | Python | mit | 2,328 | 0.005155 |
import metrics
def rate(artToCatSim, label, membershipData, categoryTree, artNamesDict, catNamesDict):
# countBefore1 = artToCatSim.count_nonzero()
# for article in membershipData:
# id_an | d_categories = article.split('\t')
# articleId = int(id_and_categories[0])
# del id_and_categories[0]
# cats = [int(x) for x in id_and_categories]
# for cat in cats:
# artToCatSim[articleId, cat] = 0
#
# artToCatSim.eliminate_zeros()
# countAfter1 = artToCatSi... | x.split(), data['po_slowach-articles_dict-simple-20120104'])
# art_labels = dict(map(lambda (x, y): [y, x], raw_art_labels))
#
# raw_cat_labels = map(lambda x: x.split(), data['po_slowach-cats_dict-simple-20120104'])
# cat_labels = dict(map(lambda (x, y): [y, x], raw_cat_labels))
# from sets impor... |
HybridF5/tempest_debug | tempest/tests/test_list_tests.py | Python | apache-2.0 | 1,828 | 0.001641 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | nd(fail_id)
error_message = ("The follow | ing tests have import failures and aren't"
" being run with test filters %s" % import_failures)
self.assertFalse(import_failures, error_message)
|
fedspendingtransparency/data-act-broker-backend | tests/unit/dataactvalidator/test_fabs28_detached_award_financial_assistance_1.py | Python | cc0-1.0 | 2,049 | 0.007321 | from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabs28_detached_award_financial_assistance_1'
def test_column_headers(database):
expected_subset = {'row_number', 'assistance_type', ... | or 08). """
det_award = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=0,
correction_delete_indicatr='')
det_award_2 = DetachedAwardFinancialAssistanceFactory(assistance_type='08', face_value_loan_guarantee=20,
... | t_award_3 = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=None,
correction_delete_indicatr='d')
errors = number_of_errors(_FILE, database, models=[det_award, det_award_2, det_award_3])
assert errors == 0
def t... |
twm/yarrharr | yarrharr/scripts/yarrharr.py | Python | gpl-3.0 | 1,676 | 0.000597 | # -*- coding: utf-8 -*-
# Copyright © 2013, 2014, 2017, 2020 Tom Most <twm@freecog.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | ection 7
#
# If you modify this Program, or any covered work, by linking or
# combining it with OpenSSL (or a modified version of that library),
# containing parts covered by the terms of the OpenSSL License, the
# licensors of this Program grant you additional permission to convey
# the resulting work. Corresponding ... | OpenSSL used as well as that of the covered work.
from __future__ import absolute_import
import argparse
import os
import sys
import yarrharr
def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Yarrharr feed reader")
parser.add_argument("--version", action="version", version=yarrhar... |
systemovich/scrapy-myuniversity | myuniversityscraper/pipelines.py | Python | gpl-3.0 | 273 | 0 | # Define your item pipelines here
#
# Don't forget to add your pipeline to | the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics | /item-pipeline.html
class MyuniversityscraperPipeline(object):
def process_item(self, item, spider):
return item
|
edx/course-discovery | course_discovery/apps/api/v1/tests/test_views/test_level_types.py | Python | agpl-3.0 | 1,985 | 0.002519 | from django.urls import reverse
from course_discovery.apps.api.v1.tests.test_views.mixins import APITestCase, SerializationMixin
from course_discovery.apps.core.tests.factories import USER_PASSWORD, UserFactory
from course_discovery.apps.course_metadata.models import LevelType
from course_discovery.apps.course_metadat... | get(self.list_path)
assert response.status_code == 200
assert response.data['results'] == self.serialize_level_type(expected, many=True)
def t | est_retrieve(self):
""" The request should return details for a single level type. """
level_type = LevelTypeFactory()
level_type.set_current_language('en')
level_type.name_t = level_type.name
level_type.save()
url = reverse('api:v1:level_type-detail', kwargs={'name': lev... |
Surufel/Personal | 2.pysifer/Older/hello_world.py | Python | agpl-3.0 | 189 | 0.010582 | #!/usr/bin/env python3
# Sifer Aseph
"""Prints a "hello world" statement."""
def main():
"""Utterly standard."" | "
print("He | llo cruel world.")
if __name__ == "__main__":
main()
|
s1na/darkoob | darkoob/book/urls.py | Python | mit | 374 | 0.005348 | from django.conf.urls import patterns, include, url
from darkoob.book import views as book_views
urlpatterns = patterns('',
url(r'^(?P<book_id>\d+)/(?P<book_title>[a-zA-Z0-9\- | _]+)/$', book_views.page, name='book_page'),
url(r'^look/$', book_views.book_lookup),
url(r'^author/$', book_views.author_lookup),
# url(r'^rate/$', book_views.rate, name='rate'),
)
| |
collective/ECReviewBox | Extensions/Install.py | Python | gpl-2.0 | 2,470 | 0.00486 | # -*- coding: utf-8 -*-
# $Id$
#
# Copyright (c) 2007 Otto-von-Guericke-Universität Magdeburg
#
# This file is part of ECReviewBox.
from StringIO import StringIO
from Products.Archetypes.Extensions.utils import installTypes, install_subskin
from Products.Archetypes.public import listTypes
from Products.CMFCore.utils... | '%' to %s.\n" % (ECR_TITLE, ECA_WF_NAME))
def install(self):
"""
Installs the product.
"""
out = StringIO()
# install depending products
installDependencies(self, out)
# install types
installTypes(self, out, | listTypes(PRODUCT_NAME), PRODUCT_NAME)
# install subskins
install_subskin(self, out, GLOBALS)
# install workflows
setupWorkflow(self, out)
# install tools
# register tool to Plone's preferences panel
# enable portal_factory for given types
factory_tool = getToolByName(self, 'po... |
rbramwell/pulp | nodes/extensions/admin/pulp_node/extensions/admin/sync_schedules.py | Python | gpl-2.0 | 4,455 | 0.001571 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | mer_content_schedules
def create_schedule(self, schedule, failure_threshold, enabled, kwargs):
node_id = kwargs[NODE_ID_OPTION.keyword]
max_bandwidth = kwargs[MAX_BANDWIDTH_OPTION.keyword]
max_concurrency = kwargs[MAX_CONCURRENCY_OPTION.keyword]
| units = [dict(type_id='node', unit_key=None)]
options = {
constants.MAX_DOWNLOAD_BANDWIDTH_KEYWORD: max_bandwidth,
constants.MAX_DOWNLOAD_CONCURRENCY_KEYWORD: max_concurrency,
}
return self.api.add_schedule(
SYNC_OPERATION,
node_id,
... |
kikimaroca/beamtools | build/lib/beamtools/pulse.py | Python | mit | 9,048 | 0.021994 | '''
Pulse characterization
Created Fri May 12 2017
@author: cpkmanchee
'''
import numpy as np
import os.path
import inspect
from beamtools.constants import h,c,pi
from beamtools.common import normalize, gaussian, sech2, alias_dict
from beamtools.import_data_file import import_data_file as _import
from beamtools.imp... | ted if from_file=True
Units assumed to be nm for wavelength.
If from_file is set True, data should be filename
Optional file_format, default is oceanoptics_spectrometer. Currently
can not change this (filetype handling for x/y).
n_interp = bit depth of frequency inter | polation, n = 2**n_interp. 0 = auto
'''
if from_file:
if type(data) is str:
if not os.path.exists(data):
print('File does not exist')
return -1
imported_data = _import(data,file_type)
#insert testing for wavelength/intensity ... |
stewartsmith/bzr | bzrlib/plugins/weave_fmt/test_bzrdir.py | Python | gpl-2.0 | 26,897 | 0.005391 | # Copyright (C) 2006-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | \xc3\xad_\xb3\xbb?m\xf5\xbd\xf9\xb8\xb4\xba\x9eJ\xec\x87\xb5_)I\xe5\x11K\xaf\xed\xe35\x85\x89\xfe\xa5\x8e\x0c@ \xc0\x05\xb8\x90\x88GT\xd2\xa1\x14\xfc\xe2@K\xc7\xfd\xef\x85\xed\xcd\xe2D\x95\x8d\x1a\xa47<\x02c2\xb0 \xbc\xd0\x8ay\xa3\xbcp\x8a\x83\x1 | 2A3\xb7XJv\xef\x7f_\xf7\x94\xe3\xd6m\xbeO\x14\x91in4*<\x812\x88\xc60\xfc\x01>k\x89\x13\xe5\x12\x00\xe8<\x8c\xdf\x8d\xcd\xaeq\xb6!\x90\xa5\xd6\xf1\xbc\x07\xc3x\xde\x85\xe6\xe1\x0b\xc8\x8a\x98\x03T\x01\x00\x00'),
('.bzr/revision-store/mbp@sourcefrog.net-20051004035756-235f2b7dcdddd8dd.gz',
'\x1f\x8b\x08\x00\xc... |
thinkopensolutions/server-tools | sentry/__init__.py | Python | agpl-3.0 | 2,417 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo.service import wsgi_server
from odoo.tools import config as odoo_config
from . import const
from .logutils import LoggerNameFilter, OdooSentryHandler
_... | e = option.converter(value)
options[option.key] = value
level = config.get('sentry_logging_level', const.DEFAULT_LOG_LEVEL)
exclude_loggers = const.split_multiple(
config.get('sentry_exclude_loggers', const.DEFAULT_EXCLUDE_LOGGERS)
)
if level not in const.LOG_LEVEL_MAP:
| level = const.DEFAULT_LOG_LEVEL
client_cls = client_cls or raven.Client
client = client_cls(**options)
handler = OdooSentryHandler(
config.get('sentry_include_context', True),
client=client,
level=const.LOG_LEVEL_MAP[level],
)
if exclude_loggers:
handler.addFil... |
kaizentech/skeleton | config/settings/configurations/ENV.py | Python | apache-2.0 | 103 | 0 | """ environ se | ttings """
import environ
BASE_DIR = environ.Path(__file__) - 4
ENV_VAR = environ.Env() | |
oxc/Flexget | flexget/plugins/modify/list_clear.py | Python | mit | 2,149 | 0.003723 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
from flexget.plugin import PluginError
log = logging.getLogger('list_clear')
class ListClear(object... | config['phase'] == task.current_phase:
if task.manager.options.test and thelist.online:
log.info('would have cleared all items from %s - %s', plu | gin_name, plugin_config)
continue
log.verbose('clearing all items from %s - %s', plugin_name, plugin_config)
thelist.clear()
@event('plugin.register')
def register_plugin():
plugin.register(ListClear, 'list_clear', api_ver=2)
|
kaushik94/sympy | sympy/ntheory/tests/test_generate.py | Python | bsd-3-clause | 6,809 | 0.001028 | from sympy import Sieve, sieve, Symbol, S, limit, I, zoo, nan, Rational
from sympy.core.compatibility import range
from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \
primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
from sympy.ntheory.generate import... | ]
assert list(sieve.totientrange(0, 1)) == []
assert list(sieve.totientrange(1, 2)) == [1]
assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
| sieve._reset(mobius=True)
assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
assert list(sieve.mobiusrange(0, 1)) == []
assert list(sieve.mobiusrange(1, 2)) == [1]
assert list(primerange... |
UmSenhorQualquer/pyStateMachine | pyStateMachine/States/__init__.py | Python | mit | 273 | 0.025641 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ | = "Ricardo Ribeiro"
__credits__ = ["Ricardo Ribeiro"]
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ri | cardojvr@gmail.com"
__status__ = "Production"
|
OpenAgInitiative/gro-api | gro_api/sensors/urls.py | Python | gpl-2.0 | 344 | 0.002907 | from .views import (
SensorTypeVie | wSet, SensorViewSet, SensingPointViewSet, DataPointViewSet
)
def contribute_to_router(router):
router.register(r'sensorType', SensorTypeViewSet)
router.register(r'sensor', SensorViewSet)
router.register(r'sensingPoint', SensingPointViewSet)
| router.register(r'dataPoint', DataPointViewSet)
|
michaelsevilla/teuthology | teuthology/packaging.py | Python | mit | 22,261 | 0.000225 | import logging
import ast
import re
import requests
from cStringIO import StringIO
from .config import config
log = logging.getLogger(__name__)
'''
Map 'generic' package name to 'flavor-specific' package name.
If entry is None, either the package isn't known here, or
it's known but should not be installed on remote... | 'purge',
'{package}'.format(package=package)]
elif flavor == 'rpm':
pkgcmd = ['sudo',
'yum',
| '-y',
'erase',
'{package}'.format(package=package)]
else:
log.error('remove_package: bad flavor ' + flavor + '\n')
return False
return remote.run(args=pkgcmd)
def get_koji_task_result(task_id, remote, ctx):
"""
Queries kojihub and retri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.