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
vedujoshi/os_tempest
tempest/services/volume/json/admin/volume_hosts_client.py
Python
apache-2.0
1,436
0
# Copyright 2013 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...
CONF.volume.build_interval self.build_timeout = CONF.volume.build_timeout def list_hosts(self, params=None): """Lists all hosts.""" url = 'os-hosts' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) ...
']
harvard-vpal/bridge-adaptivity
bridge_adaptivity/api/admin.py
Python
bsd-3-clause
148
0
from django.contrib import admin
from api.models import OAuthCli
ent @admin.register(OAuthClient) class SequenceAdmin(admin.ModelAdmin): pass
tensorflow/tfx
tfx/orchestration/experimental/kubernetes/examples/taxi_pipeline_kubernetes_test.py
Python
apache-2.0
1,478
0.003383
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Lic
ense for the specific language governing permissions and # limitations under the License. """Tests for tfx.orchestration.experimental.kubernetes.examples.taxi_pipeline_kubernetes.""" import os import tensorflow as tf from tfx.orchestration.experimental.kubernetes.examples import taxi_pipeline_kubernetes class TaxiPi...
Capitains/MyCapytain
tests/resources/collections/test_cts_collection_inheritance.py
Python
mpl-2.0
2,461
0.004876
from unittest import TestCase from MyCapytain.resources.collections.cts import XmlCtsTextInventoryMetadata, XmlCtsTextgroupMetadata, XmlCtsWorkMetadata, XmlCtsEditionMetadata, XmlCtsTranslationMetadata from MyCapytain.resources.prototypes.cts.inventory import CtsTextgroupMetadata with open("tests/testing_data/examples...
CtsWorkMetadata] * 0 + [XmlCtsEditionMetadata] * 10, "Descendant should be correctly parsed into correct types and filtered when readable" ) def test_title(self): TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA) self.assertCountEqua
l( [str(descendant.get_label()) for descendant in TI.descendants], ["Seneca, Lucius Annaeus", "de Ira", "de Vita Beata", "de consolatione ad Helviam", "de Constantia", "de Tranquilitate Animi", "de Brevitate Vitae", "de consolatione ad Polybium", "de consolatione ad Mar...
antoinecarme/pyaf
tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_PolyTrend_Seasonal_DayOfMonth_LSTM.py
Python
bsd-3-clause
166
0.048193
import te
sts.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Quantization'] , ['PolyTrend'] , ['Seasonal_D
ayOfMonth'] , ['LSTM'] );
dsm054/pandas
pandas/tests/io/test_parquet.py
Python
bsd-3-clause
37,384
0.000936
""" test parquet compat """ import datetime from io import BytesIO import os import pathlib from warnings import ( catch_warnings, filterwarnings, ) import numpy as np import pytest from pandas._config import get_option from pandas.compat import is_platform_windows from pandas.compat.pyarrow import ( pa_...
est_options_fp(df_compat, fp): # use the set option with pd.option_context("io.parquet.engine", "fastparquet"): check_round_trip(df_compat) def test_options_auto(df_compat, fp, pa): # use the set option with pd.option_context("io.parquet.engine", "auto"): check_round_trip(df_compat) ...
Impl) assert isinstance(get_engine("fastparquet"), FastParquetImpl) with pd.option_context("io.parquet.engine", "pyarrow"): assert isinstance(get_engine("auto"), PyArrowImpl) assert isinstance(get_engine("pyarrow"), PyArrowImpl) assert isinstance(get_engine("fastparquet"), FastParquetIm...
napsternxg/DeepSequenceClassification
vector_utils.py
Python
gpl-2.0
2,879
0.011462
import numpy as np from scipy.sparse import csr_matrix, coo_matrix def save_sparse_csr(filename,array): np.savez(filename,data = array.data ,indices=array.indices, indptr =array.indptr, shape=array.shape ) def load_sparse_csr(filename): loader = np.load(filename) return csr_matrix(( loader['...
in xrange(X_vec.shape[2]): try: X_vec[i,j,k,X[i,j,k]] = 1 except: print X_vec.shape, X.shape, (i, j, k), X[i,j,k] raise Exception return X_vec def onehot_to_idxarr(Y): return Y.argmax(axis=len(Y.shape) - 1) def confusion_matrix(y_pred, y...
y values. y_pred, y_true = np.array(y_pred).flatten().squeeze(), np.array(y_true).flatten().squeeze() if labels is None: labels = list(set(y_true).union(set(y_pred))) n_labels = len(labels) print "[%s] labels = %s" % (n_labels, labels) CM = coo_matrix((np.ones_like(y_true, dtype="int"), (y_...
CivicKnowledge/ambry_sources
tests/test_regression/test_issue_12.py
Python
bsd-2-clause
4,568
0.008975
# -*- coding: utf-8 -*- from ambry_sources import get_source from fs.opener import fsopendir from tests import TestBase # Tests https://github.com/CivicKnowledge/ambry_sources/issues/12 issue. class Test(TestBase): """ shapefiles (*.shp) accessor tests. """ def test_bad_row_intuition(self): from ...
ColumnSpec(position=18, width=5, name='aianhhfp', start=57), ColumnSpec(position=19, width=1, name='aihhtli', start=62), ColumnSpec(position=20, width=3, name='aitsce', start=63), ColumnSpec(position=21, width=5, name='aits', start=66), ...
ColumnSpec(position=23, width=5, name='cbsa', start=76), ColumnSpec(position=24, width=3, name='csa', start=81), ColumnSpec(position=25, width=5, name='metdiv', start=84), ColumnSpec(position=26, width=1, name='macc', start=...
pmverdugo/fiware-validator
validator/clients/puppet_client.py
Python
apache-2.0
6,861
0.000146
# -*- coding: utf-8 -*- # 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, ...
tallException(cookbook=cookbook) return msg def run_container(self, image): """Run and start a container based on the given image :param image: image to run :return: """ contname = "{}-vali
date".format(image).replace("/", "_") try: try: self.dc.remove_container(contname, force=True) LOG.info(_LI('Removing old %s container' % contname)) except NotFound: pass self.container = self.dc.create_container( ...
jgraef/pyNXT
anxt/Motor.py
Python
lgpl-3.0
5,727
0.011352
# anxt/Motor.py # pyNXT - Python wrappers for aNXT # Copyright (C) 2011 Janosch Gräf <janosch.graef@gmx.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of th...
= c_int() i = c_int() d = c_int() if (int(self.nxt.libanxt.nxt_motor_get_pid(self.nxt.handle, self.port, byref(p), byref(i), byref(d)))==0): return p.value, i.value, d.value else: return False def set_pid(self, p, i, d): return int(self.nxt.libanxt.nx...
.handle, self.port))
SurfasJones/djcmsrc3
venv/lib/python2.7/site-packages/reversion/revisions.py
Python
mit
23,546
0.00722
"""Revision management for django-reversion.""" from __future__ import unicode_literals import operator, sys from functools import wraps, reduce from threading import local from weakref import WeakValueDictionary from django.contrib.contenttypes.models import ContentType from django.core import serializers from djan...
dict( (obj, callable(data) and data() or data) for obj, data in manager_context.items() ), user = self._user, comment = self._comm...
ignore_duplicates = self._ignore_duplicates, db = self._db, ) finally: self.clear() def invalidate(self): """Marks this revision as broken, so should not be commited.""" self._assert_active() self....
google/contentbox
third_party/unidecode/x0b0.py
Python
apache-2.0
5,111
0.050088
data = ( 'ggwem', # 0x00 'ggweb', # 0x01 'ggwebs', # 0x02 'ggwes', # 0x03 'ggwess', # 0x04 'ggweng', # 0x05 'ggwej', # 0x06 'ggwec', # 0x07 'ggwek', # 0x08 'ggwet', # 0x09 'ggwep', # 0x0a 'ggweh', # 0x0b 'ggwi', # 0x0c 'ggwig', # 0x0d 'ggwigg', # 0x0e 'ggwigs...
', # 0x14 'ggwilg', # 0x15 'ggwilm', # 0x16 'ggwilb', # 0x17 'ggwils', # 0x18 'ggwilt', # 0x19 'ggwilp', # 0x1a 'ggwilh', # 0x1b 'ggwim', # 0x1c 'ggwib', # 0x1d 'ggwibs', # 0x1e 'ggwis', # 0x1f 'ggwiss', # 0x20 'ggwing', # 0x21 'ggwij', # 0x22 'ggwic', # 0x...
# 0x27 'ggyu', # 0x28 'ggyug', # 0x29 'ggyugg', # 0x2a 'ggyugs', # 0x2b 'ggyun', # 0x2c 'ggyunj', # 0x2d 'ggyunh', # 0x2e 'ggyud', # 0x2f 'ggyul', # 0x30 'ggyulg', # 0x31 'ggyulm', # 0x32 'ggyulb', # 0x33 'ggyuls', # 0x34 'ggyult', # 0x35 'ggyulp', # 0x36 ...
compas-dev/compas
src/compas/rpc/proxy.py
Python
mit
14,267
0.002383
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import time import compas import compas._os from compas.rpc import RPCServerError from compas.utilities import DataDecoder from compas.utilities import DataEncoder try: from xmlrpclib import S...
rpreter for which the functionality is installed to start the server. If possible, the proxy will try to reconnect to an already existing service Examples -------- Minimal example showing connection to the proxy server, and ensuring the server is disposed after using it: >>> from compas.r...
IP >>> with Proxy('compas.numerical') as numerical: # doctest: +SKIP ... pass # doctest: +SKIP ... # doctest: +SKIP Starting a new proxy server... # doctest: +SKIP New p...
cloudbase/coriolis
coriolis/tests/test_base.py
Python
agpl-3.0
253
0
# Copyright 2016 Cloudbase Solutions Srl # All Rights R
eserved. """Defines base class for all tests.""" from oslotest import base class CoriolisBaseTestCase(base.
BaseTestCase): def setUp(self): super(CoriolisBaseTestCase, self).setUp()
qba73/circleclient
circleclient/__init__.py
Python
mit
39
0.025641
from .circleclient im
port __version_
_
deepakkumar1984/sia-cog
vis/rcnn/dataset/imdb.py
Python
mit
13,177
0.002808
""" General image database An image database creates a list of relative image path called image_set_index and transform index to absolute image path. As to training, it is necessary that ground truth and proposals are mixed together for training. roidb basic format [image_index] ['image', 'height', 'width', 'flipped', ...
n_roidb) else: roidb = self.load_rpn_roidb(gt_roidb) return ro
idb def create_roidb_from_box_list(self, box_list, gt_roidb): """ given ground truth, prepare roidb :param box_list: [image_index] ndarray of [box_index][x1, x2, y1, y2] :param gt_roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped'] :return: roidb: [image_in...
devalbo/roboplexx
roboplexx/drivers/drvr_pololu_simple_motor_controller.py
Python
agpl-3.0
2,332
0.009005
from roboplexx import rpx_util, devices, rpx_prop __author__ = 'ajb' import serial # @rpx_util.rpx_device class PololuSimpleMotorController(devices.McBasic): def __init__(self, device_id): devices.McBasic.__init__(self, device_id) self._connection_string = "/dev/ttyACM0" self._connection...
onse = self._connection.readline() if response.startswith('.'): return response elif response.startswith('!'): raise rpx_util.RpxDevCommError("Motor error - stopped: %s" % response) elif response.startswith('?'): raise rpx_util.RpxDevCommError("Command not understoo...
response: %s" % response) #"GO" Exit Safe-Start #"F" Motor Forward #"R" Motor Reverse #"B" Motor Brake #"D" Get Variable #"L" Set Motor Limit #"V" Get Firmware Version #"X" Stop Motor
pegasus-isi/pegasus-metrics
pegasus/metrics/migrations/008_add_file_counts.py
Python
apache-2.0
428
0.009346
from pegasus.metrics import db def migrate(): cur = db.cursor() cur.execute("alter table planner_metrics add dax_input_files
int unsigned") cur.execute("alter table planner_metrics add dax_int
er_files int unsigned") cur.execute("alter table planner_metrics add dax_output_files int unsigned") cur.execute("alter table planner_metrics add dax_total_files int unsigned") db.commit(); cur.close();
spektom/incubator-airflow
airflow/models/variable.py
Python
apache-2.0
4,960
0.000605
# # 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...
eturn self._val def set_
val(self, value): if value: fernet = get_fernet() self._val = fernet.encrypt(bytes(value, 'utf-8')).decode() self.is_encrypted = fernet.is_encrypted @declared_attr def val(cls): return synonym('_val', descriptor=property(cls.get_val, cl...
valexandersaulys/airbnb_kaggle_contest
venv/lib/python3.4/site-packages/scipy/sparse/csr.py
Python
gpl-2.0
14,549
0.003368
"""Compressed Sparse Row matrix format""" from __future__ import division, print_function, absolute_import __docformat__ = "restructuredtext en" __all__ = ['csr_matrix', 'isspmatrix_csr'] import numpy as np from scipy._lib.six import xrange from ._sparsetools import csr_tocsc, csr_tobsr, csr_count
_blocks, \ get_csr_submatrix, csr_sample_values from .sputils import upcast, isintlike, IndexMixin, issequence, get_index_dtype from .compressed import _cs_matrix class csr_matrix(_cs_matrix, IndexMixin): """ Compressed Sparse Row matrix This can be instantiated in several ways: csr_matr...
S) with another sparse matrix S (equivalent to S.tocsr()) csr_matrix((M, N), [dtype]) to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype='d'. csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) where ``data``, ``row_...
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/application_gateway_sku.py
Python
mit
1,681
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
onGatewayTier :param capacity: Capacity (instance count) of an application gateway. :type capacity: int """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } def __init__(...
tier=None, capacity=None): super(ApplicationGatewaySku, self).__init__() self.name = name self.tier = tier self.capacity = capacity
jeromecc/doctoctocbot
src/community/migrations/0033_apiaccess.py
Python
mpl-2.0
2,376
0.005471
# Generated by Django 2.2.13 on 2020-10-23 00:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('community', '0032_accesslevel'), ] operations = [ migrations.CreateModel( name='ApiAccess', ...
ategory.', verbose_name='Status category')), ('status_tag', models.BooleanField(default=False, help_text='Access status tag.', verbose_name=
'Status tag')), ('status_protected', models.BooleanField(default=False, help_text='Access status from protected account.', verbose_name='Protected status')), ('community', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_access', to='community.Community'))...
veeti/stayput
stayput/tests/test_importer.py
Python
mit
478
0.002092
from os import path from stayput.import
er import import_file from stayput.tests import TestCase FIXTURE = path.abspath(path.join(path.dirname(__file__), 'fixtures', 'import_test.py')) class TestImporter(TestCase): # see fixtures/import_test.py. def test_import(self): result = import_file(FIXTURE) self.assertTrue(hasattr(result.t...
sertEqual(123, result.stuff['test'])
jeremiah-c-leary/vhdl-style-guide
vsg/vhdlFile/classify/signal_declaration.py
Python
gpl-3.0
1,368
0.005117
from vsg.token import signal_declaration as token from vsg.vhdlFile import utils from vsg.vhdlFile.classify import expression from
vsg.vhdlFile.classify import identifier_list from vsg.vhdlFile.classify import signal_kind from vsg.vhdlFile.classify import subtype_indication def detect(iToken, lObjects): ''' signal_declaration ::= signal identifier_list : subtype_indication [ signal_kind ] [ := exp
ression ] ; ''' if utils.is_next_token('signal', iToken, lObjects): return classify(iToken, lObjects) return iToken def classify(iToken, lObjects): iCurrent = utils.assign_next_token_required('signal', token.signal_keyword, iToken, lObjects) iCurrent = identifier_list.classify_until([':...
gangtao/pyflow
tests/unit/test_flow.py
Python
mit
4,506
0.000888
import unittest import sys import json import time sys.path.append('../../src') import fbp from fbp.port import Inport, Outport from fbp.node import Node from fbp.flow import Flow class TestFBPPort(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(c...
name" : "port1", "order" : 0}, {"name" : "port2", "order" : 1} ] }, "func" : "def func(x,y): return x + y" } ''' spec_obj = json.loads(spec, strict=False) node1 = Node("my.test.node1", "node1", spec_obj) node...
aflow.add_node(node1) aflow.add_node(node2) aflow.add_node(node3) aflow.add_node(node4) aflow.link(node1.id, "out", node3.id, "port1") aflow.link(node2.id, "out", node3.id, "port2") aflow.link(node2.id, "out", node4.id, "port1") node1.set_inport_value("port1",...
zkbt/mosasaurus
mosasaurus/imports.py
Python
mit
1,446
0.019364
shortcuts = {}#{'/Users/zkbt/
Cosmos/Data/Magellan/LDSS3':'...'} import craftroom.Talker craftroom.Talker.shortcuts = shortcuts #craftroom.Talker.lin
e = 200 Talker = craftroom.Talker.Talker import astropy.io.fits, astropy.io.ascii, astropy.time from astropy import time, coordinates as coord, units as u import matplotlib.pyplot as plt, numpy as np, matplotlib.animation plt.switch_backend('qt5Agg') # ignore errors from divide by zero np.seterr(divide='ignore') #i...
openstack/freezer-api
freezer_api/context.py
Python
apache-2.0
2,181
0
""" (c) Copyright 2016 Hewlett-Packard Enterprise Development Company, L.P. 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 applic...
token, # user=user, # tenant=tenant, # domain=domain, # user_domain=user_domain,
# project_domain=project_domain, is_admin=is_admin, read_only=read_only, show_deleted=show_deleted, request_id=request_id, resource_uuid=resource_uuid, overwrite=overwrite, roles=roles) @classmethod def from_dict(cls, valu...
rodrigoamaral/django-fullcalendar
demo/demo/urls.py
Python
mit
320
0.00625
from django
.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'demo.views.index', name='index'),
url(r'^all_events/', 'demo.views.all_events', name='all_events'), url(r'^admin/', include(admin.site.urls)), )
Suwmlee/XX-Net
gae_proxy/server/lib/google/appengine/tools/sdk_update_checker.py
Python
bsd-2-clause
14,750
0.006034
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy
of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in 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. # """Checks for SDK updates.""" import datetime import logging import os import socket import ss...
thenetcircle/dino
test/api/test_api_ban.py
Python
apache-2.0
2,148
0.005121
# 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 Li...
t): def test_ban_user_exists(self): self.create_and_join_room() self.set_owner() self.create_user(BaseTest.OTHER_USER_ID, BaseTest.OTHER_USER_NAME) json = sel
f.activity_for_ban() json['object']['id'] = ApiBanTest.OTHER_USER_ID response_code, _ = api.on_ban(json, as_parser(json)) self.assertEqual(ErrorCodes.OK, response_code) def create_room(self, room_id: str=None, room_name: str=None): if room_id is None: room_id = ApiBanTe...
per9000/naiveplot
src/naiveplot.py
Python
gpl-3.0
17,753
0.000282
#!/usr/bin/python """ NaivePlot - A very naive plotting library for the console """ COLORS = True try: from colorama import init from termcolor import colored init() except ImportError: COLORS = False class Point(object): """Just a point You can create it and check the value >>> p1 ...
rcle and ensure that the angle pi gives us (-1,0): >>> from math import sin, cos, pi >>> pf = ParaFunc(cos, sin) >>> p1 = pf(pi) >>> eps = 1.0/1E6 >>> (-1 - eps < p1.x < 1 + eps) and (-eps < p1.y < eps)
True """ def __init__(self, f, g): """Provide functions """ self._f = f self._g = g return def __call__(self, t): """Get the value""" return Point(self._f(t), self._g(t)) class Rectangle(ParaFunc): """Rectangle, defined by the two diagona...
flypy/flypy
flypy/runtime/obj/tests/test_pointers.py
Python
bsd-2-clause
2,989
0.000669
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import ctypes import cffi import unittest from flypy import jit, typeof, NULL from flypy.types import int32, float64 ffi = cffi.FFI() arr = ffi.new('int[3]') arr[0] = 5 arr[1] = 6 p = ffi.cast('int *', arr) class TestPointers(u...
rtFalse(f(p1, p1)) self.assertTrue(f(p1, p2)) def test_pointer_lt(self): @jit def f(p1, p2): return p1 < p2 p1, p2 = ctypes.c_void_p(2), ctypes.c_void_p(3) self.assertTrue(f(p1, p2)) self.assertFalse(f(p2, p1)) self.assertFalse(f(p1, p1)) de...
def f(p1, p2): return p1 <= p2 p1, p2 = ctypes.c_void_p(2), ctypes.c_void_p(3) self.assertTrue(f(p1, p2)) self.assertFalse(f(p2, p1)) self.assertTrue(f(p1, p1)) def test_pointer_gt(self): @jit def f(p1, p2): return p1 > p2 p1,...
openbig/odoo-contract
portal_invitation/__openerp__.py
Python
agpl-3.0
1,993
0.002514
# -*- encoding: utf-8
-*- ############################################################################## # # portal_invitation # (C) 2015 big-consulting GmbH # (C) 2015 OpenGlobe # Author: Thorsten Vocks (openBIG.org) # Author: Mikołaj Dziurzyński, Grzegorz Grzelak (OpenGlobe) # # All Rights reserved # # This program i...
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 WITHOUT ANY WARRANTY; without even the implied warranty...
huzq/scikit-learn
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
Python
bsd-3-clause
68,566
0.000642
"""Fast Gradient Boosting decision trees for classification and regression.""" # Author: Nicolas Hug from abc import ABC, abstractmethod from functools import partial import warnings import numpy as np from timeit import default_timer as time from ...base import BaseEstimator, RegressorMixin, ClassifierMixin, is_clas...
self.monotonic_cst = monotonic_cst self.categorical_features = categorical_features self.warm_start = warm_s
tart self.early_stopping = early_stopping self.scoring = scoring self.validation_fraction = validation_fraction self.n_iter_no_change = n_iter_no_change self.tol = tol self.verbose = verbose self.random_state = random_state def _validate_parameters(self): ...
google-research/tensorflow-coder
tf_coder/value_search/all_operations_test.py
Python
apache-2.0
5,136
0.004478
# Copyright 2021 The TF-Coder 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...
): operations_1 = all_operations.get_operations(include_sparse_operations=True) operations_2 = all_operations.get_operation
s(include_sparse_operations=True) self.assertEqual([op.name for op in operations_1], [op.name for op in operations_2]) def test_find_operation_with_name(self): operation = all_operations.find_operation_with_name('tf.add(x, y)') self.assertEqual(operation.name, 'tf.add(x, y)') op...
scalyr/scalyr-agent-2
scalyr_agent/builtin_monitors/kubernetes_events_monitor.py
Python
apache-2.0
40,227
0.002983
# Copyright 2018 Scalyr Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
or__ = __name__ define_config_option( __monitor__, "module", "Always ``scalyr_agent.builtin_monitors.kubernetes_events_monitor``", convert_to=six.text_type, required_option=True, ) define_config_option( __monit
or__, "max_log_size", "Optional (defaults to None). How large the log file will grow before it is rotated. If None, then the " "default value will be taken from the monitor level or the global level log_rotation_max_bytes config option. Set to zero " "for infinite size. Note that rotation is not visibl...
kg-bot/SupyBot
plugins/Asci/__init__.py
Python
gpl-3.0
2,672
0.001123
### # Copyright (c) 2011, Alex Wood # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, an...
R PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### """ Turn text into ASCII art using Fi...
FRidh/turbulence
turbulence/turbulence.py
Python
bsd-2-clause
32,642
0.002727
""" Turbulence ========== Turbulence in the atmosphere affects wave propagation. This module contains implementations of models that can be used to create random turbulence fields. References are made to the book 'Computational Atmospheric Acoustics' by 'Erik M. Salomons', published in 2001. ================ Abs...
.correlation_function(self.mu_0, self.a, self.r) ##def structure(self): ##""" ##Structure for this object. ##""" ##return self.structure_function(self.mu_0, self.a, self.r) ##def spectral_density(self): ##""" ##Spectral density for this object. ##""" ##return self.spectral_dens...
pectrum1D(Spectrum, metaclass=abc.ABCMeta): """ Abstract class for one-dimensional turbulence spectra. """ NDIM = 1 """ Amount of dimensions. """ class Spectrum2D(Spectrum, metaclass=abc.ABCMeta): """ Abstract class for two-dimensional turbulence spectra. """ NDIM = 2 ...
evangelistalab/forte
tests/pytest-methods/aci/test_aci-3.py
Python
lgpl-3.0
1,464
0.002732
import pytest import psi4 from forte.solvers import solver_factory
, HF, ActiveSpaceSolver, SpinAnalysis def test_aci_3(): """Test FCI on H4/STO-3G. Reproduces the t
est aci-1""" ref_hf_energy = -2.0310813811962456 ref_aci_energy = -2.115455548674 ref_acipt2_energy = -2.116454734743 spin_val = 1.02027340 # setup job xyz = """ H -0.4 0.0 0.0 H 0.4 0.0 0.0 H 0.1 -0.3 1.0 H -0.1 0.5 1.0 """ input = solver_factory(molecule=xyz, bas...
frapa/Schr
windows/compy/numerov.py
Python
gpl-3.0
414
0.002415
import numpy def numerov_integration(domain, a, f0, f1): f = numpy.zeros(len(domain), dtype=numpy.complex) f[0] = f0 f[1] = f1 step = domain.step for i in range(2, len(domain)):
phi_i1 = f[i-1] * (2.0 + 5.0 * step**2 * a[i-1] / 6.0) phi_i2 = f[i-2] * (1.0 - step**2 * a[i-2] / 12.0)
f[i] = (phi_i1 - phi_i2) / (1.0 - step**2 * a[i] / 12.0) return f
ghchinoy/tensorflow
tensorflow/python/keras/datasets/mnist.py
Python
apache-2.0
1,993
0.002509
# Copyright 2015 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...
ermissions and # limitations under the License. # =======================
======================================================= """MNIST handwritten digits dataset. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.keras.utils.data_utils import get_file from tensorflow.python.util.tf_...
LEDS/gde-backend
wsgi/gde/features/steps/login.py
Python
gpl-3.0
1,966
0.004069
from behave import given, when, then from test.factories.user import UserFactory @given('Sou um usuario anonimo') def step_impl(context): # from django.contrib.auth.models import User # Creates a dummy user for our tests (user is not authenticated at this point) u = UserFactory(username='foo', email='foo@...
br.find_element_
by_name('action').click() @then('Sou redirecionado para a pagina de login ate que eu informe siape e senha corretos') def step_impl(context): br = context.browser # Checks redirection URL assert br.current_url.endswith('/') # assert br.find_element_by_id('main_title').text == "Login failure"
MichaelAquilina/s3backup
s4/diff.py
Python
mit
1,447
0
#! -*- encoding: utf8 -*- import os import shutil import subprocess import tempfile def show_d
iff(client_1, client_2, key): if shutil.which("diff") is None: print('Missing required "diff" executable.') print("Install this
using your distribution's package manager") return if shutil.which("less") is None: print('Missing required "less" executable.') print("Install this using your distribution's package manager") return so_1 = client_1.get(key) data_1 = so_1.fp.read() so_1.fp.close() ...
Speedy1985/enigmalight
build/python/plugin/EnigmaLight/remote/api.py
Python
gpl-3.0
238
0.029412
# -*- coding: utf-8 -*-
from control import WebController class ApiController(WebController): def __init__(self, session, path = ""): WebController.__init__(self, session, path) def prePageLoad(self, re
quest): self.isJson = True
nagyistoce/geokey
geokey/contributions/models.py
Python
apache-2.0
13,888
0
from pytz import utc from datetime import datetime from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from django_pgjson.fields import JsonBField from simple_hist...
updator : geokey.users.models.User User who creates the observation status : str
Status of the contribution; one of active, review, pending or draft Return ------ geokey.contributions.models.Observation The updated observation """ if status != 'draft': self.version = self.version + 1 if properties: self....
ContinuumIO/chaco
chaco/tools/data_label_tool.py
Python
bsd-3-clause
3,421
0.001462
""" Defines the DataLabelTool class. """ # Major library imports from numpy import array, asarray, argmin, sqrt # Enthought library imports from traits.api import Any, Bool, Enum from enable.tools.drag_tool import DragTool class DataLabelTool(DragTool): """ A tool for dragging a data label. Attach this tool...
his method is called for every mouse_move event that the tool receives while the user is dragging the mouse. Implements DragTool. Moves and redraws the label. """ if self.component: label = self.component
dx = int(event.x - self.mouse_down_position[0]) dy = int(event.y - self.mouse_down_position[1]) label.label_position = (self._original_offset[0] + dx, self._original_offset[1] + dy) if self.auto_arrow_root: # Determine which...
imakin/CharMenu
v3/test/calc/progress.py
Python
mit
1,261
0.053132
#!/usr/bin/env python3 def progress(pos, scale): pixels_per_char = 6 max_chars = 16 max_progress = max_chars * pixels_per_char progress = (pos/scale)*max_p
rogress print(int ((pos/scale)*max_chars) ) for i in range(0,max_chars): if i==int((pos/scale)*max_chars): print("|",end="") elif i< ((pos/scale)*max_chars): print(" ",end="") elif i> ((pos/scale)*max_chars): print(" ",end="") print(
"") for x in range(0,20): progress(x,20) """ 96------------------------------------- 20 20/96*16 const uint8_t progresspixels_per_char = 6; cm_LcdGotoXY(0,1); //~ LCDprogressBar(sNum, sMax,16); //~ return; uint8_t progress=sNum; uint8_t maxprogress=sMax; uint8_t length=16; uint8_t i; uint16_t pixelprogre...
znick/anytask
anytask/issues/model_issue_student_filter.py
Python
mit
2,807
0.003919
# coding: utf-8 import django_filters from django import forms from django.utils.translation import ugettext_lazy
as _ from courses.models import Course from issues.models import Issue from issues.model_issue_status import IssueStatus class IssueFilterStudent(django_filters.FilterSet): is_active = django_filters.ChoiceFilter(label=_('tip_kursa'), name='task__course__i
s_active') years = django_filters.MultipleChoiceFilter( label=_('god_kursa'), name='task__course__year', widget=forms.CheckboxSelectMultiple ) courses = django_filters.MultipleChoiceFilter(label=_('kurs'), name='task__course', widget=forms.SelectMultiple) responsible = django_fil...
emburse/python-quickbooks
quickbooks/objects/vendorcredit.py
Python
mit
2,766
0.001808
from six import python_2_unicode_compatible from .base import QuickbooksBaseObject, Ref, QuickbooksManagedObject, QuickbooksTransactionEntity, \ LinkedTxnMixin, MarkupInfo from .detailline import DetailLine class ItemBasedExpenseLineDetail(QuickbooksBaseObject): class_dict = { "ItemRef": Ref, ...
"Line": DetailLine } qbo_object_name = "VendorCredit" def __init__(self): super(VendorCredit, self).__init__() self.DocNumber = "" self.TxnDate = "" self.PrivateNote = "" self.TotalAmt = 0 self.ExchangeRate = 1 self.GlobalTaxCalculation = "TaxEx...
): return str(self.TotalAmt)
thomasw/sitebucket
sitebucket/listener.py
Python
mit
14,366
0.006682
import httplib from socket import timeout from ssl import SSLError import urllib import time import collections import logging import oauth2 as oauth import simplejson as json from parser import DefaultParser, BaseParser from error import SitebucketError logger = logging.getLogger("sitebucket") PROTOCOL = 'https://'...
_WITH = ('user', 'followings') FOLLOW_LIMIT = 100 class SiteStream(object): ''' The SiteStream object establishes an authent
icated connection via OAuth to Twitter's site streams endpoint and parses the returned data. Keyword arguments: * follow -- a list of users that have authenticated your app to follow * stream_with -- 'user' or 'followings'. A value of 'user' will cause the stream to only return data about acti...
tipsi/tipsi_tools
tipsi_tools/django/models.py
Python
mit
752
0
import os import uuid class UploadNameGenerator(object): def __init__(self, model_name, field_name): self.model_name = model_name self.field_name = field_
name def deconstruct(self): return ( 'tipsi_tools.django.UploadNameGenerator', (), { 'model_name': self.model_name, 'field_name': self.field_name, }, ) def __call__(self, instance, filename): ret
urn os.path.join( 'static', self.model_name, '%s-%s-%s%s' % ( self.model_name, self.field_name, uuid.uuid1(), os.path.splitext(filename)[1], ), )
OldhamMade/exemelopy
docs/source/conf.py
Python
mit
8,269
0.007377
# -*- coding: utf-8 -*- # # exemelopy documentation build configuration file, created by # sphinx-quickstart on Thu Jan 13 15:41:30 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
d feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<rel
ease> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use ...
Tehsmash/networking-cisco
networking_cisco/tests/unit/cisco/cpnr/test_dns_relay.py
Python
apache-2.0
8,534
0.000234
# Copyright 2016 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
'255.255.255.0')) sock, addr, port = relay._open_dns_ext_socket() # check matching interface found if not first in list mock_netns.iflist.return_value = [] mock_netns.iflist.return_value.append(('eth0', '10.0.0.10', ...
sock, addr, port = relay._open_dns_ext_socket() @mock.patch('networking_cisco.plugins.cisco.' 'cpnr.cpnr_dns_relay_agent.netns') @mock.patch('socket.socket') def test_open_dns_int_socket(self, mock_socket, mock_netns): ...
bkonkle/chef-cookbooks
example_project/docs/conf.py
Python
bsd-3-clause
6,394
0.006569
# -*- coding: utf-8 -*- # # example_project documentation build configuration file, created by # sphinx-quickstart on Wed Aug 19 10:27:46 2009. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file....
ughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: eit...
' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If t...
joeribekker/restorm
restorm/resource.py
Python
mit
14,316
0.004401
import logging import urllib import re from restorm.conf import settings from restorm.rest import restify from restorm.exceptions import RestServerException from restorm.utils import reverse VALID_GET_STATUS_RESPONSES = ( 200, # OK 304, # NOT MODIFIED ) class ResourceManagerDescriptor(object): """ ...
y default, the default client is used. If no client and no default client are specified, a ``ValueError`` is raised. :param data: Any Python object that you want to have serialized and stored. """ client = client or settings.DEFAULT_CLIENT if client is...
absolute_url = rp.get_absolute_url(root=self.options.root) response = client.post(absolute_url, data) # Although 201 is the best HTTP status code for a valid POST response. if response.status_code in [200, 201, 204]: if 'Location' in response: return self.ge...
samuell/luigi
test/worker_test.py
Python
apache-2.0
69,585
0.002012
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
uigi.cmdline import luigi_run luigi.notifications.DEBUG = True class DummyTask(Task): def __init__(self, *args, **kwargs): super(DummyTask, self).__init__(*args, **kwargs) self.has_run = False def complete(self): return self.has_run def run(self): logging.debug("%s - se...
class DynamicDummyTask(Task): p = luigi.Parameter() def output(self): return luigi.LocalTarget(self.p) def run(self): with self.output().open('w') as f: f.write('Done!') time.sleep(0.5) # so we can benchmark & see if parallelization works class DynamicDummyTaskWith...
ostree/plaso
tests/parsers/mac_wifi.py
Python
apache-2.0
4,128
0.000969
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the Mac wifi.log parser.""" import unittest from plaso.formatters import mac_wifi as _ # pylint: disable=unused-import from plaso.lib import timelib from plaso.parsers import mac_wifi from tests.parsers import test_lib class MacWifiUnitTest(test_lib.ParserTes...
ortd[88]') self.assertEqual(event_object.function, u'_handleL
inkEvent') expected_string = ( u'Unable to process link event, op mode request returned -3903 ' u'(Operation not supported)') self.assertEqual(event_object.action, expected_string) self.assertEqual(event_object.text, expected_string) event_object = event_objects[5] expected_times...
tomasjames/citsciportal
app/agentex/migrations/0008_remove_datapoint_coordsource.py
Python
gpl-3.0
363
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.
db import models, migrations class Migration(migrations.Migration): dependencies = [ ('agentex', '0007_datapoint_coordsource'), ] operations = [ migrations.RemoveField( model_name='datapoint', name='coo
rdsource', ), ]
damien-dg/horizon
openstack_dashboard/test/integration_tests/regions/menus.py
Python
apache-2.0
8,108
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 # d...
def is_open(self): """Returns True if drop down menu is open, otherwise False.""" return "open" in self.src_elem.get_attribute('class') def open(self): """Opens menu by clicking on the first child of the source element.""" if self.is_open() is False: self._get_element(*s...
ted in the right side of the topbar, contains links to settings and help. """ _menu_first_child_locator = (by.By.CSS_SELECTOR, '*') _settings_link_locator = (by.By.CSS_SELECTOR, 'a[href*="/settings/"]') _help_link_locator = (by.By.CSS_SELECTOR, ...
crossbario/crossbar-examples
containers/max_message_size/publisher.py
Python
apache-2.0
1,986
0.005539
import os import threading import txaio txaio.use_twisted() from txaio import make_logger from twisted.internet.defer import inlineCallbacks from autobahn.twisted.util import sleep from autobahn.wamp.types import PublishOptions from autobahn.twisted.wamp import ApplicationSession class MyPublisher(ApplicationSessi...
self.log.info('{klass}[{ident}].__init__(config={config})', klass=self.__class__.__name__, ident=self.ident, config=str(config)) ApplicationSess
ion.__init__(self, config) @inlineCallbacks def onJoin(self, details): self.log.info('{klass}[{ident}].onJoin(details={details})', klass=self.__class__.__name__, ident=self.ident, details=details) n = 2 running = True last_error = None while runnin...
DiegoBalandran/prueba
archivo.py
Python
gpl-2.0
1,301
0.039201
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionar...
ombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exception: print "error" def main(): e=Estudiante("Diego",22) print"Hola %s" % e.hola(...
contador +=1 EXCEPTION(): def getWeb(): try: web=urllib2.urlopen("http://itjiquilpan.edu.mx/") print web.read() web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as e: print e def main(): cast() if __name__...
jdupl/iot
relays/server/gpio.py
Python
gpl-3.0
2,640
0
class AbstractPhysicalGPIO(): setup_pins = [] # store pins that are already setup def setup(self, pin_id, gpio_value_init): if pin_id not in self.setup_pins: self.setup_pins.append(pin_id) self._setup(pin_id, gpio_value_init) def output(self, pin_id, gpio_value): ...
y_state(self, pin_id, state_str): pass # def set_user_override(self, s
tate_str): # self.on_user_override = True # self.apply_state(state_str) class RPiGPIOWrapper(AbstractPhysicalGPIO): # Implementation for Raspberry pi 1 to 3 # Pin ID are BCM numbering def __init__(self): import RPi.GPIO as _GPIO self.GPIO = _GPIO self.GPIO.setwarnin...
qusp/orange3
Orange/classification/naive_bayes.py
Python
bsd-2-clause
2,302
0
import numpy as np from Orange.classification import Learner, Model from Orange.data import Instance, Storage, Table, DiscreteVariable from Orange.statistics import contingency from Orange.preprocess import Discretize __all__ = ["NaiveBayesLearner"] class NaiveBayesLearner(Learner): """ Naive Bayes classifi...
t a subclass of Orange.data.Storage.") if not all(isinstance(var, DiscreteVariable) for var in table.domain.variables): raise NotImplementedError("Only discrete variables are supported.") cont
= contingency.get_contingencies(table) class_freq = np.diag( contingency.get_contingency(table, table.domain.class_var)) return NaiveBayesModel(cont, class_freq, table.domain) class NaiveBayesModel(Model): def __init__(self, cont, class_freq, domain): super().__init__(domain) ...
leiferikb/bitpop-private
chrome/test/nacl_test_injection/buildbot_chrome_nacl_stage.py
Python
bsd-3-clause
11,702
0.011195
#!/usr/bin/python # Copyright (c) 2012 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. """Do all the steps required to build and test against nacl.""" import optparse import os.path import re import shutil import subproc...
r'c:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools', r'c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools', r'c:\Program Files\Microsoft Visual Studio 8\VC', r'c:\Program Files (x86)\Microsoft Visual St
udio 8\VC', r'c:\Program Files\Microsoft Visual Studio 8\Common7\Tools', r'c:\Program Files (x86)\Microsoft Visual Studio 8\Common7\Tools', ]) env['PATH'] += ';' + msvs_path scons = [python, 'scons.py'] elif sys.platform == 'darwin': bits = 32 scons = [python, 'scons.py'] else: ...
macbre/index-digest
indexdigest/test/core/test_database.py
Python
mit
12,002
0.002751
# -*- coding: utf8 -*- from __future__ import print_function from unittest import TestCase from indexdigest.test import DatabaseTestMixin, DatabaseWithMockedRow from indexdigest.database import DatabaseBase class TestDatabaseBase(TestCase, DatabaseTestMixin): def test_database_connect(self): conn = Dat...
ns self.assertTrue('item_id' in column_names) self.assertTrue('foo' in column_names) self.assertEqual(columns[0].name, 'item_id') self.assert
Equal(columns[0].type, 'int') self.assertIsNone(columns[0].character_set) # numeric column self.assertEqual(columns[1].name, 'foo') self.assertEqual(columns[1].type, 'varchar(16)') self.assertEqual(columns[1].character_set, 'utf8') self.assertEqual(len(columns), 2) # ...
LKSur/gestion-residuos
modules/app/utils.py
Python
gpl-3.0
16,591
0.010463
# -*- coding: utf-8 -*- # Aplicación web que gestiona los datos a completar en el formulario de Declaración Jurada de Generación de Residuos Sólidos Urbanos No Domiciliarios para presentar en la Intendencia de Montevideo # Copyright (C) 2016 LKSur S.A. # # Este programa es software libre: usted puede redistribuirlo y...
ia de la Licencia Pública General de GNU. De no se
r así, ingrese en <http://www.gnu.org/licenses/>. # # Si modifica este programa, agradecemos envíe las modificaciones a la dirección especificada en el README, con el objetivo de estudiar su incorporación a nuestra distribución. from gluon import current # The logger import logging class Utils(object): """ E...
jambonrose/DjangoUnleashed-1.8
blog/feeds.py
Python
bsd-2-clause
914
0
from datetime import datetime from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse_lazy from django.utils.feedgenerator import ( Atom1Feed, Rss201rev2Feed) from .models import Post class BasePostFeedMixin(): title = "Latest Startup Organizer Blog Posts" link = r...
= ( "Stay up to date on the " "hottest startup news.") def items(self): # uses Post.Meta.ordering return Post.objects.published()[:10] def item_title(self, item): return item.for
matted_title() def item_description(self, item): return item.short_text() def item_link(self, item): return item.get_absolute_url() class AtomPostFeed(BasePostFeedMixin, Feed): feed_type = Atom1Feed class Rss2PostFeed(BasePostFeedMixin, Feed): feed_type = Rss201rev2Feed
mindriot101/bokeh
bokeh/util/tests/test_string.py
Python
bsd-3-clause
3,770
0.005305
from __future__ import absolute_import import bokeh.util.string as bus class Test_escape(object): def test_default_quote(self): assert bus.escape("foo'bar") == "foo&#x27;bar" assert bus.escape('foo"bar') == "foo&quot;bar" def test_quote_False(self): assert bus.escape("foo'bar", quote...
o'bar", quote=("'"),) == "foo&#x27;bar" assert bus.escape('foo"bar', quote=("'"),) == 'foo"bar' assert bus.escape('foo"bar', quote=('"'),) == "foo&quot;bar" def test_amp(self): assert bus.escape("foo&bar
") == "foo&amp;bar" def test_lt(self): assert bus.escape("foo<bar") == "foo&lt;bar" def test_gt(self): assert bus.escape("foo>bar") == "foo&gt;bar" class Test_format_doctring(object): def test_no_argument(self): doc__ = "hello world" assert bus.format_docstring(doc__) == d...
skerit/romcollectionbrowser
resources/lib/nfowriter.py
Python
gpl-2.0
7,871
0.042053
import os import xbmc, xbmcgui, xbmcvfs import dialogprogress import util, helper from util import * from config import * from gamedatabase import * from xml.etree.ElementTree import * class NfoWriter: Settings = util.getSettings() def __init__
(self): pass def exportLibrary(self, gui): Logutil.log("Begin exportLibrary", util.LOG_LEVEL_INFO) gdb = gui.gdb romCollections = gui.config.romCollections progressDialog = dialogprogress.ProgressDialogGUI() p
rogressDialog.writeMsg(util.localize(32169), "", "") continueExport = True rccount = 1 for romCollection in gui.config.romCollections.values(): progDialogRCHeader = util.localize(32170) +" (%i / %i): %s" %(rccount, len(romCollections), romCollection.name) rccount = rccount + 1 Logu...
leesdolphin/rentme
aioutils/__init__.py
Python
agpl-3.0
1,441
0
import asyncio import functools def asyncio_loop(fn=None, *, loop_kwarg='loop', possible_loop_args=None): def wrapper(fn): @functools.wraps(fn) def aiofn(*args, **kwargs): loop = asyncio.get_event_loop() for arg_name in possible_loop_args: if kwargs.get(arg_...
return wrapper(fn) def asyncio_loop_method(fn=None, *, loop_kwarg='loop', loop_attr='loop', possible_loop_args=None): def wrapper(fn): @functools.wraps(fn) def aiofn(self, *args, **kwargs): loop = getattr(self, loop_attr, None) loop = loop or asy...
loop = kwargs.pop(arg_name) break kwargs[loop_kwarg] = loop return fn(self, *args, **kwargs) return aiofn if possible_loop_args is None: possible_loop_args = (loop_kwarg, ) if fn is None: return wrapper else: return w...
spradeepv/dive-into-python
decorators/passing_args_to_decorators.py
Python
mit
753
0.005312
""" Passing arguments to decorators ------------------------------ Looking back at the example before the one above, you can
notice how redundant the decorators in the example are. 3 decorators(div_decorate, p_decorate, strong_decorate) each with the same functionality but wrapping the string with different tags. We can definitely do much better than that. Why not have a more general implementation for one that takes the tag to wrap with as ...
n "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("p") def get_text(name): return "Hello "+name print get_text("John")
DigiThinkIT/stem
stem/descriptor/extrainfo_descriptor.py
Python
lgpl-3.0
35,907
0.008271
# Copyright 2012-2014, Damian Johnson and The Tor Project # See LICENSE for licensing information """ Parsing for Tor extra-info descriptors. These are published by relays whenever their server descriptor is published and have a similar format. However, unlike server descriptors these don't contain information that To...
_dl. ===================== =========== DirStat Description =====
================ =========== **COMPLETE** requests that completed successfully **TIMEOUT** requests that didn't complete within a ten minute timeout **RUNNING** requests still in process when measurement's taken **MIN** smallest rate at which a descriptor was downloade...
bendavis78/django-storages
storages/backends/s3boto.py
Python
bsd-3-clause
18,318
0.000819
import os import mimetypes from gzip import GzipFile import datetime try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # noqa from django.core.files.base import File from django.core.files.storage import Storage from django.core.exceptions import ImproperlyConfigured, Susp...
self._file is None: self._file = StringIO() if 'r' in self._mode: self._is_dirty = False self.key.get_contents_to_file(self._file) self._file.seek(0) if self._storage.gzip and self.key.content_encoding == 'gzip': self._...
le = property(_get_file, _set_file) def read(self, *args, **kwargs): if 'r' not in self._mode: raise AttributeError("File was not opened in read mode.") return super(S3BotoStorageFile, self).read(*args, **kwargs) def write(self, *args, **kwargs): if 'w' not in self._mode: ...
npdoty/pywikibot
scripts/listpages.py
Python
mit
9,907
0
#!/usr/bin/python # -*- coding: utf-8 -*- r""" Print a list of pages, as defined by page generator parameters. Optionally, it also prints page content to STDOUT or save it to a file in the current directory. These parameters are supported to specify which pages titles to print: -format Defines the output format....
self, page, outputlang=None, default='******'): """ Constructor. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace before title should be translated. Page ns will be searched in Site(outpu...
and, if found, its custom name will be used in page.title(). @type outputlang: str or None, if no translation is wanted. @param default: default string to be used if no corresponding namespace is found when outputlang is not None. """ self.site = page._link.site sel...
yland/coala
coalib/misc/MutableValue.py
Python
agpl-3.0
80
0
cla
ss MutableValue: def __init__(self, val=Non
e): self.value = val
luotao1/Paddle
python/paddle/fluid/tests/unittests/npu/test_argsort_op_npu.py
Python
apache-2.0
7,907
0.001265
# Copyright (c) 2021 PaddlePaddle 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 appli...
: def init_direction(self): self.descending = True class TestArgsortOpDescendingAxis2NPUINT64(TestArgsortOpAxis2NPUINT64): def init_direction(self): self.descending = True class TestArgsortOpDescendingAxisNeg1NPUINT64(TestArgsortOpAxisNeg1NPUINT6
4): def init_direction(self): self.descending = True class TestArgsortOpDescendingAxisNeg2NPUINT64(TestArgsortOpAxisNeg2NPUINT64): def init_direction(self): self.descending = True if __name__ == '__main__': unittest.main()
Instawork/django-rest-framework-json-api
example/tests/test_utils.py
Python
bsd-2-clause
882
0
""" Test rest_framework_json_api's utils functions. """ from rest_framework_json_api import utils from ..seriali
zers import EntrySerializer from ..tests import TestBase class GetRelatedResourceTests(TestBase): """ Ensure the `get_related_resource_type` function returns correct types. """ def test_reverse_relation(self): """ Ens
ure reverse foreign keys have their types identified correctly. """ serializer = EntrySerializer() field = serializer.fields['comments'] self.assertEqual(utils.get_related_resource_type(field), 'comments') def test_m2m_relation(self): """ Ensure m2ms have their type...
benjaoming/pytosquatting
pingback/admin.py
Python
gpl-3.0
446
0.002242
from django.contrib import admin from . import models @admin.register(models.Pingback) class PingbackAdmin(admin.ModelAdmin): list_display = ('package_name', 'unique_count', 'count', 'last_seen', 'first_seen', 'blocked', 'first_seen_blocked') list_filter = ('repository', 'last_seen', '
blocked') @admin.regis
ter(models.PingbackIP) class PingbackIPAdmin(admin.ModelAdmin): list_display = ('ip', 'count', 'last_seen', 'pingback')
BlogomaticProject/Blogomatic
opt/blog-o-matic/usr/lib/python/Bio/GenBank/Scanner.py
Python
gpl-2.0
79,599
0.007802
# Copyright 2007-2010 by Peter Cock. All rights reserved. # Revisions copyright 2010 by Uri Laserson. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. # # This code is NOT intend...
/feature_table.html # http://www.ncbi.nlm.nih.gov/projects/collab/FT/index.html # ftp://ftp.ncbi.nih.gov/genbank/docs/ # # 17-MAR-2009: added wgs, wgs_scafld for GenBank whole genome shotgun master records. # These are GenBank files that summarize the content of a project, and provide lists of # scaffold and contig fil...
ations['wgs_scafld']. These GenBank files do not have sequences. See # http://groups.google.com/group/bionet.molbio.genbank/browse_thread/thread/51fb88bf39e7dc36 # http://is.gd/nNgk # for more details of this format, and an example. # Added by Ying Huang & Iddo Friedberg import warnings import os import re from Bio.Se...
douban/douban-sqlstore
douban/sqlstore/genconfig.py
Python
bsd-3-clause
7,051
0.001702
#!/usr/bin/env python #coding=utf8 """Utility script for generating sqlstore configs sample settings file: ################# starts ##################### default_params = { 'roles': ['m', 's', 'b', 'g', 'h'], 'rw_user': { 'user': 'rw_user', 'passwd': 'password' }, 'ro_user': { ...
tables = [r[0] for r in cursor.fetchall()] return tables def get_sqlstore_dbcnf(self, i
nstance): conf = self.get_conf(instance) return '%(host)s:%(port)d:%(db)s:%(user)s:%(passwd)s' % conf if conf else '' def gen_config(self, name, instances, extras={}, roles=['m', 's', 'b']): conf = { 'farms': {}, 'migration': {}, 'options': {}, } ...
thebachchaoproject/bachchao-server
manage.py
Python
mit
256
0
#!/usr/bi
n/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "paheraProject.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
masayuko/nikola
nikola/plugins/compile/ipynb.py
Python
mit
6,349
0.001577
# -*- coding: utf-8 -*- # Copyright © 2013-2015 Damián Avila, Chris Warrick and others. # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including without limitation #...
kernel = self.default_kernel self.logger.notice('No kernel specified, assuming "{0}".'.format(kernel)) IPYNB_KERNELS = {} ksm = kernelspec.KernelSpecManager() for k in ksm.find_kernel_specs(): IPYNB_KERNELS
[k] = ksm.get_kernel_spec(k).to_dict() IPYNB_KERNELS[k]['name'] = k del IPYNB_KERNELS[k]['argv'] if kernel not in IPYNB_KERNELS: self.logger.error('Unknown kernel "{0}". Maybe you mispelled it?'.format(kernel)) self.logger....
TshepangRas/tshilo-dikotla
td_maternal/admin/potential_call_admin.py
Python
gpl-2.0
2,019
0.004953
from django.contrib import admin from edc_base.modeladmin.mixins import (ModelAdminChangelistModelButtonMixin, ModelAdminRedirectMixin, ModelAdminFormInstructionsMixin, ModelAdminFormAutoNumberMixin, ModelAdminAuditFieldsMixin) from simple...
ionsMixin, ModelAdminFormAutoNumberMixin, ModelAdminAuditFieldsMixin, SimpleHistoryAdmin): list_per_page = 10 date_hierarchy =
'modified' empty_value_display = '-' @admin.register(PotentialCall) class PotentialCallAdmin(ModelAdminRedirectMixin, ModelAdminChangelistModelButtonMixin, BaseModelAdmin): fields = ['subject_identifier', 'approximate_date', 'identity', 'first_name', 'last_name', 'visi...
all-of-us/raw-data-repository
rdr_service/alembic/versions/bb8c39173631_rename_a3_manifest.py
Python
bsd-3-clause
2,033
0.003443
"""rename a3 manifest Revision ID: bb8c39173631 Revises: 98595efd597e Create Date: 2020-04-07 08:44:55.893170 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'bb8c39173631' down_revision = '98595efd597e' branch_labels = None...
op_column('genomic_set_member', 'gem_a2d_manifest_job_run_id') # ### end Alembic commands ### def downgrade_rdr():
# ### commands auto generated by Alembic - please adjust! ### op.add_column('genomic_set_member', sa.Column('gem_a2d_manifest_job_run_id', mysql.INTEGER( display_width=11), autoincrement=False, nullable=True)) op.drop_constraint(None, 'genomic_set_member', type_='foreignkey') op.create_foreign_key('...
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/test-suite/python/import_stl_runme.py
Python
gpl-3.0
144
0.006944
import import_stl_b import import_stl
_a v_new = import_stl_b.process_vector([1, 2, 3]) if v_new != (1, 2, 3, 4): raise Runt
imeError, v_new
neithere/django-navigation
_version.py
Python
lgpl-3.0
352
0
# This is the product version. # Yes, it is not available in the installed package. Unfortunately, this seems # one of the few possible workaround
s to make a) coverage.py properly detect # tests coverage, b) sphinx
and setup.py properly import the version from a # single place so that I don't have to edit it always here and there. version = '0.8.1'
MerleLK/StudentSystem
student/views.py
Python
gpl-3.0
7,522
0.001141
import hashlib from django.shortcuts import render, render_to_response, redirect from django.views.decorators.csrf import csrf_exempt from django.core.exceptions import ObjectDoesNotExist from accounts.models import User from student.models import StudentMessage, Elective from StudentSystem.customize_messages import fl...
turn render_to_response('student/show_person_info.html', {'student': student}) except ObjectDoesNotExist: flash(request, 'error', u'没有查询到您的信息') return render(request, 'student/stu_home.html') elif request.method == 'POST': try: user = User.objects.g
et(username=username) student = StudentMessage.objects.get(id=user.eno_id) student.age = request.POST['age'] student.sex = request.POST['sex'] student.grade = request.POST['grade'] student.discipline = request.POST['discipline'] student.class_code ...
saurabh6790/frappe
frappe/email/doctype/document_follow/test_document_follow.py
Python
mit
1,735
0.024784
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest import frappe.desk.form.document_follow as document_follow class TestDocumentFollow(unittest.TestCase): def test_document_follow(self): user = g...
_Test_Doc_Follow", 'doc.starts_on': frappe.utils.now(), 'doc.ends_on': frappe.utils.add_days(frappe.utils.now(),5), 'doc.description': "Hello" }) doc.insert
() return doc def get_user(): if frappe.db.exists('User', 'test@docsub.com'): doc = frappe.get_doc('User', 'test@docsub.com') else: doc = frappe.new_doc("User") doc.email = "test@docsub.com" doc.first_name = "Test" doc.last_name = "User" doc.send_welcome_email = 0 doc.document_follow_notify = 1 doc....
benosteen/RDFDatabank
rdfdatabank/tests/testlib/TestUtils.py
Python
mit
5,297
0.006041
""" Copyright (c) 2012 University of Oxford Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distr...
ts "pending" return suite of pending tests "all" return suite of unit and component tests name a single named
test to be run """ suite = unittest.TestSuite() # Named test only if select[0:3] not in ["uni","com","all","int","pen"]: if not hasattr(testclass, select): print "%s: no test named '%s'"%(testclass.__name__, select) return None suite.addTest(testclass(select)) ...
chubbymaggie/asap
test/CodeGen/SystemZ/Large/spill-02.py
Python
bsd-2-clause
2,663
0.000376
# Test cases where we spill from one frame index to another, both of which # are out of range of MVC, and both of which need emergency spill slots. # RUN: python %s | llc -mtriple=s390x-linux-gnu | FileCheck %s # CHECK: f1: # CHECK: %fallthru # CHECK-DAG: stg [[REG1:%r[0-9]+]], 8168(%r15) # CHECK-DAG: stg [[REG2:%r[0-...
The two emergency spill slots live below that, so this requires # the first 8168 bytes
to be used for the call. 160 of these bytes are # allocated for the ABI frame. There are also 5 argument registers, one of # which is used as a base pointer. args = (8168 - 160) / 8 + (5 - 1) print 'declare i64 *@foo(i64 *%s)' % (', i64' * args) print 'declare void @bar(i64 *)' print '' print 'define i64 @f1(i64 %f...
roboogle/gtkmvc3
gtkmvco/tests/adapter6.py
Python
lgpl-2.1
1,877
0.003197
""" Like adapter1.py but inside controller. """ import unittest from _importer import refresh_gui import gtkmvc3 from gtkmvc3.adapters.basic import Adapter class Model(gtkmvc3.Model): en1 = 10.0 __observables__ = ["en1"] class Controller(gtkmvc3.Controller): def on_button1_clicked(self, button): ...
.adapt(a1) a2 = Adapter(self.model, "en1") a2.connect_widget(self.view["label1"], setter=lambda w,v: w.set_markup("<big><b>%.2f</b></big>" % v)) self.adapt(a2) self.e = a1 self.errors = [] class TwoForOne(unittest.TestCase): def setUp(self): self.m = Mo...
refresh_gui() def testArguments(self): self.assertEqual("5.0", self.v["entry1"].get_text()) self.assertEqual("10.00", self.v["label1"].get_text()) self.v["entry1"].set_text("1") self.assertEqual("2.00", self.v["label1"].get_text()) self.v["button1"].clicked() ...
moonso/genmod
genmod/annotate_models/__init__.py
Python
mit
268
0
from __future__ import absolute
_import from .make_haploblocks import get_haploblocks from .genetic_models import check_genetic_models from .model_score import get_model_score from .fix_variant import make_print_version from .variant_annotator import Va
riantAnnotator
emory-libraries/readux
readux/books/tests/models.py
Python
apache-2.0
25,398
0.004725
import os from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.test import TestCase from mock import patch, Mock import re import rdflib from rdflib import RDF from urllib import urlencode, u...
= Site.objects.get_current() self.assert_(current_site.domain in url) def test_voyant_url(self): # Volume with English Lang volume1 = SolrVolume(label='ocn460678076_V.1', pid='testpid:1234', language='eng') url = volume1.voyant_url() self.assert...
ume1.pid}) in url, 'voyant url should include volume pid as corpus identifier') self.assert_(urlencode({'archive': volume1.fulltext_absolute_url()}) in url, 'voyant url should include volume fulltext url as archive') self.assert_(urlencode({'stopList': 'stop.en.taporware.txt'}) i...
crs4/biodoop-core
test/all_tests.py
Python
gpl-3.0
1,125
0.009778
# BEGIN_COPYRIGHT # # Copyright (C) 2009-2013 CRS4. # # This file is part of biodoop-core. # # biodoop-core 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 optio...
import os, unittest if not hasattr(unittest.TestLoader, "discover"): try: import unittest2 as unittest except ImportError: raise ImportError("Python older than 2.7, please install unitte
st2") suite = unittest.defaultTestLoader.discover(os.path.dirname(__file__)) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
peterstace/project-euler
OLD_PY_CODE/project_euler_old_old/108/108.py
Python
unlicense
243
0.004115
f
rom number_theory import decomp, num_divisors, prime_sieve from itertools import count primes = prime_sieve(100000) for n in count(2): pd = decomp(n*n, primes) if num_divisors(p
d) // 2 + 1 >= 1000: print n break
vitaly-krugl/haigha
tests/unit/channel_test.py
Python
bsd-3-clause
18,150
0.000441
''' Copyright (c) 2011-2015, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/bl
ob/master/LICENSE.txt ''' from chai import Chai from collections import deque from haigha import channel from haigha.channel import Channel, SyncWrapper from haigha.except
ions import ChannelError, ChannelClosed, ConnectionClosed from haigha.classes.basic_class import BasicClass from haigha.classes.channel_class import ChannelClass from haigha.classes.exchange_class import ExchangeClass from haigha.classes.queue_class import QueueClass from haigha.classes.transaction_class import Transac...
mayfield/snowflake-connector-python
test/test_unit_s3_util.py
Python
apache-2.0
9,034
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2017 Snowflake Computing Inc. All right reserved. # import codecs import errno import glob import os import tempfile from os import path import OpenSSL from snowflake.connector.compat import PY2 from snowflake.connector.constants import (SHA256_DIGE...
test_extract_bucket_name_and_path(): """ Extra
ct bucket name and S3 path """ s3_util = SnowflakeS3Util() s3_loc = s3_util.extract_bucket_name_and_path( 'sfc-dev1-regression/test_sub_dir/') assert s3_loc.bucket_name == 'sfc-dev1-regression' assert s3_loc.s3path == 'test_sub_dir/' s3_loc = s3_util.extract_bucket_name_and_path( ...
lnielsen/zenodo
tests/unit/github/test_api.py
Python
gpl-2.0
10,739
0
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later v...
es.github.api.get_owner') @patch('zenodo.modules.github.api.get_contributors') @patch('zenodo.modules.git
hub.api.legacyjson_v1_translator') def test_github_creators_metadata(m_ljv1t, m_get_contributors, m_get_owner, defaults, contribs, owner, output): """Test 'creators' metadata fetching from GitHub.""" m_get_contributors.return_value = contribs m_get_owner.return_value = owne...
uptimejp/postgres-toolkit
postgres_toolkit/pt_snap_statements.py
Python
gpl-2.0
8,892
0
#!/usr/bin/env python # coding: UTF-8 # pt-snap-statements # # Copyright(c) 2015-2018 Uptime Technologies, LLC. import getopt import os import sys import PsqlWrapper import log class SnapStatements: def build_where_clause(self, where_clause, cond): if where_clause is None: where_clause = " ...
e.") return True def get(self): if self.check() is False: return False log.debug("get: " + self.query) rs = self.psql.execute_query(self.query) avail = False rs2 = [] for r in rs: if r[0] == 'USER': avail = True ...
avail is True: rs2.append(r) log.debug("get: " + str(rs2)) self.psql.print_result(rs2) return True def usage(): print ''' Usage: {0} [option...] [interval] Options: -h, --host=HOSTNAME Host name of the postgres server -p, --port=PORT Port numbe...
lesommer/oocgcm
oocgcm/core/utils.py
Python
apache-2.0
7,828
0.006771
#!/usr/bin/env python # """oocgcm.core.utils Define various generic utilities tools to be used in several submodules. """ import numpy as np import xarray as xr import dask.array as da # #=========================== General purpose ================================== # class _SliceGetter(object): """Class that re...
return True def _assert_and_set_grid_location_attribute(xarr,grid_location=None): """Assert whether xarr holds an extra attribute 'grid_location' that equals grid_location. If xarr does not have such extra-attribute, create one with value grid_location. Parameters ---------- xarr : xarray...
bing the grid location : eg 'u','v','t','f'... """ if xarr.attrs.has_key('grid_location'): assert ( xarr.attrs['grid_location'] == grid_location ) else: xarr.attrs['grid_location'] = grid_location def check_input_array(xarr,shape=None,chunks=None,\ grid_location=None,...