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 |
|---|---|---|---|---|---|---|---|---|
oliver-sanders/cylc | cylc/flow/scripts/play.py | Python | gpl-3.0 | 999 | 0 | #!/usr/bin/env python3
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# 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... | distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program... | n,
PLAY_DOC as __doc__
)
# CLI of "cylc play". See cylc.flow.scheduler_cli for details.
|
mozilla/bedrock | tests/pages/regions/download_button.py | Python | mpl-2.0 | 947 | 0.003168 | # This Source Code Form is subject to the terms of the Mozilla | Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from selenium.webdriver.common.by import By
from pages.base import BaseRegion
class DownloadButton(BaseRegion):
_download_link_locator = (By.CSS_SELECTOR, ".download-link")
... | latform link to be displayed"
return els[0]
@property
def is_displayed(self):
return self.root.is_displayed() and self.platform_link.is_displayed() or False
@property
def is_transitional_link(self):
return "/firefox/download/thanks/" in self.platform_link.get_attribute("href")
... |
Vito2015/pyextend | pyextend/core/math.py | Python | gpl-2.0 | 643 | 0.001715 | # coding: utf-8
"""
pyextend.co | re.math
~~~~~~~~~~~~~~~~~~
pyextend core math tools.
:copyright: (c) 2016 by Vito.
:license: GNU, see LICENSE for more details.
"""
def isprime(n):
"""Check the number is prime value. if prime value returns True, not False."""
n = abs(int(n))
if n < 2:
return False
if n == 2:... | x == 0:
return False
return True
|
SorenOlegnowicz/tracker | tracker/api/views.py | Python | agpl-3.0 | 739 | 0.005413 | from django.shortcuts import render
from rest_framework import generics, serializers
from beacon.models import Inquiry, Reply
class | InquirySerializer(serializers.ModelSerializer):
class Meta:
model = Inquiry
class ReplySerializer(serializers.ModelSerializer):
class Meta:
model = Reply
class InquiryUpdateAPIView(generics.RetrieveUpdateAPIView):
serializer_class = InquirySerializer
queryset = Inquiry.objects.all... | print(request.body)
return super().dispatch(request,*args,**kwargs)
class ReplyListAPIView(generics.RetrieveAPIView):
serializer_class = ReplySerializer
queryset = Reply.objects.all() |
francisrod01/wrangling_mongodb | lesson 9/using_push.py | Python | mit | 2,530 | 0.004348 | #!~/envs/udacity_python3_mongodb
"""
$push is similar to $addToSet. The difference is that rather than accumulating only unique values
it aggregates all values into an array.
Using an aggregation query, count the number of tweets for each user. In the same $group stage,
use $push to accumulate all the tweet texts for... | install MongoDB, download and insert the dataset.
For instructions related to MongoDB setup and datasets please see Course Materials.
Please note that the dataset you are using here is a smaller version of the twitter dataset used in
examples in this lesson. If you attempt some of the same queries that we looked at in... | """
def get_db(db_name):
from pymongo import MongoClient
client = MongoClient('localhost:27017')
db = client[db_name]
return db
def make_pipeline():
pipeline = [
{
"$match": {
"user.statuses_count": {"$gte": 0}
}
},
{
"$... |
jim-easterbrook/python-gphoto2 | examples/read-exif-exifread.py | Python | gpl-3.0 | 3,776 | 0.001589 | #!/usr/bin/env python
# python-gphoto2 - Python interface to libgphoto2
# http://github.com/jim-easterbrook/python-gphoto2
# Copyright (C) 2015-19 Jim Easterbrook jim@jim-easterbrook.me.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | elf._ptr - (self._ptr % len(self._buf))
self._bu | f_len = self._camera.file_read(
self._folder, self._file_name, gp.GP_FILE_TYPE_NORMAL,
self._buf_ptr, self._buf)
offset = self._ptr - self._buf_ptr
size = min(size, self._buf_len - offset)
self._ptr += size
return self._buf[offset:offset + size]
def s... |
sander76/home-assistant | homeassistant/components/xiaomi_aqara/__init__.py | Python | apache-2.0 | 12,713 | 0.000551 | """Support for Xiaomi Gateways."""
from datetime import timedelta
import logging
import voluptuous as vol
from xiaomi_gateway import XiaomiGateway, XiaomiGatewayDiscovery
from homeassistant import config_entries, core
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_ID,
ATTR_VOLTAGE,
... | _id)
if len(hass. | data[DOMAIN][GATEWAYS_KEY]) == 0:
# No gateways left, stop Xiaomi socket
hass.data[DOMAIN].pop(GATEWAYS_KEY)
_LOGGER.debug("Shutting down Xiaomi Gateway Listener")
gateway_discovery = hass.data[DOMAIN].pop(LISTENER_KEY)
await hass.async_add_executor_job(gateway_discovery.stop_lis... |
clinton-hall/nzbToMedia | core/auto_process/managers/pymedusa.py | Python | gpl-3.0 | 6,117 | 0.00327 | import time
from core import logger
from core.auto_process.common import ProcessResult
from core.auto_process.managers.sickbeard import SickBeard
import requests
class PyMedusa(SickBeard):
"""PyMedusa class."""
def __init__(self, sb_init):
super(PyMedusa, self).__init__(sb_init)
def _create_ur... | s', self.sb_init.section)
return False
tr | y:
jdata = response.json()
except ValueError:
return False
return jdata
def api_call(self):
self._process_fork_prarams()
url = self._create_url()
logger.debug('Opening URL: {0}'.format(url), self.sb_init.section)
payload = self.sb_init.fork_... |
andredalton/bcc | 2014/MAC0242/Projeto/battle.py | Python | apache-2.0 | 6,126 | 0.004255 | # Para manipular a linha de comando
import os, sys, getopt, re
# Para manipular e validar arquivos XML
from lxml import etree
from lxml.etree import XMLSyntaxError, Element
# Quem é este pokemon?
from pokemon.pokemon import Pokemon
# Battle state schema file
bss = 'battle_state.xsd'
def usage():
"""Imprime inst... | f a in args:
print("option -p requires argument")
usage()
| sys.exit()
try:
p = int(a)
except ValueError:
print("Por favor passe uma porta valida!")
sys.exit()
elif o in ("-H", "--host"):
if a in args:
print("option -H requir... |
googleapis/python-kms | google/cloud/kms_v1/services/key_management_service/transports/grpc.py | Python | apache-2.0 | 50,118 | 0.001576 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Manages cryptographic keys and operations using those keys.
Implements a REST model with the following object | s:
- [KeyRing][google.cloud.kms.v1.KeyRing]
- [CryptoKey][google.cloud.kms.v1.CryptoKey]
- [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]
- [ImportJob][google.cloud.kms.v1.ImportJob]
If you are using manual gRPC libraries, see `Using gRPC with Cloud
KMS <https://cloud.google.com/... |
homma/terminal-dots | app.py | Python | mit | 2,068 | 0.024662 | #!/usr/bin/env python
## app.py
import curses
import locale
import key_event
import key_move
import model
import edit
import copy
# global data holder
class App():
def __init__(self):
self.win = curses.initscr()
self.setup_window()
h, w = self.win.getmaxyx()
self.data = model.Model(w, h)
def se... | main(args):
app = App()
add_event(app)
app.loop()
# set locale before initialize curses
locale.setlocale(locale.LC_ALL, "")
curses.wrapper(m | ain)
|
FreedomCoop/valuenetwork | work/__init__.py | Python | agpl-3.0 | 47 | 0 | default_app_config = 'work.apps.WorkAppConfi | g'
| |
claudiordgz/GoodrichTamassiaGoldwasser | ch01/r112.py | Python | mit | 3,148 | 0.000953 | """ Python's random module includes a function choice(data) that returns a
random element from a non-empty sequence. The random module includes
a more basic function randrange, with parametrization similar to
the built-in range function, that return a random choice from the given
range. Using only the randrange functio... | True, True, True, True, True, True, True, \
True, True, True, True, True, True, True, True, True, True, \
True, True, True, True, True, True, True, True, True, True, \
True, True, True | , True, True, True, True, True, True, True, \
True, True, True, True, True, True, True, True, True, True, \
True, True, True, True, True, True, True, True, True, True, \
True, True, True, True, True, True, True, True, True, True, \
True, True, True, True, True, True, True, True, True, True, \
True, True, True, True, Tr... |
spilgames/mysql-statsd | mysql_statsd/mysql_statsd.py | Python | bsd-3-clause | 5,234 | 0.004776 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import Queue
import signal
import sys
import os
import threading
import time
from ConfigParser import ConfigParser
from thread_manager import ThreadManager
from thread_mysql import ThreadMySQL
from thread_statsd import ThreadStatsd, ThreadFakeStatsd
clas... | _true",
help="Print the output that would be sent to statsd without actually sending data somewhere"
)
# TODO switch the default to True, and make it fork by default in init script.
op.add_argument("-f", "--foreground", dest="foreground", help="Dont fork main program", default=F... | f not self.config:
sys.exit(op.print_help())
try:
logfile = self.config.get('daemon').get('logfile', '/tmp/daemon.log')
except AttributeError:
logfile = sys.stdout
pass
if not opt.foreground:
self.daemonize(stdin='/dev/null', stdout=l... |
garyd203/flying-circus | src/flyingcircus/service/appsync.py | Python | lgpl-3.0 | 351 | 0.002849 | """General-use clas | ses to interact with the AppSync service through CloudFormation.
See Also:
`AWS developer guide for AppSync
<https://docs.aws.amazon.com/appsync/latest/devguide/welcome.html>`_
"""
# noinspection PyUnresolvedReferences
from .._raw import appsync as _raw
# noins | pection PyUnresolvedReferences
from .._raw.appsync import *
|
robocomp/robocomp-robolab | components/localization/UWBpublisher/src/specificworker.py | Python | gpl-3.0 | 6,357 | 0.002832 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 by YOUR NAME HERE
#
# This file is part of RoboComp
#
# RoboComp 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 o... | ing 'sudo' before the call")
self.t_initialize_to_finalize.emit()
else:
_original = deca.is_decawave_scan_entry
def is_decawave_scan_entry(scan_entry):
for (adtype, desc, value) in scan_entry.getScanData():
if adtype == 33 or desc == "128b... | return _original(scan_entry)
deca.is_decawave_scan_entry = is_decawave_scan_entry
self.devicelist = deca.scan_for_decawave_devices() # scan_for_decawave_devices()
anchor_devices = {}
tag_devices = {}
for k, dev in self.devicelist.items():
... |
blc56/PlanetWoo | tiletree/multi.py | Python | gpl-3.0 | 4,546 | 0.031236 | #Copyright (C) 2012 Excensus, LLC.
#
#This file is part of PlanetWoo.
#
#PlanetWoo 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.
#
#PlanetWoo is distributed in th | e 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 PlanetWoo. If not, see <http://www... |
newera912/WeatherTransportationProject | target/classes/edu/albany/cs/transWeatherPy/plotMesonetOrgData.py | Python | gpl-2.0 | 43,328 | 0.03882 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import lineStyles
Light_cnames={'mistyrose':'#FFE4E1','navajowhite':'#FFDEAD','seashell':'#FFF5EE','papayawhip':'#FFEFD5','blanchedalmond':'#FFEBCD','white':'#FFFFFF','mintcream':'#F5FFFA','antiquewhite':'#FAEBD7','moccasin':'#FFE4B5','ivory':'#F... | ize=8)
plt.title(day_data[2][0]+" Station Date: "+mon+day +"Temperature")
fig.add_subplot(10,1,4)
plt.plot(X,day_data[3][2],'b*-',linewidth='2.0', markersize=5,label='Temperature')
plt.legend(bbox_t | o_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.)
#plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5])
plt.ylim([-20.0,60.0])
plt.xlabel('time Period')
#plt.xlim([0.2,0.0])
plt.legend(loc='best',fontsize=8)
plt.title(day_... |
sunqm/mpi4pyscf | mpi4pyscf/mp/__init__.py | Python | gpl-3.0 | 40 | 0 | from . imp | ort mp2
from .mp2 import R | MP2
|
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/examples/cluster/plot_kmeans_stability_low_dim_dense.py | Python | mit | 4,324 | 0.001619 | """
============================================================
Empirical evaluation of the impact of k-means initialization
============================================================
Evaluate the ability of k-means initializations strategies to make
the algorithm convergence robust as measured by the relative stan... | np.concatenate([[i] * n_samples_per_center
for i in range(n_clusters_true)])
return shuffle(X, y, random_state=random_state)
# Part 1: Quantitative evaluation of various init methods
fig = plt.figure()
plots = []
legends = []
cases = [
(KMeans, 'k-means++', {}),
(KMe | ans, 'random', {}),
(MiniBatchKMeans, 'k-means++', {'max_no_improvement': 3}),
(MiniBatchKMeans, 'random', {'max_no_improvement': 3, 'init_size': 500}),
]
for factory, init, params in cases:
print("Evaluation of %s with %s init" % (factory.__name__, init))
inertia = np.empty((len(n_init_range), n_runs)... |
mschmidt87/python-neo | setup.py | Python | bsd-3-clause | 1,476 | 0.01355 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import os
long_description = open("README.rst").read()
install_requires = ['numpy>=1.3.0',
'quantities>=0.9.0']
if os.environ.get('TRAVIS') == 'true' and \
os.environ.get('TRAVIS_PYTHON_VERSION').startswith('2.6'):
... |
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
| 'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Scientific/Engineering']
)
|
bigswitch/neutron | neutron/tests/unit/services/trunk/test_db.py | Python | apache-2.0 | 1,965 | 0 | # Copyright 2016 Hewlett Packard Enterprise Development Company, LP
#
# 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 ap... | ices.trunk import db
from neutron.services.trunk import exceptions
from neutron.tests.unit import testlib_api
class TrunkDBTestCase(testlib_api.SqlTestCase):
def setUp(self):
super(TrunkDBTestCase, self).setUp()
self.ctx = context.get_admin_context()
def _add_network(self, net_id):
w... | lf.ctx.session.add(models_v2.Network(id=net_id))
def _add_port(self, net_id, port_id):
with self.ctx.session.begin(subtransactions=True):
port = models_v2.Port(id=port_id,
network_id=net_id,
mac_address='foo_mac_%s' % port_id,
... |
IBMStreams/streamsx.topology | test/python/spl/tk17/opt/.__splpy/packages/streamsx/scripts/extract.py | Python | apache-2.0 | 18,964 | 0.008437 | from __future__ import print_function
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016,2017
import sys
import sysconfig
import inspect
if sys.version_info.major == 2:
import funcsigs
import imp
import glob
import os
import shutil
import argparse
import subprocess
import xml.etree.ElementTree as ET
im... | print("Writ | ten: " + res)
return languageList
#
# module - module for operator
# opname - name of the SPL operator
# opobj - decorated object defining operator
#
def _common_tuple_operator(self, dynm, module, opname, opobj) :
if (not hasattr(dynm, 'spl_namespace')) and hasattr(dynm,... |
catapult-project/catapult | third_party/gsutil/gslib/vendored/boto/boto/cloudformation/__init__.py | Python | bsd-3-clause | 2,185 | 0 | # Copyright (c) 2010-2011 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010-2011, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, includin... | s of the So | ftware, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EX... |
jdereus/labman | labcontrol/gui/handlers/plate.py | Python | bsd-3-clause | 9,784 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2017-, LabControl development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -------------------------------------------------... | abControlUnknownIdError:
raise HTTPError(404, reason="Plating process %s doesn't exist"
% process_id)
plate_id = process.plate.id
plate_confs = [[pc.id, pc.description, pc.num_rows, pc.num_columns]
for pc in PlateConfiguration.iter()
... | c.description]
cdesc = SampleComposition.get_control_sample_types_description()
return {'plate_confs': plate_confs, 'plate_id': plate_id,
'process_id': process_id, 'controls_description': cdesc}
class PlateMapHandler(BaseHandler):
@authenticated
def get(self):
process_id = self.get... |
gersolar/stations | stations/api.py | Python | mit | 2,047 | 0.020029 | from stations.models import OpticFilter, Brand, Product, Device, SensorCalibration, Position, Station, Configuration, Measurement
from tastypie import fields
from tastypie.authentication import SessionAuthentication
from tastypie.resources import ModelResource
from tastypie_polymorphic import PolymorphicModelResource
... | = 'optic_filter'
authentication = SessionAuthentication()
class SensorCalibrationResource(ModelResource):
class Meta(object):
queryset = SensorCalibration.objects.all()
resource_na | me = 'sensor_calibration'
authentication = SessionAuthentication()
class StationResource(ModelResource):
materials = fields.ToManyField('PositionResource', 'coordinates', full=True)
class Meta(object):
queryset = Station.objects.all()
resource_name = 'station'
authentication = SessionAuthentication()
clas... |
anhstudios/swganh | data/scripts/templates/object/tangible/component/droid/shared_binary_load_lifter_droid_chassis.py | Python | mit | 510 | 0.043137 | # | ### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/droid/shared_binary_load_lifter_droid_chassis.iff"
result.... | result |
jbenden/ansible | lib/ansible/modules/monitoring/logstash_plugin.py | Python | gpl-3.0 | 4,754 | 0.001472 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.... | = 0, "check mode", ""
else:
rc, out, err = module.run_command(cmd)
if rc != 0:
reason = parse_error(out)
module.fail_json(msg=reason)
return True, cmd, out, err
def main():
module = Ansible | Module(
argument_spec=dict(
name=dict(required=True),
state=dict(default="present", choices=PACKAGE_STATE_MAP.keys()),
plugin_bin=dict(default="/usr/share/logstash/bin/logstash-plugin", type="path"),
proxy_host=dict(default=None),
proxy_port=dict(defau... |
luzheqi1987/nova-annotation | nova/tests/unit/api/openstack/compute/contrib/test_simple_tenant_usage.py | Python | apache-2.0 | 21,262 | 0.000282 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | ack.common import policy as common_policy
from nova impo | rt policy
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova import utils
SERVERS = 5
TENANTS = 2
HOURS = 24
ROOT_GB = 10
EPHEMERAL_GB = 20
MEMORY_MB = 1024
VCPUS = 2
NOW = timeutils.utcnow()
START = NOW - datetime.timedelta(hours=HOURS)
STOP = NOW
FAKE_INST_TYPE = {'id': 1,
... |
cloudbase/neutron-virtualbox | neutron/tests/sub_base.py | Python | apache-2.0 | 5,363 | 0 | # Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | = bool_from_env('OS_LOG_CAPTURE')
if not capture_logs:
std_logging.basicConfig(format=LOG_FORMAT, level=_level)
self.log_fixture = self.useFixture(
fixtures.FakeLogger(
format=LOG_FORMAT,
level=_level,
nuke_handlers=capture_logs,
... | = int(os.environ.get('OS_TEST_TIMEOUT', 0))
if test_timeout == -1:
test_timeout = 0
if test_timeout > 0:
self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
# If someone does use tempfile directly, ensure that it's cleaned up
self.useFixture(fixtures.Nes... |
FIWARE-TMForum/business-ecosystem-charging-backend | src/wstore/ordering/models.py | Python | agpl-3.0 | 4,227 | 0.000237 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 - 2016 CoNWeT Lab., Universidad Politécnica de Madrid
# This file belongs to the business-charging-backend
# of the Business API Ecosystem.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License... | ganization = models.ForeignKey(Organization, null=True, blank=True)
date = models.DateTimeField()
sales_ids = ListField()
state = models.CharField(max_length=50)
tax_address = DictField()
# List of contracts attached to the current order
contracts = ListField(EmbeddedModelField(Contract))
... | rue, blank=True)
def get_item_contract(self, item_id):
# Search related contract
for c in self.contracts:
if c.item_id == item_id:
contract = c
break
else:
raise OrderingError('Invalid item id')
return contract
def get_pr... |
Jumpscale/jumpscale_core8 | lib/JumpScale/tools/cache/Cache.py | Python | apache-2.0 | 1,412 | 0.000708 | from JumpScale import j
try:
import ujson as json
except:
import json
class CacheFactory:
def __init__(self):
self.__jslocation__ = "j.tools.cache"
def get(self, db, expiration=300):
"""
db is keyvalue stor to use
e.g. j.tools.cache.get(j.servers.kvs.getRedisStore(na... | __(self, db, expiration=300):
self.db = db
self.expiration = expiration
self.redis = str(self.db).find("re | dis") != -1
def set(self, key, value):
tostore = {}
tostore["val"] = value
tostore["expire"] = j.data.time.getTimeEpoch() + self.expiration
data = json.dumps(tostore)
if self.redis:
self.db.set("cache", key, data)
else:
self.db.set("cache", ke... |
sunqm/mpi4pyscf | mpi4pyscf/dft/uks.py | Python | gpl-3.0 | 4,017 | 0.000498 | #!/usr/bin/env python
import platform
import time
import numpy
from pyscf import lib
from pyscf.dft import uks
from mpi4pyscf.lib import logger
from mpi4pyscf.scf import uhf as mpi_uhf
from mpi4pyscf.dft import rks as mpi_rks
from mpi4pyscf.tools import mpi
comm = mpi.comm
rank = mpi.rank
@lib.with_doc(uks.get_vef... | ol.spin)
# Broadcast the large input arrays here.
if any(comm.allgather(dm is mpi.Message.SkippedArg)):
if rank == 0 and dm is None:
dm = mf.make_rd | m1()
dm = mpi.bcast_tagged_array(dm)
if any(comm.allgather(dm_last is mpi.Message.SkippedArg)):
dm_last = mpi.bcast_tagged_array(dm_last)
if any(comm.allgather(vhf_last is mpi.Message.SkippedArg)):
vhf_last = mpi.bcast_tagged_array(vhf_last)
ground_state = (dm.ndim == 3 and dm.sha... |
Flamacue/pretix | src/tests/plugins/banktransfer/test_import.py | Python | apache-2.0 | 4,988 | 0.001405 | from datetime import timedelta
from decimal import Decimal
import pytest
from bs4 import BeautifulSoup
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils.timezone import now
from pretix.base.models import (
Event, EventPermission, Item, Order, OrderPosition, Organizer, Quota, User,
)
... | 'reference': 'Bestellung DUMMY12345',
'amount': '23.00',
'date': '2016-01-26',
}])
env[2].refresh_from_db()
assert env[2].status == Order.STATUS_PAID
@pytest.mark.django_db
def test_huge_amount(env, j | ob):
env[2].total = Decimal('23000.00')
env[2].save()
process_banktransfers(env[0].pk, job, [{
'payer': 'Karla Kundin',
'reference': 'Bestellung DUMMY12345',
'amount': '23.000,00',
'date': '2016-01-26',
}])
env[2].refresh_from_db()
assert env[2].status == Order.ST... |
darenr/MOMA-Art | extract_concepts/concepts.py | Python | mit | 2,123 | 0.021667 | import sys
import codecs
from textblob import Blobber
from textblob.wordnet import Synset
from textblob.en.np_extractors import ConllExtractor
from collections import Counter
import re
from nltk.corpus import wordnet as wn
from nltk.corpus.reader import NOUN
import os
import string
import itertools
from nltk.corpus imp... | .read()
b = tb(text)
step1 = [t[0] for t in b.tags if t[1] in ['JJ', 'NN', 'NNS'] and not bad(t[0])]
#step2 = [wn_make_synset(word) for word in step1 if wn_make_synset(word)]
| #step3 = list(itertools.chain.from_iterable([wn_expand(ss) for ss in step2]))
print "\n"
print '=' *60
print arg
print '=' *60
print ' *', Counter(step1)
print ' *', extract_capitalized(text)
|
enkidulan/slidelint | src/slidelint/tests/checkers/font_size/TestCheckerFontSize.py | Python | apache-2.0 | 13,339 | 0.000075 | """
The *_font_gradient.pdf files have 16 slides that contain a different
sized text:
* the first slide contains 1/1 sized text - the text is as high as
the page
* the second slide contains 1/2 sized text - the text is twice smaller than
the page
* ...
* the 16th slide contains 1/16 sized text - t... | ' of 1/6.0th the page.',
'msg_name': 'font-to-small',
'page': 'Slide 12'},
{'help': 'Font is to small: Text should take up a '
'minimum of 1/6th(by | default) the page.',
'id': 'C1002',
'msg': 'Font is to small: Text should take up a minimum'
' of 1/6.0th the page.',
'msg_name': 'font-to-small',
'page': 'Slide 13'},
{'help': 'Fon... |
ampax/edx-platform | lms/djangoapps/oauth_dispatch/tests/test_views.py | Python | agpl-3.0 | 9,406 | 0.001701 | """
Tests for Blocks Views
"""
import json
import ddt
from django.test import RequestFactory, TestCase
from django.core.urlresolvers import reverse
import httpretty
from student.tests.factories import UserFactory
from third_party_auth.tests.utils import ThirdPartyOAuthTestMixin, ThirdPartyOAuthTestMixinGoogle
from ... | uthTestMixinGoogle, ThirdPartyOAuthTestMixin, _DispatchingViewTestCase):
"""
Test class for AccessTokenExchangeView
"""
view_class = views.AccessTokenExchangeView
url = reverse('exchange_access_token', kwargs={'backend': 'google-oauth2'})
def _post_body(self, user, client, token_type=None):
... | access_token': self.access_token,
}
@ddt.data('dop_client', 'dot_app')
def test_access_token_exchange_calls_dispatched_view(self, client_attr):
client = getattr(self, client_attr)
self.oauth_client = client
self._setup_provider_response(success=True)
response = self._pos... |
strahlex/machinekit | lib/python/gladevcp/gladebuilder.py | Python | lgpl-2.1 | 852 | 0.003521 | #!/usr/bin/python2
# vim: sts=4 sw=4 et
import gtk
class GladeBuilder:
""" This is wrapper around Glade object that behaves just like gtk.Builder """
def __init__(self, glade):
self.glade = glade
def get_object(self, name):
return self.glade.get_widget(n | ame)
def get_objects(self):
return self.glade.get_widget_prefix("")
def connect_signals(self, *a, **kw):
self.glade.signal_autoconnect | (*a, **kw)
def widget_name(widget):
""" Helper function to retrieve widget name """
idname = None
if isinstance(widget, gtk.Buildable):
idname = gtk.Buildable.get_name(widget)
if idname is None and hasattr(widget, 'get_name'):
# XXX: Sometimes in Glade mode on HAL_VBox previous if is tr... |
kparal/anaconda | pyanaconda/ui/tui/hubs/summary.py | Python | gpl-2.0 | 5,735 | 0.001918 | # Summary text hub
#
# Copyright (C) 2012 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the h... | self._checker.error_message)
if not incompleteSpokes:
self.close()
return None
if flags.ksprompt:
for spoke in incompleteSpokes:
log.info("kickstart installation stopped for info: %s", spoke.title)
else:
errtxt = _("The... | leted:") + \
"\n" + "\n".join(spoke.title for spoke in incompleteSpokes)
log.error("CmdlineError: %s", errtxt)
raise CmdlineError(errtxt)
# override the default prompt since we want to offer the 'b' to begin
# installation option here
return _(" Pl... |
nicko96/Chrome-Infra | appengine/findit/waterfall/masters.py | Python | bsd-3-clause | 919 | 0.002176 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
_SUPPORTED_MASTERS = [
# Tree-closer.
'chromium',
'chromium.win',
'chromium.mac',
'chromium.linux',
'chromium.chrom | iumos',
'chromium.chrome',
'chromium.memory',
# Non-tree-closer.
]
# Expli | citly list unsupported masters. Additional work might be needed in order
# to support them.
_UNSUPPORTED_MASTERS = [
'chromium.lkgr', # Disable as results are not showed on Sheriff-o-Matic.
'chromium.gpu', # Disable as too many false positives.
'chromium.memory.fyi',
'chromium.gpu.fyi',
'chromiu... |
mikelum/pyspeckit | pyspeckit/spectrum/writers/txt_writer.py | Python | mit | 1,770 | 0.011864 | from __future__ import print_function
try:
import atpy
atpyOK = True
except ImportError:
atpyOK = False
# rewrite this garbage
class write_txt(object):
def __init__(self, Spectrum):
self.Spectrum = Spectrum
def write_data(self, clobber = True):
"""
Write all fit informatio... | print("", file=f)
components = zip(*self.Spectrum.specfit.modelcomponents)
for i, element in enumerate(self.Spectrum.specfit.model):
line = "{0:10}{1:10}".format(se | lf.Spectrum.xarr[self.Spectrum.specfit.gx1:self.Spectrum.specfit.gx2][i],
round(self.Spectrum.specfit.model[i], 5))
for j, component in enumerate(components[i]): line += "{0:10}".format(round(component, 5))
line += "{0:10}".format(round(self.Spectrum.specfit.resi... |
Intel-Corporation/tensorflow | tensorflow/python/ops/linalg/linear_operator_toeplitz.py | Python | apache-2.0 | 11,235 | 0.003115 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Toeplitz, self).__init__(
dtype=self._row.dtype,
is_non_singular=is_non_singular,
is_self_adjoint=is_self_adjoint,
is_positive_definite=is_positive_definite,
is_square=is_square,
parameters=parameters,
name=name)
self._set_graph_parents([self.... | ims is not None and tensor.shape.ndims < 1:
raise ValueError("Argument {} must have at least 1 dimension. "
"Found: {}".format(name, tensor))
if row.shape[-1] is not None and col.shape[-1] is not None:
if row.shape[-1] != col.shape[-1]:
raise ValueError(
... |
wezs/uktils | uktils/third/aspn426123.py | Python | gpl-2.0 | 14,222 | 0.006961 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
################################################################################
#
# Method call parameters/return value type checking decorators.
# (c) 2006-2007, Dmitry Dvoinikov <dmitry@targeted.org>
# Distributed under BSD license.
#
# Samples:
#
# from typecheck i... | ################################################## | ######
class TupleChecker(Checker):
def __init__(self, reference):
self.reference = map(Checker.create, reference)
def check(self, value):
return reduce(lambda r, c: r or c.check(value), self.reference, False)
Checker._registered.append((lambda x: isinstance(x, tuple) and not
... |
tgrogers/gpgpu-sim_simulations | util/plotting/correl_mappings.py | Python | bsd-2-clause | 21,360 | 0.039326 | # This file is eval'd inside the plot-correlation.py file
# This maps the named GPGPU-Sim config to the card name reported in the nvprof file.
# Every time you want to correlate a new configuration, you need to map it here.
config_maps = \
{
"PUB_TITANX": "TITAN X (Pascal)",
"TITANX_P102": "TITAN X (Pascal)"... | sed_cycles_sm\"])/80 - np.average(hw[\"elapsed_cycles_sm\"])/80,"+\
"np.average(hw[\"elapsed_cycles_sm\"])/80 - np.min(hw[\"elapsed_cycles_sm\"])/80",
sim_eval="float(sim[\"gpu_tot_sim_cycle\s*=\s*(.*)\"])",
hw_name="Tesla V100-SXM2-32GB",
drophwnumbelow=0,
plottype="log... | uration\"])*837",
hw_error="np.max(hw[\"Duration\"])*837 - np.average(hw[\"Duration\"])*837,"+\
"np.average(hw[\"Duration\"])*837 - np.min(hw[\"Duration\"])*837",
sim_eval="float(sim[\"gpu_tot_sim_cycle\s*=\s*(.*)\"])",
hw_name="GeForce GTX TITAN",
drophwnumbelow=0,
... |
Beckhoff/ADS | doc/source/conf.py | Python | mit | 2,430 | 0.000412 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | ative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refe... | pported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern a... |
plotly/python-api | packages/python/plotly/plotly/validators/scattercarpet/marker/_opacitysrc.py | Python | mit | 474 | 0.00211 | import _plotly_utils.basevalidators
class OpacitysrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="opacitysrc", parent_name="scattercarpet.marker", **kwargs
):
super(OpacitysrcValidator, self).__init__(
plotly_name=plotly_name,
pa... | )
| |
CSCI1200Course/csci1200OnlineCourse | tests/functional/modules_data_source_providers.py | Python | apache-2.0 | 14,954 | 0.000134 | # 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 ... | sessment1.title = title
assessment1.weight = weight
ass | essment1.html_check_answers = html_check_answers
assessment1.properties = properties
self._course.save()
response = transforms.loads(self.get(
'/test/rest/data/assessments/items').body)
self.assertEquals(1, len(response['data']))
self.assertEquals(title, response['dat... |
nzlosh/st2 | st2api/st2api/controllers/v1/traces.py | Python | apache-2.0 | 2,445 | 0.000818 | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... | r=requester_user,
)
def get_one(self, id, requester_user):
return self._get_one_by_id(
id, requester_user=requester_user, permission_type=PermissionType.TRACE_VIEW
)
traces_controll | er = TracesController()
|
pschmitt/home-assistant | tests/components/directv/test_media_player.py | Python | apache-2.0 | 14,615 | 0.000479 | """The tests for the DirecTV Media player platform."""
from datetime import datetime, timedelta
from typing import Optional
from pytest import fixture
from homeassistant.components.directv.media_player import (
ATTR_MEDIA_CURRENTLY_RECORDING,
ATTR_MEDIA_RATING,
ATTR_MEDIA_RECORDED,
ATTR_MEDIA_START_TI... | se {}
await hass.services.async_call(MP_DOMAIN, SERVICE_TURN_OFF, data)
async def async_media_pause(
hass: HomeAssistantType, entity_id: Optional[str] = None
) -> None:
"""Send the media player the command for pause."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
await hass.services.as... | MEDIA_PAUSE, data)
async def async_media_play(
hass: HomeAssistantType, entity_id: Optional[str] = None
) -> None:
"""Send the media player the command for play/pause."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
await hass.services.async_call(MP_DOMAIN, SERVICE_MEDIA_PLAY, data)
async... |
Ensembles/ert | python/python/ert/enkf/config/field_type_enum.py | Python | gpl-3.0 | 1,042 | 0.004798 | # Copyright (C) 2016 Statoil ASA, Norway.
#
# This file is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the t | erms of the GNU General Public License a | s published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT 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 GN... |
8l/beri | cheritest/trunk/tests/fpu/test_raw_fpu_div_d32.py | Python | apache-2.0 | 1,767 | 0.003962 | #-
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_ | LICENSE_HEADER_START@
#
# Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. BERI licenses this
# file to you under the BERI Hardware-Software License, Version 1.0 (t... | cense-1-0.txt
#
# Unless required by applicable law or agreed to in writing, Work 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 Li... |
vectorgraphics/robox | bin/firstnozzle.py | Python | gpl-3.0 | 5,461 | 0.027467 | #!/usr/bin/env python
import fileinput
import sys
import re
t0first=len(sys.argv) < 2 or sys.argv[1] != "1"
t0firstLayers=sys.argv[2:]
if len(t0firstLayers) == 0:
t0firstLayers=map(str,range(0,1000))
# t0firstLayers=["0"]
numeric="([-+]?(?:(?: \d* \. \d+ )|(?: \d+ \.? )))"
rX=re.compile("X"+numeric,re.VERBOS... | max(count0+1,bisect_left(index,time-pretime) | )
if i > start and i < len(index):
buffer.insert(i,Heater+" T\n")
index.insert(i,index[i])
count += 1
count1=count
count += 1
if T == 1 and time-index[count1] > pretime:
buffer.insert(count1,Heater+" S0\n")
index.insert(count1,index[co... |
hiepthai/django-activity-stream | actstream/runtests/settings.py | Python | bsd-3-clause | 3,999 | 0.00075 | # Django settings for example_project project.
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import django
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Justin Quick', 'justquick@gmail.com'),
)
ENGINE = os.environ.get('DATABASE_ENGINE', 'django.db.ba... |
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found he... | LANGUAGE_CODE = 'en-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
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = 'media'
# URL that handles the medi... |
biberino/notes | dialogs/createNotebook.py | Python | mit | 708 | 0.007062 | # -*- coding: iso-8859-1 -*-
from gi.repository import Gtk, Gdk
class CreateNotebookDialog:
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file("dialogs/createNotebook.glade")
self.window = self.builder.get_object("window1")
self.builder.connect_signals(sel... | ect("txtTitel")
self.valid = False
self.titel = ""
Gtk.main()
#------ callbacks
def on_accept(self, *args):
self.valid = True
self.titel = self.txtTitel.get_text()
self. | window.destroy()
def on_window1_destroy(self, *args):
self.window.destroy()
Gtk.main_quit()
|
CoScale/coscale-generic-scripts | docker/docker-images.py | Python | bsd-3-clause | 1,250 | 0.0056 | #!/usr/bin/python
#
# Generic script to check how many images exist on the host
#
import sys
import json
import subprocess
# Configuration mode: return the custom metrics data should be defined
def config():
settings = {
"maxruntime": 30000, # How long the script is allowed to run
"period": 60, ... | "calctype": "Instant"
}
]
}
print json.dumps(settings)
# Data retrieval mode: return the data for the custom metrics
def data():
# Get running container images
running = int(subprocess.check_output('docker images | wc -l', shell=True, stderr=subprocess.STDOUT)) - 1
... | rgv[1] == '-c':
config()
if sys.argv[1] == '-d':
data()
|
USGSDenverPychron/pychron | docs/user_guide/operation/scripts/examples/argus/measurement/jan_unknown400_120_HT_off.py | Python | apache-2.0 | 2,553 | 0.017235 | #!Measurement
'''
baseline:
after: true
before: false
counts: 120
detector: H1
mass: 34.2
settling_time: 15.0
default_fits: nominal
equilibration:
eqtime: 40
inlet: R
inlet_delay: 3
outlet: O
use_extraction_eqtime: false
multicollect:
counts: 400
detector: H1
isotope: Ar40
peakcenter:
afte... | baseline.mass, detector=mx.baseline.detector,
settling_time=mx.baseline.settling_time)
position_magnet(mx.multicollect.isotope, detector=mx.multico | llect.detector)
#sniff the gas during equilibration
if mx.equilibration.use_extraction_eqtime:
eqt = eqtime
else:
eqt = mx.equilibration.eqtime
'''
Equilibrate is non-blocking so use a sniff or sleep as a placeholder
e.g sniff(<equilibration_time>) or sleep(<equilibration_time>)... |
transcode-de/hopper | tests/form_data_tests/conftest.py | Python | bsd-3-clause | 396 | 0.002525 | # encoding: utf-8
| import json
import pytest
from pytest_factoryboy import LazyFixture, register
from . import factories
@pytest.fixture
def elements(fixture):
return json.loads(fixture('simple_form.json'))['form']['elements']
register(factories. | FormDataFactory, 'form', elements=LazyFixture('elements'))
register(factories.FormDataFactory, 'form_with_user', author=LazyFixture('user'))
|
hekra01/mercurial | mercurial/hgweb/webcommands.py | Python | gpl-2.0 | 43,136 | 0.001437 | #
# Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import os, mimetypes, re, cgi, copy
import webutil
from mercurial... | author=fctx.user(),
date=fctx.date(),
desc=fctx.description(),
extra=fctx.extra(),
| branch=webutil.nodebranchnodefault(fctx),
parent=webutil.parents(fctx),
child=webutil.children(fctx),
rename=webutil.renamelink(fctx),
permissions=fctx.manifest().flags(f))
@webcommand('file')
def file(web, req, tmpl):
"""
/file/{revision}[/{path... |
schlizbaeda/yamuplay | pyudev/src/pyudev/_ctypeslib/__init__.py | Python | gpl-3.0 | 974 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any la... | received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._ctypeslib
========== | =======
Wrappers for libraries.
.. moduleauthor:: mulhern <amulhern@redhat.com>
"""
from . import libc
from . import libudev
|
ericlink/adms-server | playframework-dist/play-1.1/python/Lib/Cookie.py | Python | mit | 26,007 | 0.01019 | #!/usr/bin/env python
#
####
# Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software
# and its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice ... | ate an Cookie object. Although deprecated, it
is still supported by the code. See the Backward Compatibility notes
for more information.]
Once you've created your Cookie, you can add values just as if it were
a dictionary.
>>> C = Cookie.SmartCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafe... | a Cookie is the
appropriate format for a Set-Cookie: header. This is the
default behavior. You can change the header and printed
attributes by using the .output() function
>>> C = Cookie.SmartCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print C.output(header="Cookie:")... |
liveblog/liveblog | server/liveblog/tests/test_settings.py | Python | agpl-3.0 | 40 | 0 | DATE_ | FORMAT = '%Y-%m-%dT%H:%M:%S+ | 00:00'
|
kumarisneha/practice_repo | techgig/techgig_isnumeric.py | Python | mit | 117 | 0.025641 | def main():
s=raw_input()
| if s.isdigit():
print "Tru | e"
else:
print "False"
main()
|
calpaterson/recall | src/recall/search.py | Python | agpl-3.0 | 7,881 | 0.003936 | # -*- coding: utf-8 -*-
# Recall is a program for storing bookmarks of different things
# Copyright (C) 2012 Cal Paterson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version... | esponse_status": status_code}))
def update_last_indexed_time(self, mark):
mark["£last_indexed"] = int(time.time())
db = conv.db()
db.marks.update(
{"@": mark["@"], "~": mark["~"]},
{"$set": {"£last_indexed": mark["£last_indexed"]},
"$unset": "£q"})
... | record:
mark = record
else:
db = conv.db()
mark = db.marks.find_one(
{"@": record[":"]["@"], "~": record[":"]["~"]})
del mark["_id"]
return mark
def do(self):
mark = self.mark_for_record(self.record)
self.update_last_i... |
VitalPet/c2c-rd-addons | c2c_budget_chricar/wizard/chart.py | Python | agpl-3.0 | 12,006 | 0.010082 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period}
cr.execute('''
SELECT * FROM (SELECT p.id
FROM account_period p,
account_fiscalyear f,
acc... | r_id = pf.id
ORDER BY p.date_start ASC
LIMIT 1) AS period_prev_start
UNION ALL
SELECT * FROM (SELECT p.id
FROM account_period p,
account_fiscalyear f,
... |
IlfirinIlfirin/shavercoin | contrib/wallettools/walletchangepass.py | Python | mit | 220 | 0 | from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:9447")
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new w | allet passphrase: ")
access.walletpassphrasechang | e(pwd, pwd2)
|
amurzeau/streamlink-debian | tests/plugins/test_senategov.py | Python | bsd-2-clause | 827 | 0.002418 | import unittest
from streamlink.plugins.senategov import SenateGov
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlSenateGov(PluginCanHandleUrl):
__plugin__ = SenateGov
should_match = [
"https://www.foreign.senate.gov/hearings/business-meeting-082218"
"https://www.se... | :00"))
self.assertEqual(3600, SenateGov.parse_stt("01:00 | :00"))
self.assertEqual(70, SenateGov.parse_stt("1:10"))
|
colloquium/cobbler | cobbler/action_reposync.py | Python | gpl-2.0 | 22,241 | 0.006519 | """
Builds out and synchronizes yum repo mirrors.
Initial support for rsync, perhaps reposync coming later.
Copyright 2006-2007, Red Hat, Inc
Michael DeHaan <mdehaan@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
th... | c(repo)
elif repo.breed == "yum":
return self.yum_sync(repo)
#elif repo.breed == "apt":
# return self.apt_sync(repo)
elif repo.breed == "rsync":
return self.rsync_sync(repo)
else:
utils.die(self.logger,"unable to sync repo (%s), unknown or u... | d repo type (%s)" % (repo.name, repo.breed))
# ====================================================================================
def createrepo_walker(self, repo, dirname, fnames):
"""
Used to run createrepo on a copied Yum mirror.
"""
if os.path.exists(dirname) or repo['bre... |
yntantan/beetles | dbdb/tool.py | Python | apache-2.0 | 1,012 | 0 | from __future__ import print_function
import sys
import dbdb
OK = 0
BAD_ARGS = 1
BAD_VERB = 2
BAD_KEY = 3
def usage():
print("Usage:", file=sys.stderr)
print("\tpython -m dbdb.tool DBNAME get KEY", file=sys.stderr)
print("\tpython -m dbdb.tool DBNAME set KEY VALUE", file=sys.stderr)
print("\tpython... | elete KEY", file=sys.stderr)
def main(argv):
if not (4 <= len(argv) <= 5):
usage()
return BAD_ARGS
| dbname, verb, key, value = (argv[1:] + [None])[:4]
if verb not in {'get', 'set', 'delete'}:
usage()
return BAD_VERB
db = dbdb.connect(dbname)
try:
if verb == 'get':
sys.stdout.write(db[key])
elif verb == 'set':
db[key] = value
db.commit()
... |
driftx/Telephus | telephus/cassandra/constants.py | Python | mit | 187 | 0 | #
# Aut | ogenerated by Thrift Compiler (0.7.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from ttypes import *
VERSION = "19.35 | .0"
|
uday12kumar/myreview | reviews/reviews/wsgi.py | Python | mit | 1,422 | 0.000703 | """
WSGI config for reviews project.
| This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It shou | ld expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a cust... |
deKupini/erp | addons/project_issue/project_issue.py | Python | agpl-3.0 | 30,662 | 0.004925 | #-*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ate
@param context: A standard dictionary for contextual values
"""
Calendar = self.pool['resource.calendar']
res = dict((res_id, {}) for res_id in ids)
for issue in self.browse(cr, uid, ids, context=context):
values = {
'day_open': 0.0, 'day_close': ... | _close': 0.0,
'days_since_creation': 0.0, 'inactivity_days': 0.0,
}
# if the working hours on the project are not defined, use default ones (8 -> 12 and 13 -> 17 * 5), represented by None
calendar_id = None
if issue.project_id and issue.project_id.resource... |
andpp/cherrymusic | cherrymusicserver/service.py | Python | gpl-3.0 | 7,773 | 0.000129 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 - 2014 Tom Wallroth & Tilman Boerner
#
# Project page:
# http://fomori.org/cherrymusic/
# Sources on github:
# http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
# jPlayer (GPL/MIT licens... | ally dependent providers
try to instantiate each other.
"""
_master_lock = threading.Lock()
__factories = {}
@classmethod
def get(cls, provider, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
with cls._mast | er_lock:
try:
factory = cls.__factories[id(provider)]
factory.args = args
factory.kwargs = kwargs
except KeyError:
factory = cls(provider, args, kwargs)
cls.__factories[id(provider)] = factory
return fact... |
daedric/buck | scripts/diff_rulekeys_test.py | Python | apache-2.0 | 11,725 | 0.000597 | import os
import unittest
import tempfile
from diff_rulekeys import *
class MockFile(object):
def __init__(self, lines):
self._lines = lines
def readlines(self):
return self._lines
class TestRuleKeyDiff(unittest.TestCase):
def test_key_value_diff(self):
list_diff = KeyValueDiff... | srcs={"Zero": "0"}
),
makeRuleKeyLine(
name="//:One",
key="10",
srcs={"One": "0"}
),
])),
RuleKeyStructu... | 1"],
),
makeRuleKeyLine(
name="//:Zero",
key="01",
srcs={"Zero": "0"}
),
makeRuleKeyLine(
name="... |
MartinHjelmare/home-assistant | tests/helpers/test_template.py | Python | apache-2.0 | 39,409 | 0 | """Test Home Assistant template helper methods."""
import asyncio
from datetime import datetime
import unittest
import random
import math
import pytz
from unittest.mock import patch
from homeassistant.components import group
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import template
... | '%Y', 'invalid')
]
for inp, fmt, expected in tests:
if expected is None:
expected = datetime.strptime(inp, fmt)
temp = '{{ strptime(\'%s\', \'%s\') }}' % (inp, fmt)
assert str(expected) == \
template.Template(temp, self.hass).render... | imestamps to custom filter."""
now = dt_util.utcnow()
tests = [
(None, None, None, 'None'),
(1469119144, None, True, '2016-07-21 16:39:04'),
(1469119144, '%Y', True, '2016'),
(1469119144, 'invalid', True, 'invalid'),
(dt_util.as_timestamp(now),... |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/package/test_rule_001.py | Python | gpl-3.0 | 1,229 | 0.004068 |
import os
import unittest
from vsg.rules import package
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_001_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.append('')
... | e.violations))
def test_fix_rule_001(self):
oRule = package.rule_001()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule | .violations, [])
|
zenoss/ZenPacks.community.OpenSolaris | ZenPacks/community/OpenSolaris/tests/plugindata/Solaris/server3/ifconfig.py | Python | gpl-2.0 | 393 | 0.007634 | {"ifconfig":
{
"lo0": dict(
interfaceName='lo0',
mtu=8232,
| operStatus=1,
adminStatus=1,
compname="os", ),
"xnf0": dict(
| interfaceName='xnf0',
mtu=1500,
operStatus=1,
adminStatus=1,
speed=1000000000,
setIpAddresses=['10.209.191.4/23'],
compname="os", ),
}
}
|
Vijaysai005/KProject | vijay/POI_RLE/timedate.py | Python | gpl-3.0 | 709 | 0.03385 | # usr/bin/env python
"""
Created on Fri Jun 23
@author : Vijayasai S
"""
def DateMonthYear(data):
year = [] ; month = [] ; date = []
for index in range(len(data["packettimestamp"])):
year.append(int(data["packettimestamp"][index][0:4]))
month.append(in | t(data["packettimestamp"][index][5:7]))
date.append(int(data["packettimestamp"][index][8:10]))
return date, month, year
def HoursMinutesSeconds(data):
hours = [] ; minutes = [] ; seconds = []
for index in range(len(data["packettimestamp"])):
hours.append(data["packettimestamp"][index][11:13])
minutes.append(d... | kettimestamp"][index][17:-1])
return hours, minutes, seconds
|
flamingspaz/remo | remo/profiles/tasks.py | Python | bsd-3-clause | 5,501 | 0.000364 | from calendar import monthrange
from datetime import date
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.timezone import ... | data['full_name']['privacy'] == 'Public':
full_name = data['full_name']['value']
first_name, last_name = (full_name.split(' ', 1)
if ' ' in full_name else ('', full_name))
user.first_name = first_name
user.last_name = | last_name
user.userprofile.mozillian_username = data['username']
else:
user.first_name = 'Anonymous'
user.last_name = 'Mozillian'
user.userprofile.mozillian_username = ''
if len(user.last_name) > 30:
user.last_name = user.last_name[:30]
... |
louispotok/pandas | pandas/core/indexes/category.py | Python | bsd-3-clause | 31,573 | 0 | import operator
import numpy as np
from pandas._libs import index as libindex
from pandas import compat
from pandas.compat.numpy import function as nv
from pandas.core.dtypes.generic import ABCCategorical, ABCSeries
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.common import (
is_... | input ndarray
name : object
Name to be stored in the index
Attributes
----------
codes
categories
ordered
Methods
-------
rename_categories
reorder_categories
add_categories
remove_categories
remove_unused_categories
set_categories
as_ordered
as_... | yp = 'categoricalindex'
_engine_type = libindex.Int64Engine
_attributes = ['name']
def __new__(cls, data=None, categories=None, ordered=None, dtype=None,
copy=False, name=None, fastpath=False):
if fastpath:
return cls._simple_new(data, name=name, dtype=dtype)
i... |
cropleyb/pentai | pentai/ai/t_rot_standardise.py | Python | mit | 11,292 | 0.005756 | #!/usr/bin/env python
import unittest
from pentai.base.game_state import *
from pentai.base.game import *
import pentai.base.player as p_m
from pentai.base.rules import *
from pentai.ai.rot_standardise import *
class RotStandardiseTest(unittest.TestCase):
def setUp(self):
self.rules = Rules(9, "standard"... | oves("1. (8, 8)\n2. (4, 8)")
std, fwd, rev = standardise(self.game.current_state)
brd = std.get_board()
self.assertEqual(std.get_all_captured(), [0, 0, 0])
self.assertEqual(brd.get_occ((0,8)), P1)
self.assertEqual(brd.get_occ((4,8)), P2)
def test_standardise_SE_E(self):
... | game.current_state)
brd = std.get_board()
self.assertEqual(std.get_all_captured(), [0, 0, 0])
self.assertEqual(brd.get_occ((0,8)), P1)
self.assertEqual(brd.get_occ((4,8)), P2)
def test_standardise_SE_S(self):
self.game.load_moves("1. (8, 0)\n2. (4, 0)")
std, fwd, re... |
brentp/methylcode | methylcoder/tests/test_index.py | Python | bsd-3-clause | 2,099 | 0.003335 | import unittest
import os.path as op
import sys
import os
from methylcoder.fastqindex import FastQIndex, FastaIndex, FastQEntry, FastaEntry, guess_index_class
import bsddb
PATH = op.dirname(__file__)
DATA = op.join(PATH, "data")
class GuesserTest(unittest.TestCase):
def setUp(self):
self.fastq = op.join(D... | )))
def test_sequence(self):
fi = self.klass(self.path)
key, pos = iter(fi).next()
obj = fi[key]
pos = int(pos)
fh = open(self.path, "r")
fh.seek(pos)
entry = self.klass.entry_class(fh)
self.assertEquals(obj.seq, entry.seq, (obj, entry, pos))
def... | __name__ == "__main__":
unittest.main()
|
aldryn/aldryn-blog | aldryn_blog/__init__.py | Python | bsd-3-clause | 100 | 0 | # -*- coding: utf-8 -*-
__version__ = '0.5.0'
request_post_identifie | r = 'current_aldryn_b | log_entry'
|
michaelBenin/sqlalchemy | lib/sqlalchemy/testing/requirements.py | Python | mit | 17,967 | 0.001169 | # testing/requirements.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
"""Global database feature support policy.
Provides decorators to mark tests ... | ING."""
return exclusions.only_if(
lambda config: config.db.dialect.implicit_returning,
"'returning' not supported by database"
)
@property
def duplicate_names_in_cursor_description(self):
| """target platform supports a SELECT statement that has
the same name repeated more than once in the columns list."""
return exclusions.open()
@property
def denormalized_names(self):
"""Target database must have 'denormalized', i.e.
UPPERCASE as case insensitive names."""
... |
rhlobo/github_jackdaw | server/blueprints/api.py | Python | mit | 2,205 | 0.006349 | import re
import json
import flask
_URIPATH_REGEX = re.compile(r'http[s]?://[^/]+/(.*)')
def new_blueprint(github, basic_auth):
blueprint = flask.Blueprint('api', __name__, url_prefix='/api')
@blueprint.route('/status')
@basic_auth.required
def status():
data = {}
user = github.ge... | email']
data['orgs'] = []
for organization in github.get(_remove_host(user['organizations_url'])):
orgdata = {
'name': organization['login'],
'avatar': organization['avatar_url']
}
orgdata['hooks'] = github.get('orgs/%s/hooks' % organi... | data['orgs'].append(orgdata)
return flask.Response(json.dumps(data), content_type='application/json')
@blueprint.route('/hook/<org>', methods=['POST'])
@basic_auth.required
def createhook(org):
hook_registration = {
'name': 'web',
'active': True,
... |
munizao/mate-workspace-name-applet | wsname_applet.py | Python | gpl-2.0 | 7,780 | 0.0063 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Uncomment to debug. If you aren't me, I bet you want to change the paths, too.
import sys
from wsnamelet import wsnamelet_globals
if wsnamelet_globals.debug:
sys.stdout = open ("/home/munizao/hacks/wsnamelet/debug.stdout", "w", buffering=1)
sys.stderr = open ("/ho... | self._on_workspace_name_changed)
self.show_workspace_name()
def _on_workspace_name_changed(self, event):
self.show_workspace_name()
def show_workspace_name(self):
if self.workspace:
self.label.set_text(self.workspace.get_name())
self.applet.show_all()
def exit_edi... | s bit is needed because wnck is asynchronous.
while Gtk.events_pending():
Gtk.main_iteration()
return screen.get_active_workspace()
def applet_factory(applet, iid, data):
WSNameApplet(applet)
return True
MatePanelApplet.Applet.factory_main("WsnameAppletFactory",
... |
atsuyim/OpenBazaar | node/backuptool.py | Python | mit | 4,817 | 0 | import tarfile
import time
import os
import json
class BackupTool(object):
"""Simple backup utility."""
def __init__(self):
pass
@staticmethod
def backup(openbazaar_installation_path,
backup_folder_path,
on_success_callback=None,
on_error_callback... | except os.error:
pass
db_folder = os.path.join(openbazaar_installation_path, "db")
try:
with tarfile.open(output_file_path, "w:gz") as tar:
tar.add(db_folder, arcname=os.path.basename(db_folder))
except tarfile.TarError as exc:
# TODO: Install... | on_error_callback(exc)
return
if on_success_callback is not None:
on_success_callback(output_file_path)
@staticmethod
def restore(backup_tar_filepath):
raise NotImplementedError
@staticmethod
def get_installation_path():
"""Return the Project... |
zetaops/ulakbus | ulakbus/views/bap/bap_iletisim.py | Python | gpl-3.0 | 1,146 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
from ulakbus.models import AbstractRole
from ulakbus.models import Personel
from ulakbus.models import Role
from zengine.views.crud import Crud | View
from zengine.lib.translation import gettext as _
class BAPIletisimView(CrudView):
def iletisim_bilgilerini_goster(self):
self.current.output["meta"]["allow_search"] = | False
self.current.output["meta"]["allow_actions"] = False
self.output['object_title'] = _(u"BAP Koordinatörlüğü İletişim")
self.output['objects'] = [
[_(u"Ad Soyad"), _(u"Telefon"), _(u"E-posta")]
]
abstract_role = AbstractRole.objects.get(
name='Bilimsel... |
will4906/PatentCrawler | service/__init__.py | Python | apache-2.0 | 413 | 0.002421 | # -*- coding: utf-8 -*-
"""
Created on 2017/3/24
@author: will4906
"""
# from logbook import Logger |
# from service import log
# # # from service.account import *
# # # from service.proxy import *
# #
# # logger = Logger('main')
# #
# # if __name__ == '__main__':
# # # stupid()
# # # update_proxy()
# # # notify_ip_address()
# # # update_cookies()
# from service.account import login
#
| # login() |
tomsik68/kodi-putlocker-tvshows | examples/putlockertest.py | Python | mit | 357 | 0 | from putlocker import Putlocker
putlocker = Putlocker()
series | = putlocker.search('Gold Rush')
serie = series[0]
print(serie.getName())
print(serie.getImageUrl())
print(serie.url)
print('-' * 80)
seasons = serie.getSeasons()
season = seasons[0]
episodes | = season.getEpisodes()
for episode in episodes:
print(episode.getName(), episode.getVideoLink())
|
quantumlib/Cirq | cirq-core/cirq/transformers/target_gatesets/sqrt_iswap_gateset_test.py | Python | apache-2.0 | 13,585 | 0.001914 | # Copyright 2022 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | rq.SQRT_ISWAP_INV(a, b)]),
cirq.Moment([cirq.SQRT_ISWAP(a, b)]),
cirq.Moment([cirq.SQRT_ISWAP(a | , b)]),
cirq.Moment([cirq.SQRT_ISWAP(a, b)]),
]
),
expected=cirq.Circuit(
[
cirq.Moment([cirq.SQRT_ISWAP_INV(a, b)]),
]
),
)
def test_works_with_tags():
a, b = cirq.LineQubit.range(2)
assert_optimizes(
befo... |
junranhe/tf-faster-rcnn | tools/test_net.py | Python | mit | 3,912 | 0.016616 | # --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Zheqi he, Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------- | -----
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from model.test import test_net
from model.config import cfg, cfg_from_file, cfg_from_list
from datasets.factory import get_imdb
import argparse
import pprint
import time, os, sys
impo... | et_v1 import resnetv1
from nets.mult_mobilenet import mobilenet
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file', default=None, type=str)
parser.add... |
SepehrMN/nest-simulator | pynest/nest/tests/test_weights_as_lists.py | Python | gpl-2.0 | 4,995 | 0.002002 | # -*- coding: utf-8 -*-
#
# test_weights_as_lists.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 L... | ub_weights in ref_weights for w in sub_weights]
self.assertEqual(weights.sort(), ref_weights.sort())
def test_FixedTotalNumberWeight(self):
"""Weight given as list, when connection rule is fixed_total_number"""
src = nest.Create('iaf_psc_alp | ha', 3)
tgt = nest.Create('iaf_psc_delta', 4)
conn_dict = {'rule': 'fixed_total_number', 'N': 4}
# weight has to be a list with dimension (n_conns x 1) when fixed_total_number is used
ref_weights = [1.2, -3.5, 0.4, -0.2]
syn_dict = {'weight': ref_weights}
nest.Connect(s... |
Teagan42/home-assistant | tests/components/mqtt/test_lock.py | Python | apache-2.0 | 20,567 | 0.000194 | """The tests for the MQTT lock platform."""
import json
from unittest.mock import ANY
from homeassistant.components import lock, mqtt
from homeassistant.components.mqtt.discovery import async_start
from homeassistant.const import (
ATTR_ASSUMED_STATE,
STATE_LOCKED,
STATE_UNAVAILABLE,
STATE_UNLOCKED,
)
... | ""Test optimistic mode without state topic."""
assert await async_setup_component(
hass,
lock.DOMAIN,
{
lock.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic | ",
"payload_lock": "LOCK",
"payload_unlock": "UNLOCK",
"state_locked": "LOCKED",
"state_unlocked": "UNLOCKED",
"optimistic": True,
}
},
)
state = hass.states.get("lock.test")
assert state.state is STATE_UNLO... |
strogo/turbion | turbion/bits/utils/tests/merging.py | Python | bsd-3-clause | 2,375 | 0.002947 | from datetime import date
from django.db import models
from django.test import TestCase
from django.contrib.auth.models import User
from turbion.bits.utils import merging
class MyProfile(models.Model | ):
user_ptr = models.ForeignKey(User, unique=True)
nickname = models.CharField(max_length=100)
www = models.URLField()
birth = models.DateField()
class Meta:
app_label="turbion"
class OtherProfile(models.Model):
| user = models.ForeignKey(User, unique=True)
nickname = models.CharField(max_length=100)
website = models.URLField()
dob = models.DateField()
class Meta:
app_label="turbion"
class MyProfileLayer(merging.ModelLayer):
model = MyProfile
fields = ["nickname"]
aliases = {
"site"... |
LeereNix/2chParser | optional.py | Python | bsd-3-clause | 553 | 0.003617 | import os.path
def writeToFile(element):
if not os.path.exists("interestingThreads.txt"):
outF = open("interestingThreads.txt", "w")
outF.write(string)
outF.close()
else:
outF = open("interestingThreads.txt", "a")
outF.write(string)
|
outF.close()
def countThreads(string):
number_threads = string.count("comment")
return number_threads |
def write_thread(bytes, number):
name = "thread" + number + ".html"
f = open(name, 'wb')
f.write(bytes)
f.close
|
ravibhure/ansible | lib/ansible/modules/network/aci/aci_epg_monitoring_policy.py | Python | gpl-3.0 | 4,278 | 0.002338 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | state = module.params['state']
tenant = module.params['tenant']
aci = ACIModule(module)
aci.construct_url(
root_class=dict(
aci_class='fvTenant',
aci_rn='tn-{0}'.format(tenant),
filter_target='eq(fvTenant.name, "{0}")'.format(tenant),
module_objec... | ),
subclass_1=dict(
aci_class='monEPGPol',
aci_rn='monepg-{0}'.format(monitoring_policy),
filter_target='eq(monEPGPol.name, "{0}")'.format(monitoring_policy),
module_object=monitoring_policy,
),
)
aci.get_existing()
if state == 'presen... |
dizzy54/fplbot | fplbot/settings.py | Python | mit | 4,120 | 0.001214 | """
Django settings for fplbot project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
im... | ct.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'fplbot_db',
'USER': 'fplbot',
'PASSWORD': 'fplbot0',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproje | ct.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contri... |
PixelDragon/pixeldragon | MARC21relaxed.py | Python | apache-2.0 | 30,253 | 0.007074 | # ./MARC21relaxed.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:5e592dacc0cf5bbbe827fb7d980f3324ca92c3dc
# Generated 2016-12-21 00:24:34.092428 by PyXB version 1.2.4 using Python 2.7.12.final.0
# Namespace http://www.loc.gov/MARC21/slim
from __future__ import unicode_literals
import pyxb
import pyxb.binding
import... | in this module.
@deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}."""
if default_namespace is None:
default_namespace = Namespace.fallbackNamespace()
return pyxb.binding.basis.element.AnyCreateFromDOM(n | ode, default_namespace)
# Atomic simple type: {http://www.loc.gov/MARC21/slim}recordTypeType
class recordTypeType (pyxb.binding.datatypes.NMTOKEN, pyxb.binding.basis.enumeration_mixin):
"""An atomic simple type."""
_ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'recordTypeType')
_XSDLocation = p... |
domenicosolazzo/jroc | tests/tasks/tokenizers/__init__.py | Python | gpl-3.0 | 89 | 0.011236 | from jroc.tasks.tokenizers.TokenizerTask import Senten | ceTo | kenizerTask, WordTokenizerTask
|
thrisp/flails | flask_flails/flinf.py | Python | mit | 2,087 | 0 | import pprint
class Flinf(object):
"""Information about a generated flask application. By default, provides
the url map and configuration variables of the generated application. To
return additional information pass a list to requested.
:param requested: a list of information items to extract from th... | env.__dict__
@property
def list_templates(self):
return self.app.jinja_env.list_templates()
@property
def asset_env(self):
return self.jinja_env.get('assets_environment').__dict__
|
@property
def asset_bundles(self):
return self.asset_env['_named_bundles']
def return_basic(self, item):
return getattr(self.app, item, None)
@property
def app_information(self):
"""Returns a dict containing parameters in cls.provide_information
list attribute. Thi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.