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 |
|---|---|---|---|---|---|---|---|---|
atloiaco/vivo-pump | examples/positions/make_enum.py | Python | bsd-3-clause | 1,483 | 0.001349 | #!/usr/bin/env/python
"""
make_enum.py -- make enumerations for positions
"""
__author__ = "Michael Conlon"
__copyright__ = "Copyright 2015 (c) Michael Conlon"
__license__ = "BSD 3-Clause license"
__version__ = "0.1.1"
from datetime import datetime
from vivopump import get_parms, create_enum
def main():
""... | n via Orcid
query = """
SELECT (MIN (?xshort) AS ?short) ?vivo
WHERE
{
?vivo vivo:orcidId ?xs | hort .
}
GROUP BY ?vivo
ORDER BY ?short
"""
create_enum("orcid_enum.txt", query, parms)
# department via label
query = """
SELECT (MIN (?xlabel) AS ?short) ?vivo
WHERE
{
{?vivo a vivo:Department . } UNION {?vivo a vivo:Institute . } UNION {?vivo a vivo:School . }
... |
while519/SME | Tensor_exp.py | Python | bsd-3-clause | 11,310 | 0.002918 | #! /usr/bin/python
from model import *
# Utils ----------------------------------------------------------------------
def load_file(path):
return scipy.sparse.csr_matrix(cPickle.load(open(path)),
dtype=theano.config.floatX)
def compute_prauc(pred, lab):
pred = np.asarray(pred)
lab = np.asar... |
if state.op == 'SE':
valido = valido[-state.Nrel:, :]
outvalid = cPickle.load(open(state.datapath +
'%s-valid-targets-fold%s.pkl' % (state.dataset, state.fold)))
# Test set
testl = load_file(state.datapath + state.dataset +
'-test-lhs-fold%s.pkl' % state.fold)
testr = l... | pkl' % state.fold)
testo = load_file(state.datapath + state.dataset +
'-test-rel-fold%s.pkl' % state.fold)
if state.op == 'SE':
testo = testo[-state.Nrel:, :]
outtest = cPickle.load(open(state.datapath +
'%s-test-targets-fold%s.pkl' % (state.dataset, state.fold)))
# Model de... |
chenyujie/hybrid-murano | murano/packages/load_utils.py | Python | apache-2.0 | 3,350 | 0 | # Copyright (c) 2014 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... | tion as ex:
trace = sys.exc_info()[2]
raise e.PackageLoadError(
"Unable to load due to '{0}'".format(str(ex))), None, trace
if content:
p_format = str(content.get('Format'))
if not p_format or p_format not in formats:
raise e.PackageFormatError(
... | ats[p_format].create(source_directory, content, loader)
formats[p_format].load(package, content)
if preload:
package.validate()
return package
|
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/twisted/protocols/amp.py | Python | bsd-3-clause | 60,989 | 0.002246 | # -*- test-case-name: twisted.test.test_amp -*-
# Copyright 2005 Divmod, Inc. See LICENSE file for details
"""
This module implements AMP, the Asynchronous Messaging Protocol.
AMP is a protocol for sending multiple asynchronous request/response pairs over
the same connection. Requests and responses are both collect... | int 'Divided: %d / %d = %d' % (numerator, denominator, total)
return {'result': result}
Divide.responder(divide)
On the client side, the errors mapping will be used to | determine what the
'ZERO_DIVISION' error means, and translated into an asynchronous exception,
which can be handled normally as any L{Deferred} would be::
def trapZero(result):
result.trap(ZeroDivisionError)
print "Divided by zero: returning INF"
return 1e1000
ClientCreator(reactor, amp... |
tsdmgz/ansible | lib/ansible/utils/module_docs_fragments/dellos9.py | Python | gpl-3.0 | 2,591 | 0.003088 | #
# (c) 2015, Peter Sprygada <psprygada@ansible.com>
#
# Copyright (c) 2016 Dell Inc.
#
# This file is part of Ansible
#
# Ansible 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 Licens... | t object containing connection details.
default: null
suboptions:
host:
description:
- Specifies the DNS host name or address for connecting to the remote
device over the specified transport. The value of host is used as
the destination address for the transport.... | he port to use when building the connection to the remote
device.
default: 22
username:
description:
- User to authenticate the SSH session to the remote device. If the
value is not specified in the task, the value of environment variable
C(ANSIBLE_NET... |
straup/buildingequalsyes | bin/sqlite2solr.py | Python | bsd-2-clause | 3,932 | 0.006358 | #!/usr/bin/env python
import pysolr
import os.path
import sqlite3
import sys
import json
import Geohash
import re
import geojson
import shapely.wkt
from shapely.geometry import Polygon
from shapely.geometry import LineString
solr = pysolr.Solr('http://localhost:9999/solr/buildings')
solr.delete(q='*:*')
dbconn = sq... | LIMIT %s, %s" % (offset, limit)
print "%s (%s)" % (sql, count)
dbcurs.execute(sql)
for row in dbcurs.fetchall():
counter += 1
uid = uid + 1
way_ | id, lat, lon, woeid, nodes, tags = row
if not lat or not lon:
continue
if float(lat) < -90. or float(lat) > 90.:
continue
if float(lon) < -180. or float(lon) > 180.:
continue
if not woeid:
woeid = 0
nodes = nodes.split(',')
... |
pwyliu/cloud-init-0.6.3 | cloudinit/CloudConfig/cc_rsyslog.py | Python | gpl-3.0 | 3,237 | 0.000618 | # vi: ts=4 expandtab syntax=python
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free softw | are: 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General P... |
anupam-mitra/PySpikeSort | spikesort/features/spectral.py | Python | gpl-3.0 | 1,567 | 0.008296 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ${FILENAME}
#
# Copyright 2015 Anupam Mitra <anupam.mitra@gmail.com>
#
# 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... | in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if n... | Floor, Boston,
# MA 02110-1301, USA.
#
#
import numpy as np
import pywt
def wavelet_decomp (s, wavelet='haar', levels=4):
"""
Wavelet decomposition based features
Parameters
----------
s:
Signal segments from which to compute first difference with
lag. The shape should be... |
liqd/a4-meinberlin | tests/dashboard/test_dashboard_views_module_delete.py | Python | agpl-3.0 | 3,903 | 0 | import pytest
from django.urls import reverse
from adhocracy4.modules.models import Module
from adhocracy4.test.helpers import redirect_target
@pytest.mark.django_db
def test_module_delete_perms(client, phase, user, user2):
module = phase.module
module_delete_url = reverse('a4dashboard:module-delete', kwarg... | g published modules has no effect
client.login(username=user2, password='password')
response = client.post(m | odule_delete_url)
assert response.status_code == 302
assert Module.objects.all().count() == 1
# unpublish module
module.is_draft = True
module.save()
client.login(username=user2, password='password')
response = client.post(module_delete_url)
assert redirect_target(response) == 'project... |
ternaris/marv-robotics | code/marv/marv_node/testing/_robotics_tests/test_section_topics.py | Python | agpl-3.0 | 960 | 0.002083 | # Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from pkg_resources import resource_filename
import marv_node.testing
fro | m marv_node.testing import make_dataset, run_nodes, temporary_directory
from marv_robotics.detail import connections_section as node
from marv_store import Store
class TestCase(marv_node.testing.TestCase):
# TODO: Generate bags instead, but with connection info!
BAGS = [
resource_filename('marv_node.t... | ef test_node(self):
with temporary_directory() as storedir:
store = Store(storedir, {})
dataset = make_dataset(self.BAGS)
store.add_dataset(dataset)
streams = await run_nodes(dataset, [node], store)
self.assertNodeOutput(streams[0], node)
#... |
tvansteenburgh/PerfKitBenchmarker | tests/sample_test.py | Python | apache-2.0 | 1,098 | 0.001821 | # Copyright 2014 | Google 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 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 e... |
alessio/laditools | laditools/jack.py | Python | gpl-3.0 | 8,258 | 0.013684 | #!/usr/bin/python
# LADITools - Linux Audio Desktop Integration Tools
# Copyright (C) 2011-2012 Alessio Treglia <quadrispro@ubuntu.com>
# Copyright (C) 2007-2010, Marc-Olivier Barre <marco@marcochapeau.org>
# Copyright (C) 2007-2009, Nedko Arnaudov <nedko@arnaudov.name>
#
# This program is free software: you can redist... | return _dbus_type_to_python_type (values[0][0]), _dbus_type_to_python_type (values[1][0])
def param_has_enum (self, path):
is_range, is_strict, is_fake_value, values = self.controller_iface.GetParameterConstraint (path)
return not is_range and len (values) != 0
def param_is_strict_enum (sel... | ler_iface.GetParameterConstraint (path)
return is_strict
def param_is_fake_value (self, path):
is_range, is_strict, is_fake_value, values = self.controller_iface.GetParameterConstraint (path)
return is_fake_value
def param_get_enum_values (self, path):
is_range, is_strict, is_f... |
openzim/zimfarm | dispatcher/backend/supervisor-listener.py | Python | gpl-3.0 | 1,917 | 0.000522 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
""" supervisor event listenner for generic script launching
launches a script (passed as $1+) and communicates with supervisor """
import sys
import pathlib
import datetime
import subprocess
def to_supervisor(text):
# only event... | ad event payload and print it to stderr
| headers = dict([x.split(":") for x in line.split()])
sys.stdin.read(int(headers["len"]))
now = datetime.datetime.now()
if last_run is None or last_run <= now - datetime.timedelta(seconds=interval):
last_run = now
script = subprocess.run(
[command] + ... |
olivierdalang/stdm | third_party/sqlalchemy/engine/interfaces.py | Python | gpl-2.0 | 31,317 | 0.000032 | # engine/interfaces.py
# Copyright (C) 2005-2014 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
"""Define core interfaces used by the engine system."""
from .. impor... | Compiled, D | efaultGenerator, and TypeEngine.
All Dialects implement the following attributes:
name
identifying name for the dialect from a DBAPI-neutral point of view
(i.e. 'sqlite')
driver
identifying name for the dialect's DBAPI
positional
True if the paramstyle for this Di... |
grahamhayes/pdns | regression-tests.dnsdist/test_Trailing.py | Python | gpl-2.0 | 2,718 | 0.004047 | #!/usr/bin/env python
import threading
import dns
from dnsdisttests import DNSDistTest
class TestTrailing(DNSDistTest):
# this test suite uses a different responder port
# because, contrary to the other ones, its
# responders allow trailing data and we don't want
# to mix things up.
_testServerPor... | newServer{address="127.0.0.1:%s"}
addAction(AndRule({QTypeRule(dnsdist.AAAA), TrailingDataRule()}), DropAction())
"""
| @classmethod
def startResponders(cls):
print("Launching responders..")
cls._UDPResponder = threading.Thread(name='UDP Responder', target=cls.UDPResponder, args=[cls._testServerPort, True])
cls._UDPResponder.setDaemon(True)
cls._UDPResponder.start()
cls._TCPResponder = th... |
Hybrid-Cloud/conveyor | conveyor/conveyorheat/engine/resources/aws/cfn/wait_condition_handle.py | Python | apache-2.0 | 2,385 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | tatus = support.SupportStatus(version='2014.1')
METADATA_KEYS = (
| DATA, REASON, STATUS, UNIQUE_ID
) = (
'Data', 'Reason', 'Status', 'UniqueId'
)
def get_reference_id(self):
if self.resource_id:
wc = signal_responder.WAITCONDITION
return six.text_type(self._get_ec2_signed_url(signal_type=wc))
else:
return six.tex... |
TiddlySpace/tiddlyspace | tiddlywebplugins/tiddlyspace/betaserialization.py | Python | bsd-3-clause | 3,007 | 0.000998 | """
extend TiddlyWiki serialization to optionally use beta or
externalized releases and add the UniversalBackstage.
activated via "twrelease=beta" URL parameter or ServerSettings,
see build_config_var
"""
import logging
from tiddlyweb.util import read_utf8_file
from tiddlywebwiki.serialization import Serialization... | name in tiddlers.link:
tiddlers.link = '/tiddlers'
return WikiSerialization.list_tiddlers(self, tiddlers)
def _get_wiki(self):
beta = external = False
release = self.environ.get('tiddlyweb.query', {}).get(
'twrelease', [False])[0]
externali | ze = self.environ.get('tiddlyweb.query', {}).get(
'external', [False])[0]
download = self.environ.get('tiddlyweb.query', {}).get(
'download', [False])[0]
if release == 'beta':
beta = True
if externalize:
external = True
# If someb... |
JMill/edX-Learning-From-Data-Solutions-jm | Homework_6/Python/hw6_by_kirbs.py | Python | apache-2.0 | 3,869 | 0.010856 | #-------------------------------------------------------------------------------
# Name: hom | ework 6
# Author: kirbs
# Created: 11/9/2013
#-------------------------------------------------------------------- | -----------
#!/usr/bin/env python
import urllib
import numpy
# ###################################################
# ##################Question 2-6 Helpers #############
# ###################################################
def in_dta():
fpin = urllib.urlopen("http://work.caltech.edu/data/in.dta")
return ... |
kwilliams-mo/iris | lib/iris/tests/test_grib_save.py | Python | gpl-3.0 | 10,295 | 0.002817 | # (C) British Crown Copyright 2010 - 2013, Met Office
#
# This file is part of Iris.
#
# Iris 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 l... | (("GRIB", "uk_t", "uk_t.grib2"))
reference_text = tests.get_result_path(("grib_save", "latlon_forecast_plev.grib_compare.txt"))
self.save_and_compare(source_grib, reference_text)
def test_rotated_latlon(self):
source_gr | ib = tests.get_data_path(("GRIB", "rotated_nae_t", "sensible_pole.grib2"))
reference_text = tests.get_result_path(("grib_save", "rotated_latlon.grib_compare.txt"))
# TODO: Investigate small change in test result:
# long [iDirectionIncrement]: [109994] != [109993]
# Consider t... |
jeffbaumes/jeffbaumes-vtk | Wrapping/Python/vtk/charts.py | Python | bsd-3-clause | 230 | 0 | """ This module loads all the classes from t | he VTK Charts library into
its namespace. This is an optional module."""
import os
if os.name == 'posix':
from libvtkChartsPython import *
else:
from vtkChartsPython | import *
|
shantnu/PyEng | WordCount/count_lines_fixed.py | Python | mit | 299 | 0.003344 | #! / | usr/bin/python
f = open("birds.txt", "r")
data = f.read()
f.close()
lines = data.split("\n")
print("Wrong: The number of lines is", len(lines))
for l in lines:
if not l:
# Can also do this: if len(l) == 0
| lines.remove(l)
print("Right: The number of lines is", len(lines))
|
ZerpaTechnology/AsenZor | apps/votSys2/admin/settings/config.py | Python | lgpl-3.0 | 220 | 0.045455 | #!/usr/bin/python
# | -*- coding: utf-8 -*-
libs_python=["functions"]
libs_php=[]
#aqui va el nombre de las bases de datos
dbs=["main"]
#variable para paso de parametros
p={}
consola=True
host="localhost"
consola | _port=9999 |
alexandercrosson/ml | neural_network/basic.py | Python | mit | 1,043 | 0.004794 | """A basic implementation of a Neural Network
by following the tutorial by Andrew Trask
http://iamtrask.github.io/2015/07/12/basic-python-network/
"""
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
if deriv==True:
return x * (1-x)
return 1 / (1 + np.exp(-x))
# input dataset
x = np.... | ndom.random((3, 1)) - 1
for i in xrange(10000):
# forward propagation
l0 = x
l1 = nonlin(np.dot(l0, syn0))
print l1
break
# how much did we miss
l1_error = y - l1
# multiply how much we missed by the
# slope of the si | gmoid at the values in l1
l1_delta = l1_error * nonlin(l1, True)
# update weights
syn0 += np.dot(l0.T, l1_delta)
print 'Output after training:'
print l1
|
ronnyandersson/zignal | zignal/tests/test_music_scales.py | Python | mit | 5,855 | 0.006319 | '''
Created on 24 Feb 2015
@author: Ronny Andersson (ronny@andersson.tk)
@copyright: (c) 2015 Ronny Andersson
@license: MIT
'''
# Standard library
import unittest
# Third party
import nose
# Internal
from zignal.music import scales
class Test_midi_scales(unittest.TestCase):
# Benson, DJ. (2006). Music: A Math... | les.piano_freq2key(scales.piano_key2freq(10.2),
| quantise=True), 10, places=7)
self.assertAlmostEqual(scales.piano_freq2key(scales.piano_key2freq(34.678),
quantise=True), 35, places=7)
if __name__ == "__main__":
noseargs = [__name__,
"--verbosity... |
pk-python/basics | basics/files.py | Python | mit | 169 | 0.029586 | flight_file=open("flight.txt","w")
flight_file.write("Hello")
| text=fl | ight_file.read()
flight_file.close()
flight_file.closed # Returns whether the file is closed or not. |
tilogaat/blueflood | demo/ingest.py | Python | apache-2.0 | 3,541 | 0.001977 | #!/usr | /bin/env python
# Licensed to Rackspace under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# Rackspace licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file... | uired 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.
import time
imp... |
Landver/netmon | apps/backups/migrations/0002_auto_20170424_0117.py | Python | mit | 737 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on | 2017-04-23 22:17
from __future__ import unicode_literals
| from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('backups', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='backupfirewall',
name='file_location',
),
migrations.RemoveField(
... |
tboyce021/home-assistant | homeassistant/components/vizio/media_player.py | Python | apache-2.0 | 18,119 | 0.000883 | """Vizio SmartCast Device support."""
from datetime import timedelta
import logging
from typing import Any, Callable, Dict, List, Optional, Union
from pyvizio import VizioAsync
from pyvizio.api.apps import find_app_name
from pyvizio.const import APP_HOME, INPUT_APPS, NO_APP_RUNNING, UNKNOWN_APP
from homeassistant.com... | e = None
return
self._state = STATE_ON
audio_settings = await self._device.get_all_settings(
VIZIO_AUDIO_SETTINGS, log_api_exception=False
)
if audio_settings:
self._volume_level = float(audio_settings[VIZIO_VOLUME]) / self._max_volume
i... | self._is_volume_muted = (
audio_settings[VIZIO_MUTE].lower() == VIZIO_MUTE_ON
)
else:
self._is_volume_muted = None
if VIZIO_SOUND_MODE in audio_settings:
self._supported_commands |= SUPPORT_SELECT_SOUND_MODE
... |
theicfire/djangofun | src/firsty/settings.py | Python | bsd-3-clause | 5,085 | 0.001573 | # Django settings for firsty project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'N... | dmindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 er | ror.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmai... |
iti-luebeck/HANSE2012 | hanse_ros/hanse_pipefollowing/nodes/pipefollowing.py | Python | bsd-3-clause | 10,171 | 0.033133 | #!/usr/bin/env python
PACKAGE = 'hanse_pipefollowing'
import roslib; roslib.load_manifest('hanse_pipefollowing')
import rospy
import dynamic_reconfigure.server
import math
import smach
import smach_ros
import numpy
from geometry_msgs.msg import PoseStamped, Point, Twist, Vector3
from hanse_msgs.msg import Object, sollS... | ospy.loginfo('distY: '+repr(distanceY / Config.maxDistance))
def configCallback(config, level):
rospy.loginfo('Reconfigure Request: ')
Config.minSize = config['minSize' | ]
Config.maxSize = config['maxSize']
Config.fwSpeed = config['fwSpeed']
Config.deltaAngle = config['deltaAngle']
Config.deltaDist = config['deltaDist']
Config.kpAngle = config['kpAngle']
Config.kpDist = config['kpDist']
Config.robCenterX = config['robCenterX']
Config.robCenterY = config['robCenterY']
Config.ma... |
dries007/Basys3 | python/RouletteMaker.py | Python | mit | 1,814 | 0.001654 | index = 20
bets = 25
names = ("Plain", "Cheval H", "Cheval V", "Trans", "Trans S", "Carre", "Colonne", "Simple")
for bet in range(bets):
col = 40
# --------------------------------------- money
print("""
when %d =>
if bets_index > %d then
fb_a_addr <= std_logic_vector(to_unsigned(COLS*21 + COLS... | > %d then
fb_a_addr <= std_logic_vector(to_unsigned(COLS*21 + COLS*%d + %d, 14));
fb_a_dat_in <= x"2e"; -- .
end if;""" % (index, bet, bet, col))
index += 1
col += 1
# --------------------------------------- name
col += 1
for n in range(8): # n = index of letter... | %d).kind is""" % (index, bet, bet, col, bet))
for kind in range(1, 9):
if n < len(names[kind-1]) and names[kind-1][n] != ' ':
print(""" when %d => fb_a_dat_in <= x"%02x"; -- %c""" % (kind, ord(names[kind-1][n]), names[kind-1][n]))
print(""" when others => ... |
PyBossa/random-scheduler | random_scheduler/__init__.py | Python | agpl-3.0 | 1,346 | 0.001486 | import pybossa.sched as sched
from pybossa.forms.forms import TaskSchedulerForm
from pybossa.core import project_repo
from flask.ext.plugins import | Plugin
from functools import wraps
import random
__plugin__ = "RandomScheduler"
__version__ = "0.0.1"
SCHEDULER_NAME = 'random'
def get_random_task(project_id, user_id=None, user_ip=None,
n_answers=30, offset=0):
"""Return a random task for the user."""
project = project_repo.get(projec... | en(project.tasks) > 0:
return random.choice(project.tasks)
else:
return None
def with_random_scheduler(f):
@wraps(f)
def wrapper(project_id, sched, user_id=None, user_ip=None, offset=0):
if sched == SCHEDULER_NAME:
return get_random_task(project_id, user_id, user_ip, of... |
ThiefMaster/indico | indico/modules/events/static/util.py | Python | mit | 6,995 | 0.002001 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import base64
import mimetypes
import re
from contextlib import contextmanager
from urllib.parse import ur... | need | a .html extension
if not _url_has_extension_re.match(url):
url += '.html'
return url
def _rule_for_endpoint(endpoint):
return next((x for x in current_app.url_map.iter_rules(endpoint) if 'GET' in x.methods), None)
@contextmanager
def override_request_endpoint(endpoint):
rule = _rule_for_end... |
wgwoods/blivet | tests/imagebackedtestcase.py | Python | gpl-2.0 | 3,326 | 0.001203 |
import os
import unittest
from blivet import Blivet
from blivet import util
from blivet.size import Size
from blivet.flags import flags
@unittest.skipUnless(os.environ.get("JENKINS_HOME"), "jenkins only test")
@unittest.skipUnless(os.geteuid() == 0, "requires root access")
class ImageBackedTestCase(unittest.TestCase... | self.blivet.clearPartitions()
#
# create the rest of the stack
#
self._set_up_storage()
#
# write configuration to disk images
#
self.blivet.doIt()
| def setUp(self):
""" Do any setup required prior to running a test. """
flags.image_install = True
self.blivet = Blivet()
self.addCleanup(self._cleanUp)
self.set_up_storage()
def _cleanUp(self):
""" Clean up any resources that may have been set up for a test. ""... |
PTAug/fashion-analytics | fashion-analytics/image-processing/testcolor.py | Python | apache-2.0 | 56 | 0.017857 | from colordetection | imp | ort *
topColors(992780587437103) |
kamagatos/django-registration-withemail | registration_withemail/auth_urls.py | Python | bsd-2-clause | 1,200 | 0.0075 | """
URL patterns for the views included in ``django.contrib.auth``.
"""
from django.conf.urls import patterns, url
from registration_withemail.forms import EldonUserAuth | enticationForm
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',
{'template_name': 'registration/login.html', 'authentication_form': EldonUserAuthenticationForm}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^password_change/$',... | ango.contrib.auth.views.password_change_done', name='password_change_done'),
url(r'^password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'),
url(r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9... |
Cuile/Grab-the-National-Train-Timetable | grab.py | Python | mit | 7,660 | 0.002094 | # -*- coding: utf-8 -*-
import json
from concurrent.futures import ThreadPoolExecutor
from datetime import date, timedelta
import requests
import common
# ------------------------------------------------------------------------
def grab(url):
requests.packages.urllib3.disable_warnings()
# 请求头
headers ... | time + timedelta(days=3)
# ]
dates = [start_time]
urls = []
for d in dates:
for i in train_list:
train_no | = i['train_no']
for j in station_name:
if i['from_station'] == j['station_name']:
from_station_telecode = j['telecode']
if i['to_station'] == j['station_name']:
to_station_telecode = j['telecode']
ur... |
gisce/enerdata | spec/contracts/tariff_spec.py | Python | mit | 226,020 | 0.007597 | from expects.testing import failure
from expects import *
from enerdata.contracts.tariff import *
from datetime import datetime, timedelta
from enerdata.datetime.timezone import TIMEZONE
from mamba import before, context, description, it
with description('Create a period'):
with it('accepts "te"'):
Tariff... | lambda: tari_T30A.evaluate_powers([16, 17.1, 16])).to(
raise_error(NotNormalizedPower))
expect(lambda: tari_T30A.evaluate_powers([14, 15.242, 15.242])).to(
raise_error(IncorrectMinPower))
assert tari_T30A.evaluate_powers([15.242, 15.242, 16.454])
expect(lambda: tari_T30A.... | 1A.evaluate_powers([-10, -5, 0])).to(
raise_error(NotPositivePower))
assert tari_T31A.evaluate_powers([10, |
plotly/plotly.py | packages/python/plotly/plotly/graph_objs/scatter/_hoverlabel.py | Python | mit | 17,848 | 0.000952 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Hoverlabel(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scatter"
_path_str = "scatter.hoverlabel"
_valid_props = {
"align",
"ali... | burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksal... | rkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory,... |
hannosch/genc | genc/__init__.py | Python | apache-2.0 | 935 | 0 | from genc.regions import (
Region,
REGIONS,
)
try:
basestring
except NameError: # pragma: no cover
basestring = str
def _build_cache(name):
idx = Region._fields.index(name)
return dict([(reg[idx].upper(), reg) for reg in REGIONS
if reg[idx] is not None])
_alpha2 = _build_c... | e, basestring):
code = code.upper()
return _alpha3.get(code, default)
def region_by_name(name, default=None):
if isinstance(name, basestring):
name = name.upper()
return _name.get(name, default)
__all__ = (
'region_by_alpha2',
'region_by_alpha3',
'region_by_name',
| 'REGIONS',
)
|
empty/django-reversion | test_project/test_app/admin.py | Python | bsd-3-clause | 780 | 0.017949 | from django.contrib import admin
from django.contrib.contenttypes.generic import GenericStackedInline
from reversion.admin import VersionAdmin
from test_project.test_app.models import ChildModel, RelatedModel, GenericRelatedModel, ProxyModel
class RelatedModelInline(admin.StackedInline):
model = RelatedMo... | nAdmin):
inlines = RelatedModelInline, GenericRelatedInline,
list_display = ("parent_name", "child_name",)
list_editable = ("child_name",)
readonly_fields = ("parent_name",)
admin.site.register(ChildModel, ChildModelAdmin)
admin.site.register(ProxyModel, ChildModel | Admin)
|
arongdari/sparse-graph-prior | sgp/MixGGPgraphmcmc.py | Python | mit | 7,905 | 0.002657 | import time
import numpy as np
from numpy import log, exp
from scipy.sparse import triu, csr_matrix
from scipy.special import gammaln
from scipy.stats import norm, lognorm
from .NCRMmcmc import NGGPmcmc
from .GGPgraphmcmc import tpoissonrnd
def MixGGPgraphmcmc(G, modelparam, mcmcparam, typegraph, verbose=True):
... | = tpoissonrnd(lograte_poi)
count | = csr_matrix((n, (ind1, ind2)), (K, K))
N = count.sum(0).T + count.sum(1)
if iter == 10:
toc = (time.time() - tic) * niter / 10.
hours = np.floor(toc / 3600)
minutes = (toc - hours * 3600.) / 60.
print('-----------------------------------', flush=True)
... |
tedder/ansible-modules-core | utilities/helper/_fireball.py | Python | gpl-3.0 | 1,209 | 0.000827 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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... | NY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http:// | www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: fireball
short_description: Enable fireball mode on remote node
version_added: "0.9"
deprecated: "in favor of SSH with ControlPersist"
description:
- Modern SSH clients support ControlPersist which is just as fast as
fireball was. Please enable that in... |
giuseppe/virt-manager | virtManager/about.py | Python | gpl-2.0 | 1,472 | 0 | #
# Copyright (C) 2006, 2013 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <berrange@redhat.com>
#
# 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
# (... | def __init__(self):
vmmGObjectUI.__init__(self, "about.ui", "vmm-about")
self.builder.connect_signals({
"on_vmm_about_delete_event": self.close,
"on_vmm_about_response": self.close,
})
def show(self):
logging.debug("Showing about")
self.topwin.se... | logging.debug("Closing about")
self.topwin.hide()
return 1
def _cleanup(self):
pass
|
google/google-ctf | 2017/quals/2017-re-food/dex_to_bytes.py | Python | apache-2.0 | 705 | 0.001418 | #!/usr/bin/python
#
# Copyright 2018 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.o | rg/licenses/LICENSE-2.0
#
# Unless re | quired 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.
data = open('o... |
fabioz/Pydev | plugins/org.python.pydev.core/pysrc/conftest.py | Python | epl-1.0 | 12,827 | 0.002495 | import pytest
import sys
from _pydevd_bundle.pydevd_constants import IS_JYTHON, IS_IRONPYTHON
from tests_python.debug_constants import TEST_CYTHON
from tests_python.debug_constants import PYDEVD_TEST_VM
import site
import os
from _pydev_bundle import pydev_log
def pytest_report_header(config):
print('PYDEVD_USE_C... | .stdout.write(
'''
===============================================================================
Memory before: %s
%s
===============================================================================
''' % (request.function, format_memory_info(psutil.virtual_memory(), before_curr_proc_memory_info)))
yield
proc... | _iter():
if proc.pid not in current_pids:
try:
try:
cmdline = proc.cmdline()
except:
cmdline = '<unable to get>'
processes_info.append(
'New Process: %s(%s - %s) - %s' % (
... |
wbtuomela/mezzanine | mezzanine/utils/sites.py | Python | bsd-2-clause | 4,584 | 0.000218 | from __future__ import unicode_literals
import os
import sys
import threading
from contextlib import contextmanager
from django.contrib.sites.models import Site
from mezzanine.conf import settings
from mezzanine.core.request import current_request
from mezzanine.utils.conf import middlewares_or_subclasses_installed
... | bclasses_installed([SITE_PERMISSION_MIDDLEWARE]):
return user.is_staff and user.is_active |
return getattr(user, "has_site_permission", False)
def host_theme_path():
"""
Returns the directory of the theme associated with the given host.
"""
# Set domain to None, which we'll then query for in the first
# iteration of HOST_THEMES. We use the current site_id rather
# than a reques... |
artemsok/sockeye | test/unit/test_attention.py | Python | apache-2.0 | 18,317 | 0.005186 | # Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | layer_normalization=False,
| config_coverage=None,
is_scaled=False)
attention = sockeye.rnn_attention.get_attention(config_attention, max_seq_len=None)
assert type(attention) == sockeye.rnn_attention.DotAttention
assert att... |
adrienbrault/home-assistant | homeassistant/helpers/aiohttp_client.py | Python | apache-2.0 | 5,482 | 0.000547 | """Helper for aiohttp webclient stuff."""
from __future__ import annotations
import asyncio
from contextlib import suppress
from ssl import SSLContext
import sys
from typing import Any, Awaitable, cast
import aiohttp
from aiohttp import web
from aiohttp.hdrs import CONTENT_TYPE, USER_AGENT
from aiohttp.web_exceptions... | to_cleanup: bool = True,
**kwargs: Any,
) -> aiohttp.ClientSession:
"""Create a new ClientSession with kwargs, i.e. for cookies.
If auto_cleanup is False, you need to call detach() after the session
returned is no longer used. Default is True, the session will | be
automatically detached on homeassistant_stop.
This method must be run in the event loop.
"""
connector = _async_get_connector(hass, verify_ssl)
clientsession = aiohttp.ClientSession(
connector=connector,
headers={USER_AGENT: SERVER_SOFTWARE},
**kwargs,
)
client... |
harikishen/addons-server | src/olympia/zadmin/management/commands/addusertogroup.py | Python | bsd-3-clause | 1,528 | 0 | from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError
import olympia.core.logger
from olympia.access.models import Group, GroupUser
from olympia.users.models import UserProfile
class Command(BaseCommand):
help = 'Add a new user to a group.'
log = olympia.core... | o_adduser(user, group):
try:
if '@' in user:
| user = UserProfile.objects.get(email=user)
elif user.isdigit():
user = UserProfile.objects.get(pk=user)
else:
raise CommandError('Unknown input for user.')
group = Group.objects.get(pk=group)
GroupUser.objects.create(user=user, group=group)
except Integrit... |
angelblue05/plugin.video.emby | libraries/emby/core/connection_manager.py | Python | gpl-3.0 | 28,487 | 0.002457 | # -*- coding: utf-8 -*-
#################################################################################################
import json
import logging
import hashlib
import socket
import time
from datetime import datetime
from distutils.version import LooseVersion
from credentials import Credentials
from http import H... | , key):
return self.__shortcuts__(key)
def clear_data(self):
| LOG.info("connection manager clearing data")
self.user = None
credentials = self.credentials.get_credentials()
credentials['ConnectAccessToken'] = None
credentials['ConnectUserId'] = None
credentials['Servers'] = list()
self.credentials.get_credentials(credentials)
... |
wolendranh/movie_radio | admin/models.py | Python | apache-2.0 | 415 | 0.00241 | from config.settings import STREAM_COLLECTION
from bson.objectid import ObjectId
from radio_db.models import Ba | seModel
class Stream(BaseModel):
def __init__(self, db, data):
super().__init__(db, collection=STREAM_COLLECTION)
self.stream_ip = data.get('stream_ip')
self.name = data.get('name')
self.id = da | ta.get('id')
self.user_id = ObjectId(data.get('user_id'))
|
leaffan/pynhldb | db/takeaway.py | Python | mit | 991 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
from db.event impor | t Event
from db.player import Player
from db.team import Team
class Takeaway(Base, SpecificEvent):
__tablename__ = 'takeaways'
__autoload__ = True
HUMAN_READABLE = 'takeaway'
STANDARD_ATTRS = [
"team_id", "player_id", "zone", "taken_from_team_id"
]
def __init__(self, event_id, data_... | self.takeaway_id = uuid.uuid4().urn
self.event_id = event_id
for attr in self.STANDARD_ATTRS:
if attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
setattr(self, attr, None)
def __str__(self):
plr = Player.find_by_id(... |
arbiterofcool/fig-seed | template/fig-django/figexample/settings.py | Python | mit | 2,114 | 0 | """
Django set | tings for figexample project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the | project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SEC... |
Thx3r/survivalAlertWin | SurvivalAlertWin.py | Python | gpl-2.0 | 2,493 | 0.015243 | #!/usr/bin/env python
#PYTHON 3 only
# Sample Windows Startup check -- Mail alert
# SurvivalAlert v1.0
# By thxer.com
# N-pn.fr Communi | ty and Hexpresso CTF team
import os
import socket
import ctypes
import smtplib
#Global Variables
HOSTNAME = str(socket.gethostname())
IPLAN = str(socket.gethostbyna | me(socket.gethostname()))
AUTHORIZE_USER = ['Users','Utilisateur'] #User wich are allow to use computers
LIMIT_FREE_HDD_SPACE = 11 # Limit of free HDD space alert in GB
#Email Settings
TO = "admin@1337.com" # User who recept mail alert
USER = "smtp_user@1337.com"
PWD = "smtp_passwd"
SMTPSERV = "smtp.server_addres.com... |
amwelch/a10sdk-python | a10sdk/core/cgnv6/cgnv6_lsn_stun_timeout_udp.py | Python | apache-2.0 | 1,644 | 0.009732 | from a10sdk.common.A10BaseClass import A10BaseClass
class Udp(A10BaseClass):
"""Class Description::
Set UDP STUN timeout.
Class udp supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param port_start: {"description": "Port... | , "minLength": 1, "modify-not-allowed": 1, " | optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/lsn/stun-timeout/udp/{port_start}+{port_end}`.
"""
... |
yebrahim/pydatalab | google/datalab/bigquery/commands/_bigquery.py | Python | apache-2.0 | 49,966 | 0.011348 | # Copyright 2015 Google 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/li | censes/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 L | icense for the specific language governing permissions and limitations under
# the License.
"""Google Cloud Platform library - BigQuery IPython Functionality."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
from past.built... |
Jorge-Rodriguez/ansible | lib/ansible/modules/system/cron.py | Python | gpl-3.0 | 24,897 | 0.002691 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Dane Summers <dsummers@pinedesk.biz>
# Copyright: (c) 2013, Mike Grozak <mike.grozak@gmail.com>
# Copyright: (c) 2013, Patrick Callahan <pmc@patrickcallahan.com>
# Copyright: (c) 2015, Evan Kaufman <evan@digitalflophouse.com>
# Copyright: (c) 2015, Luca... | ion:
- If set, create a backup of the crontab before it is modified.
The location of the backup is returned in the C(backup_file) variable by this module.
type: bool
default: 'no'
minute:
description:
- Minute when the job should run ( 0-59, *, */2, etc )
default: "*"
hour:
d... | run ( 1-31, *, */2, etc )
default: "*"
aliases: [ dom ]
month:
description:
- Month of the year the job should run ( 1-12, *, */2, etc )
default: "*"
weekday:
description:
- Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )
default: "*"
aliases: [ d... |
phw/picard | picard/ui/ui_options_metadata.py | Python | gpl-2.0 | 9,138 | 0.003174 | # -*- coding: utf-8 -*-
# Automatically generated - don't edit.
# Use `python setup.py build_ui` to update it.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MetadataOptionsPage(object):
def setupUi(self, MetadataOptionsPage):
MetadataOptionsPage.setObjectName("MetadataOptionsPage")
Metada... | alLayout_3.addWidget(self.convert_punctuation)
self.release_ars = QtWidgets.QCheckBox(self.metadata_groupbox)
self.release_ars.setObjectName("release_ars")
self.verticalLayout_3.addWidget(self.release_ars)
self.track_ars = QtWidgets.QCheckBox(self.metadata_groupbox)
self.track_ar... |
self.guess_tracknumber_and_title = QtWidgets.QCheckBox(self.metadata_groupbox)
self.guess_tracknumber_and_title.setObjectName("guess_tracknumber_and_title")
self.verticalLayout_3.addWidget(self.guess_tracknumber_and_title)
self.verticalLayout.addWidget(self.metadata_groupbox)
se... |
gkc1000/pyscf | pyscf/geomopt/__init__.py | Python | apache-2.0 | 977 | 0.002047 | # Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | icense for the specific language governing permissions and
# limitations under the License.
#from . import berny_solver as berny
from .addons import as_pyscf_method
def optimize(method, *args, **kwargs):
try:
| from . import geometric_solver as geom
except ImportError as e1:
try:
from . import berny_solver as geom
except ImportError as e2:
raise e1
return geom.optimize(method, *args, **kwargs)
|
demisto/content | Packs/AzureDevOps/Integrations/AzureDevOps/AzureDevOps.py | Python | mit | 59,271 | 0.002733 | # type: ignore
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import copy
from requests import Response
from typing import Callable
INCIDENT_TYPE_NAME = "Azure DevOps"
OUTGOING_MIRRORED_FIELDS = {'status': 'The status of the pull request.',
'titl... | ization}',
verify=verify,
proxy=proxy,
scope='499b84ac-1321-427f-aa17-267ca6975798/user_impersonation offline_access')
self.organization = organization
def pipeline_run_request(self, project: str, pipeline_id: str, branch_name: str) -> dict:
"""
Run a pip... | project (str): The name or the ID of the project.
pipeline_id (str): The ID of the pipeline.
branch_name (str): The name of the repository branch which run the pipeline.
Returns:
dict: API response from Azure.
"""
params = {'api-version': '6.1-preview.1'}... |
sunqm/pyscf | pyscf/eph/eph_fd.py | Python | apache-2.0 | 5,884 | 0.008158 | #!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. 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
#
# U... | (mfset):
atmid, axis = np.divmod(k | i, 3)
p0, p1 = aoslice[atmid][2:]
vfull1 = mf1.get_veff() + mf1.get_hcore() - mf1.mol.intor_symmetric('int1e_kin') # <u+|V+|v+>
vfull2 = mf2.get_veff() + mf2.get_hcore() - mf2.mol.intor_symmetric('int1e_kin') # <u-|V-|v->
vfull = (vfull1 - vfull2)/disp # (<p+|V+|q+>-<p-|V-|q->)/dR
... |
brianwc/courtlistener | cl/visualizations/migrations/0001_initial.py | Python | agpl-3.0 | 3,649 | 0.005755 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('search', '0003_auto_20150826_0632'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | lization will map to (the slug)', max_length=75)),
('notes', models.TextFi | eld(help_text=b'Any notes that help explain the diagram, in Markdown format', blank=True)),
('degree_count', models.IntegerField(help_text=b'The number of degrees to display between cases')),
('view_count', models.IntegerField(default=0, help_text=b'The number of times the visualization ... |
indictranstech/erpnext | erpnext/stock/doctype/delivery_trip/test_delivery_trip.py | Python | agpl-3.0 | 2,568 | 0.025312 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import erpnext
import unittest
from frappe.utils import nowdate, add_days
from erpnext.tests.utils import create_test_contact_and_address
from erpnext.sto... | Delivery Trip',
'subject': 'Test Subject',
'owner': frappe.session.user
}).insert()
def create_vehicle():
if not frappe.db.exists("Vehicle", "JB 007"):
vehicle = frappe.get_doc({
"doctype": "Vehicle",
"license_plate": "JB 007",
"make": "Maruti",
"model": "PCM",
"last_odometer": 5000,
"acqu... | le.insert()
|
Frankkkkk/arctic | tests/unit/scripts/test_arctic_fsck.py | Python | lgpl-2.1 | 2,098 | 0.006673 | from mock import patch, sentinel, call
from arctic.scripts.arctic_fsck import main
from ...util import run_as_main
import sys
import pytest
def test_main():
with patch('arctic.scripts.arctic_fsck.Arctic') as Arctic, \
patch('arctic.scripts.arctic_fsck.get_mongodb_uri') as get_mongodb_uri, \
pa... | Ar | ctic.return_value._conn,
'arctic_sentinel'),
call('%s:%s' % (sentinel.host, sentinel.port),
Arctic.return_value._conn,
'arctic')]... |
Meisterschueler/ogn-python | migrations/versions/7f5b8f65a977_add_receiverranking.py | Python | agpl-3.0 | 2,677 | 0.004483 | """Add ReceiverRanking
Revision ID: 7f5b8f65a977
Revises: c53fdb39f5a5
Create Date: 2020-12-02 22:33:58.821112
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7f5b8f65a977'
down_revision = 'c53fdb39f5a5'
branch_labels = None
depends_on = None
def upgrade():
... | er(), nullable=True),
sa.Column('global_rank', sa.Integer(), nullable=True),
sa.Column('max_distance', sa.Float(precision=2), nullable=True),
sa.Column('max_normalized_quality', sa.Float(precision=2), nulla | ble=True),
sa.Column('messages_count', sa.Integer(), nullable=True),
sa.Column('coverages_count', sa.Integer(), nullable=True),
sa.Column('senders_count', sa.Integer(), nullable=True),
sa.Column('receiver_id', sa.Integer(), nullable=True),
sa.Column('country_id', sa.Integer(), nu... |
cdw/multifil | multifil/aws/userdata.py | Python | mit | 3,807 | 0.008406 | #!/usr/bin/env python3
# encoding: utf-8
"""
userdata_script.py - control an aws instance from a sqs queue
Run this guy on startup as a userdata scrip | t and he will connect to
s3 to download code | to a directory, and run commands in it that are
provided by an SQS queue, one job at a time per core
Processing as a string template, we replace the following keys with their
equivalents:
- aws_access_key
- aws_secret_key
- job_queue_name
- code_zip_key
Created by Dave Williams on 2011-02-08
"""
## I... |
catlinman/campdown | campdown/discography.py | Python | mit | 10,389 | 0.001636 |
import html
from .helpers import *
from .track import Track
from .album import Album
class Discography:
"""
Discography class of Campdown. This class takes in a URL and treats it as a
Bandcamp discography page. Takes over downloading of files as well as
fetching of general information which can be ... | tring_between(self.content, '<meta name="Description" content="', ">")).strip()
self.artist = meta.split(".\n", 1)[0]
if self.artist:
| self.output = os.path.join(self.output, self.artist, "")
# Create a new artist folder if it doesn't already exist.
if not os.path.exists(self.output):
os.makedirs(self.output)
safe_print(
'\nSet "{}" as the working directory.'.format(self.outp... |
LAMAC-IFUNAM/lafrioc-electronics-labjack | Python_LJM/Examples/eReadAddresses.py | Python | gpl-3.0 | 1,058 | 0.008507 | """
Demonstrates how to use the labjack.ljm.eReadAddresses (LJM_eReadAddresses)
function.
"""
from labjack import ljm
# Open first found LabJack
handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
#handle = ljm.openS("ANY", "ANY", "ANY")
info = ljm.getHandleInfo(handle)
print("Opened a LabJack with ... | mFrames = 3
aAddresses = [60028, 60000, 60004] # [serial number, product ID, firmware version]
aDataTypes = [ljm.constants.UINT32, ljm.constants.FLOAT32,
ljm.constants.FLOAT32]
results = ljm.eReadAddresses(handle, numFrames, aAddresses, aDataTypes)
print("\neReadAddresses res | ults: ")
for i in range(numFrames):
print(" Address - %i, data type - %i, value : %f" % \
(aAddresses[i], aDataTypes[i], results[i]))
# Close handle
ljm.close(handle)
|
zepto/musio | musio/portaudio/__init__.py | Python | gpl-3.0 | 830 | 0.003614 | #!/usr/bin/env python
# -*- coding: UTF8 -*-
#
# Provides access to portaudio.
# Copyright (C) 2010 Josiah Gordon <josiahg@gmail.com>
#
# This pr | ogram 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 program is distributed in the hope that it will be useful,
# but WITHOU... | . See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" A portaudio module.
"""
__all__ = ['_portaudio']
|
lyoniionly/django-cobra | src/cobra/apps/dashboard/autocheck/app.py | Python | apache-2.0 | 480 | 0 | from django.co | nf.urls import url
from cobra.core.application import Application
from cobra.core.loading import get_class
class AutoCheckDashboardApplication(Application):
name = None
index_view = get_class('dashboard.autocheck.views', 'IndexView')
def get_urls(self):
urls = [
url(r'^$', self.inde... | lication()
|
oppia/oppia | core/controllers/resources_test.py | Python | apache-2.0 | 33,854 | 0.000148 | # Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | exp_services.load_demo('0')
rights_manager.release_ownership_of_exploration(
self.system_user, '0')
self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME)
def test_image_upload_with_no_filename_raises_error(self):
self.login(self.EDITOR_EMAIL)
csrf_token = self.get_new_c... | os.path.join(feconf.TESTS_DATA_DIR, 'img.png'),
'rb', encoding=None
) as f:
raw_image = f.read()
response_dict = self.post_json(
'%s/exploration/0' % feconf.EXPLORATION_IMAGE_UPLOAD_PREFIX, {},
csrf_token=csrf_token,
upload_files=(('image', ... |
listyque/TACTIC-Handler | thlib/side/ntlm/des_c.py | Python | epl-1.0 | 9,208 | 0.016725 | # This file is part of 'NTLM Authorization Proxy Server' http://sourceforge.net/projects/ntlmaps/
# Copyright 2001 Dmitry A. Rozmanov <dima@xenon.spb.ru>
#
# This library is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Soft... | ils.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/> or <http://www.gnu.org/lic | enses/lgpl.txt>.
from U32 import U32
# --NON ASCII COMMENT ELIDED--
#typedef unsigned char des_cblock[8];
#define HDRSIZE 4
def c2l(c):
"char[4] to unsigned long"
l = U32(c[0])
l = l | (U32(c[1]) << 8)
l = l | (U32(c[2]) << 16)
l = l | (U32(c[3]) << 24)
return l
def c2ln(c,l1,l2,n):
"cha... |
tadgh/Shizuka | src/test_client/test_MonitorManager.py | Python | mit | 2,845 | 0.004569 | import unittest
import MonitorManager
import RamByteMonitor
import Constants
import logging
import Utils
#TODO figure out proper logging practice.
logging.basicConfig(level=logging.INFO)
class TestMonitorManager(unittest.TestCase):
def setUp(self):
self.manager = MonitorManager.MonitorManager()
... | all(self):
mp = Utils.get_drive_mountpoints()[0]
cpu_mon = self.manager.create_monitor(Constants.CPU_PERCENT_MONITOR)
self.manager.add_monitor(cpu_mon)
config_dict = {
"add": [
Constants.RAM_BYTE_MONITOR,
Constants.BYTES_RECEIVED_MONITOR,
... | andle_config(config_dict)
self.assertTrue(len(self.manager.list_monitors()) == 3
and Constants.CPU_PERCENT_MONITOR not in self.manager.list_monitors().keys())
if __name__ == "__main__":
unittest.main()
|
flyingSprite/spinelle | task_inventory/order_1_to_30/order_17_show_time_with_current_and_given.py | Python | mit | 1,185 | 0 |
"""Order 17: show time with give time and current time.
"""
class ShowTimeWithCurrentAndGiven(object):
@staticmethod
def show(current_timestamp=0, given_timestamp=0):
if current_tim | estamp - given_timestamp < 0:
return ''
if current_timestamp - given_timestamp < 120:
return '1分钟前'
if current_timestamp - given_timestamp < 60 * 60:
munite = int((current_timestamp - given_timestamp) / 60)
return f'{munite}分钟前'
| if current_timestamp - given_timestamp < 24 * 60 * 60:
hour = int((current_timestamp - given_timestamp) / 60 / 60)
return f'{hour}小时前'
day = int((current_timestamp - given_timestamp) / 24 / 60 / 60)
return f'{day}天前'
# # 1分钟前
# print(ShowTimeWithCurrentAndGiven.show(1502173717, ... |
javihernandez/accerciser-mirror | src/lib/accerciser/__init__.py | Python | bsd-3-clause | 1,039 | 0.014437 | '''
Configures the path to pyatspi. Exposes all other package conten | ts.
@author: Eitan Isaacson
@author: Peter Parente
@organization: IBM Corporation
@copyright: Copyright (c) 2006, 2007 IBM Corporation
@license: BSD
All rights reserved. This program and the accompanying materials are made
available under the terms of the BSD which accompanies this distribution, and
is available at... | _
import signal
def signal_handler(signal, frame):
print _(
'You pressed Ctrl+Z. This would normally freeze your keyboard')
print _(
'Ctrl+Z has been disabled; use "accerciser &" instead from the command line')
signal.signal(signal.SIGTSTP, signal_handler)
# If pyatspi not installed seperately, add pyatspi... |
isloux/Shannon | python/rbawz2.py | Python | bsd-3-clause | 3,690 | 0.066667 | #!/usr/bin/env python
#
# Computation of the rate-distortion function for source coding with side
# information at the decoder using the Blahut-Arimoto algorithm.
#
# Formulation similar to R.E. Blahut "Computation of Channel Capacity and
# Rate-Distortion Functions," IEEE Transactions on Information Theory, 18,
# no. ... | here is a problem
D=distortion_measure(max(nx,ny))
npoints=100
ds=arange(-10.0,0.0,0.1)
c=zeros((nx,nt),dtype='longdou | ble')
vtx=zeros((nt,nx),dtype='longdouble')
sexp=zeros(nt,dtype='longdouble')
#epsilon=finfo(longdouble(1.0)).eps
epsilon=1.0e-7
for s in range(npoints):
qty=ones((nt,ny),dtype='longdouble')
qty=qty/nt/ny
# Initialise stop test
stop=longdouble(1.0e5)
n=0
while stop>epsilon:
n=n+1
for i in range(n... |
slimta/python-slimta | test/test_slimta_edge_smtp.py | Python | mit | 5,342 | 0 | import unittest
from mox import MoxTestBase, IsA, IgnoreArg
import gevent
from gevent.socket import create_connection
from gevent.ssl import SSLSocket
from slimta.edge.smtp import SmtpEdge, SmtpSession
from slimta.envelope import Envelope
from slimta.queue import QueueError
from slimta.smtp.reply import Reply
from sli... | est('arg')
self.mox.ReplayAll()
h = SmtpSession(None, mock, None)
h._call_validator('test', 'arg')
def test_protocol_attribute(self): |
h = SmtpSession(None, None, None)
self.assertEqual('SMTP', h.protocol)
h.extended_smtp = True
self.assertEqual('ESMTP', h.protocol)
h.security = 'TLS'
self.assertEqual('ESMTPS', h.protocol)
h.auth = 'test'
self.assertEqual('ESMTPSA', h.protocol)
def ... |
bolt-project/bolt | test/spark/test_spark_basic.py | Python | apache-2.0 | 4,090 | 0.003912 | from numpy import arange, dtype, int64, float64
from bolt import array, ones
from bolt.utils import allclose
def test_shape(sc):
x = arange(2*3).reshape((2, 3))
b = array(x, sc)
assert b.shape == x.shape
x = arange(2*3*4).reshape((2, 3, 4))
b = array(x, sc)
assert b.shape == x.shape
def test... | mbda x: x[1].dtype).collect()
for dt in dtypes:
assert dt == dtype(float64)
b = ones(2**8, sc, dtype=bool)
assert b.dtype == dtype(bool)
dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
for dt in dtypes:
assert dt == dtype(bool)
def test_astype(sc):
from numpy | import ones as npones
a = npones(2**8, dtype=int64)
b = array(a, sc, dtype=int64)
c = b.astype(bool)
assert c.dtype == dtype(bool)
dtypes = c._rdd.map(lambda x: x[1].dtype).collect()
for dt in dtypes:
assert dt == dtype(bool)
b = ones((100, 100), sc, dtype=int64)
c... |
codefisher/web_games | million/migrations/0002_auto_20150622_0949.py | Python | mit | 2,654 | 0.00113 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('million', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='game',
options={'ver... | rrect'),
),
migrations.AlterField(
model_name='question',
name='answer_two',
field=models.CharField(max_length=50, verbose_name='Second Answer'),
),
migrations.AlterField(
model_name='question',
name='answer_two_correct',
... | rect'),
),
migrations.AlterField(
model_name='question',
name='game',
field=models.ForeignKey(verbose_name='Game', to='million.Game', on_delete=models.CASCADE),
),
migrations.AlterField(
model_name='question',
name='question',
... |
samgoodgame/sf_crime | iterations/spark-sklearn/spark_sklearn_test.py | Python | mit | 1,383 | 0.004345 |
## Non-optimized:
#
# from sklearn import grid_search, datasets
# from sklearn.ensemble import RandomForestClassifier
# from sklearn.grid_search import GridSearchCV
#
#
# digits = datasets.load_digits()
# X, y = digits.data, digits.target
# param_grid = {"max_depth": [3, None],
# "max_features": [1, 3, 1... | timators": [10, 20, 40, 80]}
# gs = grid_search.GridSearchCV(RandomForestClassifier(), param_grid=param_grid)
# print(gs.fit(X, y))
## Spark-optimized:
print("Spark-optimized grid search:")
from sklearn import grid_search, datasets
from sklearn.ensemble import RandomForestClassifier
# Use spark_sklearn’s grid search... | {"max_depth": [3, None],
"max_features": [1, 3, 10],
"min_samples_split": [2, 3, 10],
"min_samples_leaf": [1, 3, 10],
"bootstrap": [True, False],
"criterion": ["gini", "entropy"],
"n_estimators": [10, 20, 40, 80]}
gs = grid_search.GridS... |
stonewell/pymterm | pymterm/term_pylibui/main.py | Python | mit | 10,403 | 0.007402 | #coding=utf-8
import json
import logging
import os
from pylibui.core import App
from pylibui.controls import Window, Tab, OpenGLArea
import cap.cap_manager
from session import create_session
from term import TextAttribute, TextMode, reserve
import term.term_keyboard
from term.terminal_gui import TerminalGUI
from term... | , document):
view = self._create_view(document)
w, h = view.get_prefered_size()
win = TermWindow(bounds = (0, 0, w + 10, h + 50), document = document)
win.tabview = tabview = TermTabView()
win.auto_position = False
self._create_new_tab(win, view)
win.place(tabv... | enter()
win.show()
view.become_target()
def _remove_session_tab(self, win, view):
selected_index = win.tabview.selected_index
count = len(win.tabview.items)
if selected_index < 0 or selected_index >= count:
return
win.tabview.remove_item(view)
... |
openstack/nova | nova/virt/powervm/disk/localdisk.py | Python | apache-2.0 | 8,561 | 0.000117 | # Copyright 2013 OpenStack Foundation
# Copyright 2015, 2018 IBM Corp.
#
# 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/lice... | ts | k_stg.upload_new_vdisk(
self._adapter, self._vios_uuid, self.vg_uuid,
disk_dvr.IterableToFileAdapter(
IMAGE_API.download(context, image_meta.id)), img_name,
image_meta.size, d_size=image_meta.size,
upload_type=tsk_stg.UploadType.IO_STREAM,
file... |
idies/pyJHTDB | tests.py | Python | apache-2.0 | 1,897 | 0.01845 | ########################################################################
#
# Copyright 2014 Johns Hopkins University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai | n 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 s... | he License.
#
# Contact: turbulence@pha.jhu.edu
# Website: http://turbulence.pha.jhu.edu/
#
########################################################################
import sys
sys.path[0] = ''
import argparse
parser = argparse.ArgumentParser(
description = 'Test pyJHTDB installation.')
parser.add_argument(
'... |
magenta/magenta | magenta/pipelines/lead_sheet_pipelines.py | Python | apache-2.0 | 7,193 | 0.003337 | # Copyright 2022 The Magenta Authors.
#
# 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 ... | y using
chords_lib.extract_chords_for_melodies.
Args:
quantized_sequence: A quantized NoteSequence object.
search_start_step: Start searching for a melody at this time step. Assumed
to be the first step of a bar.
min_bars: Minimum length of melodies in number of bars. Shorter melodies are
... | , melodies will be truncated to the end of the last bar below
this threshold.
max_steps_discard: Maximum number of steps in extracted melodies. If
defined, longer melodies are discarded.
gap_bars: A melody comes to an end when this number of bars (measures) of
silence is encountered.
... |
alfredo/django-simpleblocks | src/simpleblocks/tests.py | Python | bsd-3-clause | 1,975 | 0.000506 | from django.contrib.sites.models import Site
from django.db.utils import IntegrityError
from django.test import TestCase
from django.template import Context, Template
from simpleblocks.models import SimpleBlock
def render_to_string(template, data):
t = Template(template)
c = Context(data)
return t.render... | """Helper to create block"""
data = {'body': self.body,
'key': key,
'site': self.site}
return SimpleBlock.objects.create(**data)
def testCreateBlock(self):
"""Test block creation"""
data = {'body': self.body,
'key': 'test',
... | ef testRenderedStatic(self):
"""Test the tag with a static key"""
self.create_block()
rendered = render_to_string(self.template, self.data)
self.assertEquals(rendered, self.body)
def testRenderedVariable(self):
"""Test the tag with a variable key"""
self.create_block... |
vishnu2kmohan/dcos-commons | __init__.py | Python | apache-2.0 | 191 | 0 | import sys
import os.path
# Add /testing/ to PYTHONPATH:
this_file_dir = os.path.dirname(os.path.abspath(__file__) | )
sys.path.append(os.path.normpath(os.path.join(this_file_ | dir, 'testing')))
|
bigzz/autotest | server/autoserv.py | Python | gpl-2.0 | 8,355 | 0.001317 | """
Library for autotest-remote usage.
"""
import sys
import os
import re
import traceback
import signal
import time
import logging
import getpass
try:
import autotest.common as common
except ImportError:
import common
from autotest.client.shared.settings import settings
require_atfork = settings.get_value('... | ault="")
results = parser.options.results
if not results:
results = 're | sults.' + time.strftime('%Y-%m-%d-%H.%M.%S')
if output_dir:
results = os.path.join(output_dir, results)
results = os.path.abspath(results)
resultdir_exists = False
for filename in ('control.srv', 'status.log', '.autoserv_execute'):
if os.path.exists(os.pa... |
nicococo/scRNA | scRNA/simulation.py | Python | mit | 24,906 | 0.003132 | import pdb
import random
import sys
import numpy as np
from sklearn.model_selection import train_test_split
def recursive_dirichlet(cluster_spec, num_cells,
dirichlet_parameter_cluster_size):
num_clusters = len(cluster_spec)
cluster_sizes = np.ones(num_clusters)
while min(cluste... | is cluster or set of cluster | s
prop_genes_de = np.random.uniform(min_prop_genes_de, max_prop_genes_de)
de_logfc = np.random.normal(mean_de_logfc, sd_de_logfc)
logfc = np.add(
parent_logfc,
generate_de_logfc(num_genes, prop_genes_de, de_logfc)
)
if type(num_cells) is list:
... |
chamikaramj/incubator-beam | sdks/python/apache_beam/examples/snippets/snippets.py | Python | apache-2.0 | 40,001 | 0.0134 | #
# 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 "License"); you may not us... | :
if transform_node.full_label.find('DummyReadForTesting') >= 0:
transform_node.transform.fn.file_to_read = self.renames['read']
elif transform_node.full_label.find('DummyWriteForTesting') >= 0:
transform_node.transform.fn.file_to_wri | te = self.renames['write']
def construct_pipeline(renames):
"""A reverse words snippet as an example for constructing a pipeline."""
import re
class ReverseWords(beam.PTransform):
"""A PTransform that reverses individual elements in a PCollection."""
def expand(self, pcoll):
return pcoll | beam.... |
LaoLiulaoliu/hzkgelastic2-doc-manager | setup.py | Python | apache-2.0 | 2,047 | 0.000489 | try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys
test_suite = "tests"
tests_require = ["mongo-orchestration >= 0.2, < 0.4", "requests >= 2.5.1"]
if sys.version_info[:2] == (2, 6):
# Need unittest2 to... | scription=lo | ng_description,
platforms=['any'],
author='anna herlihy',
author_email='mongodb-user@googlegroups.com',
url='https://github.com/mongodb-labs/hzkgelastic2-doc-manager',
install_requires=['mongo-connector >= 2.3.0', "elasticsearch>=2.0.0,<3.0.0"],
packages=["mongo_connector", "mongo_co... |
wolverton-research-group/qmpy | qmpy/analysis/tests.py | Python | mit | 1,996 | 0.001503 | import os
from qmpy import *
from django.test import TestCase
peak_locations = []
class MiedemaTestCase(TestCase):
def setUp(self):
read_elements()
def test_methods(self):
## test that it generally works
self.assertEqual(Miedema("FeNi").energy, -0.03)
self.assertEqual(Miedem... | def setUp(self):
read_elements()
sample_files_loc = os.path.join(INSTALL_PATH, "io", "files")
self.fcc = io.poscar.read(os.path.join(sample_files_loc, "POSCAR_FCC"))
self.bcc = io.poscar.read(os.path.join(sample_files_loc, "POSCAR_BCC"))
self.sc = io.poscar.read(os.path.join(sam... | ssertEqual(len(self.fcc[0].neighbors), 12)
self.bcc.find_nearest_neighbors()
self.assertEqual(len(self.bcc[0].neighbors), 8)
self.sc.find_nearest_neighbors()
self.assertEqual(len(self.sc[0].neighbors), 6)
def test_voronoi(self):
self.fcc.find_nearest_neighbors(method="voro... |
sapcc/monasca-agent | tests_to_fix/test_redis.py | Python | bsd-3-clause | 5,369 | 0.001863 | """
Redis check tests.
"""
import logging
import os
import unittest
import subprocess
import time
import pprint
import redis
from tests.common import load_check
from nose.plugins.skip import SkipTest
logger = logging.getLogger()
MAX_WAIT = 20
NOAUTH_PORT = 16379
AUTH_PORT = 26379
DEFAULT_PORT = 6379
MISSING_KEY_TOLER... | load_check('redisdb', {}, {})
instance = {
'host': 'localhost',
'port': AUTH_PORT,
'password': 'datadog-is-devops-best-friend'
}
r.check(instance) |
metrics = self._sort_metrics(r.get_metrics())
assert len(metrics) > 0, "No metrics returned"
# wrong passwords
instances = [
{
'host': 'localhost',
'port': AUTH_PORT,
'password': ''
... |
elcolie/fight | hopes/views.py | Python | mit | 2,543 | 0.002359 | from django.core.urlresolvers import reverse_lazy
from django.views.generic import View
from hopes.forms import StudentForm, SchoolForm, OneTimeForm, SpecificDateTimeForm
from hopes.models import Student, School, OneTime, SpecificDateTime
from vanilla import CreateView, DeleteView, ListView, UpdateView
class ListStu... | model = SpecificDateTime
form_class = SpecificDateTimeForm
success_url = | reverse_lazy('list_spec_time')
class DeleteSpecDateTime(DeleteView):
model = SpecificDateTime
success_url = reverse_lazy('list_spec_time') |
emanueldima/b2share | b2share/modules/files/cli.py | Python | gpl-2.0 | 3,385 | 0.001182 | # -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2016 CERN.
#
# B2Share 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... | ocations) > 0:
if matching_loca | tions[0].name == name:
raise click.BadParameter(
'Another location with the same name already exists.')
else:
raise click.BadParameter(
'Existing location "{}" has the same uri.'.format(
matching_locations[0].name))
if default:
... |
UnbDroid/robomagellan | Codigos/Raspberry/desenvolvimentoRos/devel/lib/python2.7/dist-packages/tf2_ros/__init__.py | Python | gpl-3.0 | 1,035 | 0.000966 | # -*- coding: utf-8 -*-
# generated from catkin/cmake/template/__init__.py.in
# keep symbol table as clean as possible by deleting all unnecessary symbols
from os import path as os_path
from sys import path as sys_path
from pkgutil import extend_path
__extended_path = "/home/pi/Documents/desenvolvimentoRos/src/tf2_r... | sys_path.insert(0, p)
del p
del sys_path
__path__ = extend_path(__path__, __name__)
del extend_path
__execfiles = []
for p in __extended_path:
src_init_file = os_path.join(p, __name__ + '.py')
if os_path.isfile(src_init_file):
__execfiles.append(src_init_file)
else:
src_init_file = os... | os_path.isfile(src_init_file):
__execfiles.append(src_init_file)
del src_init_file
del p
del os_path
del __extended_path
for __execfile in __execfiles:
with open(__execfile, 'r') as __fh:
exec(__fh.read())
del __fh
del __execfile
del __execfiles
|
RegioHelden/django-datawatch | django_datawatch/management/commands/datawatch_run_checks.py | Python | mit | 701 | 0.001427 | # -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from django_datawatch.datawatch import Scheduler
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--force',
acti | on='store_true',
dest='force',
default=False,
help='Execute all checks.',
)
parser.add_argument(
'--slug',
dest='slug',
default=None,
help='Slug of check to refresh, all checks will be | refreshed if slug is not provided',
)
def handle(self, force, slug, *args, **options):
Scheduler().run_checks(force=force, slug=slug)
|
cliftonmcintosh/openstates | openstates/mn/__init__.py | Python | gpl-3.0 | 5,612 | 0.000713 | from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the O... | ',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1 | 997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minneso... |
mattdelhey/kaggle-galaxy | saveData.py | Python | mit | 440 | 0.004545 | def saveData(X, f_out, colfmt='%i'):
'''
Quick alias for saving data matricies. If X and f_out are tuples,
this function will save multiple matricies at once.
'''
import numpy as np
if isinstance(X, tuple):
assert(len(X) == len(f_out))
for idx,Z in enumerate(X):
... | savetxt(f_out[idx], Z, delimiter=',', fmt=colfmt)
else:
np.savet | xt(f_out, X, delimiter=',', fmt=colfmt)
|
andrevmatos/Librix-ThinClient | src/ui/export/ssh_export/__init__.py | Python | gpl-2.0 | 739 | 0 | #!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient 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.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warrant... | ARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
__all__ = [
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.