commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
023e88f264274211674a100820d590dcee694445
Allow neutron network list to be used as pillar data
salt/pillar/neutron.py
salt/pillar/neutron.py
Python
0.000001
@@ -0,0 +1,2582 @@ +# -*- coding: utf-8 -*-%0A'''%0AUse Openstack Neutron data as a Pillar source. Will list all networks listed%0Ainside of Neutron, to all minions.%0A%0A.. versionadded:: Beryllium%0A%0A:depends: - python-neutronclient%0A%0AA keystone profile must be used for the pillar to work (no generic keystone%0Aconfiguration here).%0A%0A For example::%0A%0A my openstack_config:%0A keystone.user: 'admin'%0A keystone.password: 'password'%0A keystone.tenant: 'admin'%0A keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'%0A keystone.region_name: 'RegionOne'%0A keystone.service_type: 'network'%0A%0AAfter the profile is created, configure the external pillar system to use it.%0A%0A.. code-block:: yaml%0A%0A ext_pillar:%0A - neutron: my_openstack_config%0A%0AUsing these configuration profiles, multiple neutron sources may also be used:%0A%0A.. code-block:: yaml%0A%0A ext_pillar:%0A - neutron: my_openstack_config%0A - neutron: my_other_openstack_config%0A%0ABy default, these networks will be returned as a pillar item called%0A%60%60networks%60%60. In order to have them returned under a different name, add the%0Aname after the Keystone profile name:%0A%0A ext_pillar:%0A - neutron: my_openstack_config neutron_networks%0A'''%0A%0A# Import python libs%0Aimport logging%0A%0A# Import third party libs%0Atry:%0A import salt.utils.openstack.neutron as suoneu%0A HAS_NEUTRON = True%0Aexcept NameError as exc:%0A HAS_NEUTRON = False%0A%0A# Set up logging%0Alog = logging.getLogger(__name__)%0A%0A%0Adef __virtual__():%0A '''%0A Only return if python-neutronclient is installed%0A '''%0A return HAS_NEUTRON%0A%0A%0Adef _auth(profile=None):%0A '''%0A Set up neutron credentials%0A '''%0A credentials = __salt__%5B'config.option'%5D(profile)%0A kwargs = %7B%0A 'username': credentials%5B'keystone.user'%5D,%0A 'password': credentials%5B'keystone.password'%5D,%0A 'tenant_name': credentials%5B'keystone.tenant'%5D,%0A 'auth_url': credentials%5B'keystone.auth_url'%5D,%0A 'region_name': credentials.get('keystone.region_name', None),%0A 'service_type': credentials%5B'keystone.service_type'%5D,%0A %7D%0A%0A return suoneu.SaltNeutron(**kwargs)%0A%0A%0Adef ext_pillar(minion_id,%0A pillar, # pylint: disable=W0613%0A conf):%0A '''%0A Check neutron for all data%0A '''%0A comps = conf.split()%0A%0A profile = None%0A if comps%5B0%5D:%0A profile = comps%5B0%5D%0A%0A conn = _auth(profile)%0A ret = %7B%7D%0A networks = conn.list_networks()%0A for network in networks%5B'networks'%5D:%0A ret%5Bnetwork%5B'name'%5D%5D = network%0A%0A if len(comps) %3C 2:%0A comps.append('networks')%0A return %7Bcomps%5B1%5D: ret%7D%0A
6df4cdd8fe629fabadd792d0b7507a57f9dc37b7
refactor tests
tests/test_helper_functions.py
tests/test_helper_functions.py
import quora def test_try_cast_int(): assert quora.try_cast_int('200 Upvotes') == 200 assert quora.try_cast_int('2k Upvotes') == 2000 assert quora.try_cast_int('2 K Upvotes') == 2000 assert quora.try_cast_int('2.3k Upvotes') == 2300 assert quora.try_cast_int('2.3 K Upvotes') == 2300 assert quora.try_cast_int('<span class="count">3</span>') == 3 test_try_cast_int()
Python
0.00002
@@ -11,60 +11,93 @@ ra%0A%0A -def test_try_cast_int():%0A%09assert quora.try_cast_int( +class TestHelperFunctions:%0A def test_try_cast_int(self):%0A input_strings = %5B '200 @@ -109,299 +109,270 @@ tes' -) == 200%0A%09assert quora.try_cast_int('2k Upvotes') == 2000%0A%09assert quora.try_cast_int('2 K Upvotes') == 2000%0A%09assert quora.try_cast_int('2.3k Upvotes') == 2300%0A%09assert quora.try_cast_int('2.3 K Upvotes') == 2300%0A%09assert quora.try_cast_int('%3Cspan class=%22count%22%3E3%3C/span%3E') == 3%0A%0Atest_try_cast_int() +, '2k Upvotes', '2 K Upvotes', '2.3k Upvotes', '2.3 K Upvotes', '%3Cspan class=%22count%22%3E3%3C/span%3E'%5D%0A expected = %5B200, 2000, 2000, 2300, 2300, 3%5D%0A%0A for i in range(0, len(input_strings)):%0A assert quora.try_cast_int(input_strings%5Bi%5D) == expected%5Bi%5D
2b0ade5407902c2b8d8a0853967bbe01c9e38e7e
test file for paraview functions
tests/unit/io/test_paraview.py
tests/unit/io/test_paraview.py
Python
0
@@ -0,0 +1,1024 @@ +import os%0Aimport sys%0Aimport pytest%0Aimport numpy as np%0Aimport porespy as ps%0Aimport openpnm as op%0Afrom numpy.testing import assert_allclose%0Aimport psutil%0Afrom openpnm.io.__paraview__ import export_data%0Afrom openpnm.io.__paraview__ import open_paraview%0A%0Aclass ExportTest():%0A%0A def setup_class(self):%0A self.path = os.path.dirname(os.path.abspath(sys.argv%5B0%5D))%0A %0A def test_export_data(self):%0A im = ps.generators.blobs(shape=%5B50, 50, 50%5D, spacing=0.1)%0A export_data(im=im, filename='test_to_paraview.pvsm')%0A os.remove('test_to_paraview.pvsm')%0A%0A def test_open_paraview(self):%0A open_paraview(filename='../fixtures/image.pvsm')%0A if sys.platform != %22darwin%22:%0A assert %22paraview%22 in (p.name().split('.')%5B0%5D for p in psutil.process_iter())%0A%0A%0Aif __name__ == %22__main__%22:%0A t = ExportTest()%0A self = t%0A t.setup_class()%0A for item in t.__dir__():%0A if item.startswith(%22test%22):%0A print(f%22Running test: %7Bitem%7D%22)%0A t.__getattribute__(item)()%0A
1f281a1279b7b185559d9d267a69ea24024c633e
Transpose of a Matrix
math/Matrix/Python/transpose.py
math/Matrix/Python/transpose.py
Python
0
@@ -0,0 +1,1048 @@ +%22%22%22 Transpose of a Matrix%0D%0A%0D%0AFollowing is a simpler code for Transpose%0D%0Aof a matrix using the NUMPY library of Python.%0D%0A%0D%0AThe transpose of a matrix swaps its rows and columns:%0D%0A%0D%0A %5B%5Ba,b,c%5D,%0D%0A %5Bd,e,f%5D%5D%0D%0A%E2%80%8B%0D%0AWould be written as :%0D%0A%0D%0A %5B%5Ba,d%5D,%0D%0A %5Bb,e%5D,%0D%0A %5Bc,f%5D%5D%0D%0A%0D%0AThis comes in extensive use when we matrices in ML. %22%22%22%0D%0A%0D%0A%0D%0Aimport numpy as np%0D%0A%0D%0A# We have imported the NUMPY library using above SYNTAX.%0D%0A%0D%0Adef Transpose(mat):%0D%0A%0D%0A# Here we create a function Transpose.%0D%0A arr=np.array(mat)%0D%0A%0D%0A # We convert the incoming matrix in an array form using np.array() function.%0D%0A %0D%0A a=arr.T%0D%0A%0D%0A # Here we just use the inbuild function of the NUMPY library.%0D%0A return a%0D%0A%0D%0A%22%22%22 Let us declare a matrix and we will see the output%0D%0A%0D%0A%3E%3E%3Emat=%5B%5B1,2,3%5D,%0D%0A %5B4,5,6%5D%5D%0D%0A%3E%3E%3Eprint(Transpose(mat)) %0D%0A%0D%0AOUTPUT:%0D%0A%3E%3E%3E %0D%0A%5B%5B1 4%5D%0D%0A %5B2 5%5D%0D%0A %5B3 6%5D%5D%0D%0A%0D%0A%0D%0A%3E%3E%3Emat=%5B%5B'a','b','c'%5D,%0D%0A %5B'd','e','f'%5D%5D%0D%0A%3E%3E%3Eprint(Transpose(mat))%0D%0A%0D%0AOUTPUT:%0D%0A %3E%3E%3E %0D%0A%5B%5B'a' 'd'%5D%0D%0A %5B'b' 'e'%5D%0D%0A %5B'c' 'f'%5D%5D%0D%0A %22%22%22%0D%0A%0D%0A
f2efa222f2dd454d65a6e8cc33457b3b340ffe89
Switch AMO-dev to use FxA staging environment (#14950)
src/olympia/conf/dev/settings.py
src/olympia/conf/dev/settings.py
from olympia.lib.settings_base import * # noqa # Allow addons-dev CDN for CSP. CSP_BASE_URI += ( # Required for the legacy discovery pane. 'https://addons-dev.allizom.org', ) CDN_HOST = 'https://addons-dev-cdn.allizom.org' CSP_CONNECT_SRC += (CDN_HOST,) CSP_FONT_SRC += (CDN_HOST,) CSP_IMG_SRC += (CDN_HOST,) CSP_SCRIPT_SRC += ( CDN_HOST, ) CSP_STYLE_SRC += (CDN_HOST,) ENGAGE_ROBOTS = False EMAIL_URL = env.email_url('EMAIL_URL') EMAIL_HOST = EMAIL_URL['EMAIL_HOST'] EMAIL_PORT = EMAIL_URL['EMAIL_PORT'] EMAIL_BACKEND = EMAIL_URL['EMAIL_BACKEND'] EMAIL_HOST_USER = EMAIL_URL['EMAIL_HOST_USER'] EMAIL_HOST_PASSWORD = EMAIL_URL['EMAIL_HOST_PASSWORD'] ENV = env('ENV') RAISE_ON_SIGNAL_ERROR = True API_THROTTLING = False DOMAIN = env('DOMAIN', default='addons-dev.allizom.org') SERVER_EMAIL = 'zdev@addons.mozilla.org' SITE_URL = 'https://' + DOMAIN EXTERNAL_SITE_URL = env('EXTERNAL_SITE_URL', default='https://addons-dev.allizom.org') SERVICES_URL = env('SERVICES_URL', default='https://services.addons-dev.allizom.org') CODE_MANAGER_URL = env('CODE_MANAGER_URL', default='https://code.addons-dev.allizom.org') STATIC_URL = '%s/static/' % CDN_HOST MEDIA_URL = '%s/user-media/' % CDN_HOST SESSION_COOKIE_DOMAIN = ".%s" % DOMAIN # Domain emails should be sent to. INBOUND_EMAIL_DOMAIN = env('INBOUND_EMAIL_DOMAIN', default='addons-dev.allizom.org') DATABASES = { 'default': get_db_config('DATABASES_DEFAULT_URL'), 'replica': get_db_config('DATABASES_REPLICA_URL', atomic_requests=False), } SERVICES_DATABASE = get_db_config('SERVICES_DATABASE_URL') REPLICA_DATABASES = ['replica'] CACHES = {} CACHES['default'] = env.cache('CACHES_DEFAULT') CACHES['default']['TIMEOUT'] = 500 CACHES['default']['BACKEND'] = 'django.core.cache.backends.memcached.MemcachedCache' # noqa CACHES['default']['KEY_PREFIX'] = CACHE_KEY_PREFIX # Celery CELERY_WORKER_PREFETCH_MULTIPLIER = 1 # Update the logger name used for mozlog LOGGING['formatters']['json']['logger_name'] = 'http_app_addons_dev' csp = 'csp.middleware.CSPMiddleware' ES_TIMEOUT = 60 ES_HOSTS = env('ES_HOSTS') ES_URLS = ['http://%s' % h for h in ES_HOSTS] ES_INDEXES = dict((k, '%s_%s' % (v, ENV)) for k, v in ES_INDEXES.items()) CEF_PRODUCT = STATSD_PREFIX NEW_FEATURES = True REDIRECT_URL = 'https://outgoing.stage.mozaws.net/v1/' ADDONS_LINTER_BIN = 'node_modules/.bin/addons-linter' ALLOW_SELF_REVIEWS = True NEWRELIC_ENABLE = env.bool('NEWRELIC_ENABLE', default=False) if NEWRELIC_ENABLE: NEWRELIC_INI = '/etc/newrelic.d/%s.ini' % DOMAIN FXA_CONFIG = { 'default': { 'client_id': env('FXA_CLIENT_ID'), 'client_secret': env('FXA_CLIENT_SECRET'), # fxa redirects to https://%s/api/auth/authenticate-callback/ % DOMAIN }, 'local': { 'client_id': env('DEVELOPMENT_FXA_CLIENT_ID'), 'client_secret': env('DEVELOPMENT_FXA_CLIENT_SECRET'), # fxa redirects to http://localhost:3000/api/auth/authenticate-callback/?config=local # noqa }, } FXA_CONTENT_HOST = 'https://stable.dev.lcip.org' FXA_OAUTH_HOST = 'https://oauth-stable.dev.lcip.org/v1' FXA_PROFILE_HOST = 'https://stable.dev.lcip.org/profile/v1' DEFAULT_FXA_CONFIG_NAME = 'default' ALLOWED_FXA_CONFIGS = ['default', 'local'] FXA_SQS_AWS_QUEUE_URL = ( 'https://sqs.us-east-1.amazonaws.com/927034868273/' 'amo-account-change-dev') VAMO_URL = 'https://versioncheck-dev.allizom.org' REMOTE_SETTINGS_IS_TEST_SERVER = True
Python
0
@@ -3108,35 +3108,41 @@ https:// -stable.dev.lcip.org +accounts.stage.mozaws.net '%0AFXA_OA @@ -3170,28 +3170,25 @@ auth --stable.dev.lcip.org +.stage.mozaws.net /v1' @@ -3220,40 +3220,38 @@ s:// -stable.dev.lcip.org/profile +profile.stage.mozaws.net /v1'%0A +%0A DEFA @@ -3410,15 +3410,8 @@ 273/ -'%0A ' amo- @@ -3429,16 +3429,17 @@ nge-dev' +%0A )%0A%0AVAMO_
bf98a5d06436a905aa5710db4a60f1e6b7c8f7fc
Add link local plugin
services/presence2/linklocal_plugin.py
services/presence2/linklocal_plugin.py
Python
0
@@ -0,0 +1,940 @@ +# Copyright (C) 2007, Red Hat, Inc.%0A# Copyright (C) 2007, Collabora Ltd.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU General Public License as published by%0A# the Free Software Foundation; either version 2 of the License, or%0A# (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU General Public License for more details.%0A#%0A# You should have received a copy of the GNU General Public License%0A# along with this program; if not, write to the Free Software%0A# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA%0A%0Aimport gobject%0A%0Aclass LinkLocalPlugin(gobject.GObject):%0A def __init__(self, registry):%0A gobject.GObject.__init__(self)%0A self._registry = registry%0A
2ab796aeb53e650b8a1dd828b5daaca16850d9c3
Add tests for APNS message.
zerver/tests/test_push_notifications.py
zerver/tests/test_push_notifications.py
Python
0
@@ -0,0 +1,1636 @@ +import mock%0A%0Afrom django.test import TestCase%0Afrom django.conf import settings%0A%0Afrom zerver.models import PushDeviceToken, UserProfile%0Afrom zerver.models import get_user_profile_by_email%0Afrom zerver.lib import push_notifications as apn%0Afrom zerver.lib.redis_utils import get_redis_client%0A%0A%0Aclass PushNotificationTest(TestCase):%0A def setUp(self):%0A email = 'hamlet@zulip.com'%0A self.redis_client = get_redis_client()%0A apn.connection = apn.get_connection('fake-cert', 'fake-key')%0A apn.dbx_connection = apn.get_connection('fake-cert', 'fake-key')%0A self.user_profile = get_user_profile_by_email(email)%0A self.tokens = %5B'aaaa', 'bbbb'%5D%0A for token in self.tokens:%0A PushDeviceToken.objects.create(%0A kind=PushDeviceToken.APNS,%0A token=apn.hex_to_b64(token),%0A user=self.user_profile,%0A ios_app_id=settings.ZULIP_IOS_APP_ID)%0A%0A def tearDown(self):%0A for i in %5B100, 200%5D:%0A self.redis_client.delete(apn.get_apns_key(i))%0A%0Aclass APNsMessageTest(PushNotificationTest):%0A @mock.patch('random.getrandbits', side_effect=%5B100, 200%5D)%0A def test_apns_message(self, mock_getrandbits):%0A apn.APNsMessage(self.user_profile, self.tokens, alert=%22test%22)%0A data = self.redis_client.hgetall(apn.get_apns_key(100))%0A self.assertEqual(data%5B'token'%5D, 'aaaa')%0A self.assertEqual(int(data%5B'user_id'%5D), self.user_profile.id)%0A data = self.redis_client.hgetall(apn.get_apns_key(200))%0A self.assertEqual(data%5B'token'%5D, 'bbbb')%0A self.assertEqual(int(data%5B'user_id'%5D), self.user_profile.id)%0A
f491db91ed2608698d2d91558f41f544819684bf
Add python-copy to calvinsys
calvin/calvinsys/native/python-copy.py
calvin/calvinsys/native/python-copy.py
Python
0.000018
@@ -0,0 +1,1103 @@ +# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2015 Ericsson AB%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Aimport copy%0Aimport types%0A%0A%0Aclass Copy(object):%0A%0A _copy = %7B%0A name: getattr(copy, name)%0A for name in dir(copy) if not name.startswith('_') and isinstance(getattr(copy, name), types.FunctionType)%0A %7D%0A%0A def __getattr__(self, attr):%0A if attr in self._copy:%0A return self._copy%5Battr%5D%0A raise AttributeError(attr)%0A%0A def show_module(self):%0A import inspect%0A print inspect.getsource(copy)%0A%0A%0Adef register(node=None, actor=None):%0A return Copy()%0A
689cd96b4ea284fcc526805d978e58c01e4198aa
FIX removed isotropic spectral clustering test because of arpack problems.
sklearn/cluster/tests/test_spectral.py
sklearn/cluster/tests/test_spectral.py
"""Testing for Spectral Clustering methods""" from cPickle import dumps, loads import nose import numpy as np from numpy.testing import assert_equal from nose.tools import assert_raises from scipy import sparse from sklearn.datasets.samples_generator import make_blobs from sklearn.utils.testing import assert_greater from sklearn.cluster import SpectralClustering, spectral_clustering from sklearn.cluster.spectral import spectral_embedding from sklearn.metrics import pairwise_distances, adjusted_rand_score def test_spectral_clustering(): S = np.array([[1, 5, 2, 1, 0, 0, 0], [5, 1, 3, 1, 0, 0, 0], [2, 3, 1, 1, 0, 0, 0], [1, 1, 1, 1, 2, 1, 1], [0, 0, 0, 2, 2, 3, 2], [0, 0, 0, 1, 3, 1, 4], [0, 0, 0, 1, 2, 4, 1], ]) for mat in (S, sparse.csr_matrix(S)): model = SpectralClustering(random_state=0, n_clusters=2, affinity='precomputed').fit(mat) labels = model.labels_ if labels[0] == 0: labels = 1 - labels assert_equal(labels, [1, 1, 1, 0, 0, 0, 0]) model_copy = loads(dumps(model)) assert_equal(model_copy.n_clusters, model.n_clusters) assert_equal(model_copy.mode, model.mode) assert_equal(model_copy.random_state.get_state(), model.random_state.get_state()) assert_equal(model_copy.labels_, model.labels_) def test_spectral_amg_mode(): # Test the amg mode of SpectralClustering centers = np.array([ [0., 0., 0.], [10., 10., 10.], [20., 20., 20.], ]) X, true_labels = make_blobs(n_samples=100, centers=centers, cluster_std=1., random_state=42) D = pairwise_distances(X) # Distance matrix S = np.max(D) - D # Similarity matrix S = sparse.coo_matrix(S) try: from pyamg import smoothed_aggregation_solver amg_loaded = True except ImportError: amg_loaded = False if amg_loaded: labels = spectral_clustering(S, n_clusters=len(centers), random_state=0, mode="amg") # We don't care too much that it's good, just that it *worked*. # There does have to be some lower limit on the performance though. assert_greater(np.mean(labels == true_labels), .3) else: assert_raises(ValueError, spectral_embedding, S, n_components=len(centers), random_state=0, mode="amg") def test_spectral_unknown_mode(): # Test that SpectralClustering fails with an unknown mode set. centers = np.array([ [0., 0., 0.], [10., 10., 10.], [20., 20., 20.], ]) X, true_labels = make_blobs(n_samples=100, centers=centers, cluster_std=1., random_state=42) D = pairwise_distances(X) # Distance matrix S = np.max(D) - D # Similarity matrix S = sparse.coo_matrix(S) assert_raises(ValueError, spectral_clustering, S, n_clusters=2, random_state=0, mode="<unknown>") def test_spectral_clustering_sparse(): # We need a large matrice, or the lobpcg solver will fallback to its # non-sparse and buggy mode raise nose.SkipTest("XFailed Test") S = np.array([[1, 5, 2, 2, 1, 0, 0, 0, 0, 0], [5, 1, 3, 2, 1, 0, 0, 0, 0, 0], [2, 3, 1, 1, 1, 0, 0, 0, 0, 0], [2, 2, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 2, 1, 1, 1], [0, 0, 0, 0, 1, 2, 2, 3, 3, 2], [0, 0, 0, 0, 2, 2, 3, 3, 3, 4], [0, 0, 0, 0, 1, 3, 3, 1, 2, 4], [0, 0, 0, 0, 1, 3, 3, 2, 1, 4], [0, 0, 0, 0, 1, 2, 4, 4, 4, 1], ]) S = sparse.coo_matrix(S) labels = SpectralClustering(random_state=0, n_clusters=2, affinity='precomputed').fit(S).labels_ if labels[0] == 0: labels = 1 - labels assert_greater(np.mean(labels == [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]), .9) def test_affinities(): X, y = make_blobs(n_samples=40, random_state=1, centers=[[1, 1], [-1, -1]], cluster_std=0.4) # nearest neighbors affinity sp = SpectralClustering(n_clusters=2, affinity='nearest_neighbors', random_state=0) labels = sp.fit(X).labels_ assert_equal(adjusted_rand_score(y, labels), 1) sp = SpectralClustering(n_clusters=2, gamma=2, random_state=0) labels = sp.fit(X).labels_ assert_equal(adjusted_rand_score(y, labels), 1) def test_isotropic(): # test that no cluster with a single point is created X, y = make_blobs(n_samples=40, random_state=1, centers=[[1, 1]], cluster_std=0.1) sp = SpectralClustering(n_clusters=2, gamma=0.2, random_state=0) labels = sp.fit(X).labels_ assert_greater(np.min(np.bincount(labels)), 10) X = np.ones((10, 9)) sp = SpectralClustering(n_clusters=2, gamma=0.2, random_state=0) labels = sp.fit(X).labels_ assert_greater(np.min(np.bincount(labels)), 3)
Python
0
@@ -4598,514 +4598,4 @@ 1)%0A -%0A%0Adef test_isotropic():%0A # test that no cluster with a single point is created%0A X, y = make_blobs(n_samples=40, random_state=1, centers=%5B%5B1, 1%5D%5D,%0A cluster_std=0.1)%0A sp = SpectralClustering(n_clusters=2, gamma=0.2, random_state=0)%0A labels = sp.fit(X).labels_%0A assert_greater(np.min(np.bincount(labels)), 10)%0A%0A X = np.ones((10, 9))%0A sp = SpectralClustering(n_clusters=2, gamma=0.2, random_state=0)%0A labels = sp.fit(X).labels_%0A assert_greater(np.min(np.bincount(labels)), 3)%0A
f62f8971bcaddc93cf9993e7ff0e4bfd70e0735d
Connect attribute filling signal to profile to dic function.
authentic2/idp/signals.py
authentic2/idp/signals.py
from django.dispatch import Signal from authentic2.idp.attributes import provide_attributes_at_sso '''authorize_decision Expect a dictionnaries as return with: - the authorization decision e.g. dic['authz'] = True or False - optionnaly a message e.g. dic['message'] = message ''' authorize_service = Signal(providing_args = ["request", "user", "audience"]) '''add_attributes_to_response This signal is used by asynchronous bindings that do not receive attribute list in the request. That means that a predefined list is defined. The asynchronous binding means that the user is "on" the IdP to bring the request then it is possible to take attributes in the Django session. Mainly, it is usable at SSO request treatment. The signal is send with parameters: - request: The request having triggerred a need of attribute - user: instance of the User Django Model to indicate the subject of attributes. Maybe different from request.user if any. - We should here only use a username in case that we want to provide attributes for entities having no corresponding User instance. - audience: identifier of the destination of attributes (e.g. the providerID for SAML2). The return expected is a dictionnaries such as: - dic = {} - attributes = {} - attributes[name] = (value1, value2, ) - attributes[(name, format)] = (value1, value2, ) - attributes[(name, format, nickname)] = (value1, value2, ) - dic['attributes'] = attributes - return dic ''' add_attributes_to_response = \ Signal(providing_args = ["request", "user", "audience"]) add_attributes_to_response.connect(provide_attributes_at_sso) '''add_attributes_to_response Idem as add_attributes_to_response except that the signal sender gives a list of attribute identifiers. The attribute namespace is obtained from the provider to which a namespace has been declared. ''' add_attributes_listed_to_response = \ Signal(providing_args = ["request", "user", "audience", "attributes"]) '''avoid_consent Expect a boolean e.g. dic['avoid_consent'] = True or False ''' avoid_consent = Signal(providing_args = ["request", "user", "audience"])
Python
0
@@ -27,16 +27,49 @@ t Signal +%0Afrom django.conf import settings %0A%0Afrom a @@ -125,16 +125,58 @@ s_at_sso +, %5C%0A provide_attributes_of_user_profile %0A%0A%0A'''au @@ -1692,16 +1692,125 @@ _at_sso) +%0Aif settings.PUSH_PROFILE_UPDATES:%0A add_attributes_to_response.connect(provide_attributes_of_user_profile) %0A%0A'''add
4a74a541104f7534b8f5eb36e8e101ee48c2e672
Update services_and_index_sync.py
tendrl/node_agent/node_sync/services_and_index_sync.py
tendrl/node_agent/node_sync/services_and_index_sync.py
import json import uuid import etcd from tendrl.commons.event import Event from tendrl.commons.message import ExceptionMessage from tendrl.commons.objects.job import Job from tendrl.commons.utils import etcd_utils from tendrl.commons.utils import log_utils as logger # TODO(darshan) this has to be moved to Definition file TENDRL_SERVICES = [ "tendrl-node-agent", "etcd", "tendrl-api", "tendrl-gluster-integration", "tendrl-ceph-integration", "glusterd", "ceph-mon@*", "ceph-osd@*", "ceph-installer" ] def sync(sync_ttl=None): try: tags = [] # update node agent service details logger.log( "debug", NS.publisher_id, {"message": "node_sync, Updating Service data"} ) for service in TENDRL_SERVICES: s = NS.tendrl.objects.Service(service=service) if s.running: service_tag = NS.compiled_definitions.get_parsed_defs()[ 'namespace.tendrl' ]['tags'][service.strip("@*")] tags.append(service_tag) if service_tag == "tendrl/server": tags.append("tendrl/monitor") s.save() _cluster = NS.tendrl.objects.Cluster( integration_id=NS.tendrl_context.integration_id ).load() # Try to claim orphan "provisioner_%integration_id" tag _tag = "provisioner/%s" % _cluster.integration_id _is_new_provisioner = False NS.node_context = NS.tendrl.objects.NodeContext().load() if _tag not in NS.node_context.tags: try: _index_key = "/indexes/tags/%s" % _tag _node_id = json.dumps([NS.node_context.node_id]) NS._int.wclient.write(_index_key, _node_id, prevExist=False) etcd_utils.refresh(_index_key, sync_ttl) tags.append(_tag) _is_new_provisioner = True except etcd.EtcdAlreadyExist: pass # updating node context with latest tags logger.log( "debug", NS.publisher_id, {"message": "node_sync, updating node context " "data with tags"} ) NS.node_context = NS.tendrl.objects.NodeContext().load() current_tags = list(NS.node_context.tags) tags += current_tags NS.node_context.tags = list(set(tags)) NS.node_context.tags.sort() current_tags.sort() if NS.node_context.tags != current_tags: NS.node_context.save() if _is_new_provisioner: _msg = "node_sync, NEW provisioner node found! "\ "re-configuring monitoring (job-id: %s) on this node" payload = { "tags": [ "tendrl/node_%s" % NS.node_context.node_id ], "run": "tendrl.flows.ConfigureMonitoring", "status": "new", "parameters": { 'TendrlContext.integration_id': NS.tendrl_context.integration_id }, "type": "node" } _job_id = str(uuid.uuid4()) Job( job_id=_job_id, status="new", payload=payload ).save() logger.log( "debug", NS.publisher_id, {"message": _msg % _job_id} ) # Update /indexes/tags/:tag = [node_ids] for tag in NS.node_context.tags: index_key = "/indexes/tags/%s" % tag _node_ids = [] try: _node_ids = NS._int.client.read(index_key).value _node_ids = json.loads(_node_ids) except etcd.EtcdKeyNotFound: pass if _node_ids: if "provisioner" in tag: # Check if this is a stale provisioner if NS.node_context.node_id != _node_ids[0]: NS.node_context.tags.remove(tag) NS.node_context.save() continue if NS.node_context.node_id in _node_ids: continue else: _node_ids += [NS.node_context.node_id] else: _node_ids = [NS.node_context.node_id] _node_ids = list(set(_node_ids)) etcd_utils.write(index_key, json.dumps(_node_ids)) if sync_ttl and len(_node_ids) == 1: etcd_utils.refresh(index_key, sync_ttl) logger.log( "debug", NS.publisher_id, {"message": "node_sync, Updating detected " "platform"} ) except Exception as ex: Event( ExceptionMessage( priority="error", publisher=NS.publisher_id, payload={"message": "node_sync service and indexes " "sync failed: " + ex.message, "exception": ex} ) )
Python
0.000002
@@ -2637,39 +2637,115 @@ e()%0A -%0A if _is_new_provisioner + %0A _cluster = _cluster.load()%0A if _is_new_provisioner and _cluster.is_managed == %22yes%22 :%0A
88bb5d1a42b817a000f10ec0989282c0998cc1b0
Add approved and open
openapproved.py
openapproved.py
Python
0.000001
@@ -0,0 +1,2685 @@ +#!/usr/bin/env python%0A#%0A# Copyright (C) 2011 - Soren Hansen%0A# Copyright (C) 2013 - Red Hat, Inc.%0A#%0A%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0A%22%22%22Identify approved and open patches.%0A%0APrints out list of approved patches that failed to merge and are currently%0Astill open.%0A%22%22%22%0A%0Aimport optparse%0Aimport sys%0A%0Aimport utils%0A%0A%0Adef main(argv=None):%0A if argv is None:%0A argv = sys.argv%0A%0A optparser = optparse.OptionParser()%0A optparser.add_option('-p', '--project', default='projects/nova.json',%0A help='JSON file describing the project to generate stats for')%0A optparser.add_option('-a', '--all', action='store_true',%0A help='Generate stats across all known projects (*.json)')%0A optparser.add_option('-u', '--user', default='russellb', help='gerrit user')%0A optparser.add_option('-k', '--key', default=None, help='ssh key for gerrit')%0A optparser.add_option('-s', '--stable', action='store_true',%0A help='Include stable branch commits')%0A options, args = optparser.parse_args()%0A%0A projects = utils.get_projects_info(options.project, options.all)%0A%0A if not projects:%0A print %22Please specify a project.%22%0A sys.exit(1)%0A%0A changes = utils.get_changes(projects, options.user, options.key,%0A only_open=True)%0A%0A approved_and_rebased = set()%0A for change in changes:%0A if 'rowCount' in change:%0A continue%0A if not options.stable and 'stable' in change%5B'branch'%5D:%0A continue%0A if change%5B'status'%5D != 'NEW':%0A # Filter out WORKINPROGRESS%0A continue%0A for patch_set in change%5B'patchSets'%5D%5B:-1%5D:%0A if approved(patch_set) and not approved(change%5B'patchSets'%5D%5B-1%5D):%0A approved_and_rebased.add(%22%25s %25s%22 %25 (change%5B'url'%5D, change%5B'subject'%5D))%0A%0A for x in approved_and_rebased:%0A print x%0A print %22total %25d%22 %25 len(approved_and_rebased)%0A%0A%0Adef approved(patch_set):%0A approvals = patch_set.get('approvals', %5B%5D)%0A for review in approvals:%0A if review%5B'type'%5D == 'APRV':%0A return True%0A return False%0A%0A%0Aif __name__ == '__main__':%0A sys.exit(main())%0A
9bfbf6eb6f65fa745d0ef3777ad4486f47c69b87
Add pose_to_kml.py formatting script
scripts/pose_to_kml.py
scripts/pose_to_kml.py
Python
0.000001
@@ -0,0 +1,1964 @@ +import sys%0Aimport csv%0Afrom math import sin, radians, fabs%0A%0AKML_TEMPLATE = %22%22%22%0A%3C?xml version=%221.0%22 encoding=%22UTF-8%22?%3E%0A%3Ckml xmlns=%22http://www.opengis.net/kml/2.2%22 xmlns:gx=%22http://www.google.com/kml/ext/2.2%22 %0A xmlns:kml=%22http://www.opengis.net/kml/2.2%22 %0A xmlns:atom=%22http://www.w3.org/2005/Atom%22%3E%0A%3CDocument%3E%0A %3Cname%3EKmlFile%3C/name%3E%0A %3CPlacemark%3E%0A %3Cname%3EPlacemark 1%3C/name%3E%0A %3CLookAt%3E%0A %3Clongitude%3E%7Blon%7D%3C/longitude%3E%0A %3Clatitude%3E%7Blat%7D%3C/latitude%3E%0A %3Caltitude%3E0%3C/altitude%3E%0A %3Cheading%3E%7Bhead%7D%3C/heading%3E%0A %3Ctilt%3E%7Btilt%7D%3C/tilt%3E%0A %3Crange%3E%7Brange%7D%3C/range%3E%0A %3Cgx:altitudeMode%3ErelativeToSeaFloor%3C/gx:altitudeMode%3E%0A %3C/LookAt%3E%0A %3CPoint%3E%0A %3Cgx:drawOrder%3E1%3C/gx:drawOrder%3E%0A %3Ccoordinates%3E%7Blon%7D,%7Blat%7D,0%3C/coordinates%3E%0A %3C/Point%3E%0A %3C/Placemark%3E%0A%3C/Document%3E%0A%3C/kml%3E%0A%22%22%22%0A%0Adef parse(data):%0A reader = csv.DictReader(data)%0A for row in reader:%0A # In all serious GIS lon is X and lat is Y,%0A # but we messed it up, and print lon as Y.%0A result = %7B%0A 'lat': float(row%5B'field.pose.position.x'%5D),%0A 'lon': float(row%5B'field.pose.position.y'%5D),%0A 'tilt': float(row%5B'field.pose.orientation.x'%5D),%0A 'head': float(row%5B'field.pose.orientation.y'%5D)%0A %7D%0A divisor = sin(radians(result%5B'tilt'%5D))%0A if fabs(result%5B'tilt'%5D) %3C 1.0:%0A result%5B'range'%5D = float(row%5B'field.pose.position.z'%5D)%0A else:%0A result%5B'range'%5D = float(row%5B'field.pose.position.z'%5D) / divisor%0A return result%0A%0Adef format_kml(data):%0A return KML_TEMPLATE.format(0,%0A lat=data%5B'lat'%5D,%0A lon=data%5B'lon'%5D,%0A head=data%5B'head'%5D,%0A tilt=data%5B'tilt'%5D,%0A range=data%5B'range'%5D)%0A%0Aif __name__ == %22__main__%22:%0A msg = parse(sys.stdin)%0A print format_kml(msg)%0A
846ce88f199381387f612463da51c6b17281dd21
Add script for checking Python3 compatibility
scripts/check_python3_compatibility.py
scripts/check_python3_compatibility.py
Python
0.000002
@@ -0,0 +1,1092 @@ +#!/usr/bin/env python%0A#%0A# Copyright 2021 Google Inc.%0A#%0A# Use of this source code is governed by a BSD-style license that can be%0A# found in the LICENSE file.%0A%0A%0A%22%22%22Check for Python scripts which are incompatible with Python 3.%22%22%22%0A%0A%0Aimport ast%0Aimport os%0Aimport subprocess%0Aimport sys%0A%0A%0Adef check_file(fp):%0A content = open(fp, 'r').read()%0A try:%0A parsed = ast.parse(content)%0A if not parsed:%0A return False%0A return True%0A except SyntaxError:%0A return False%0A%0A%0Adef check_repo(path):%0A files = subprocess.check_output(%5B'git', 'ls-files'%5D, cwd=path).splitlines()%0A incompatible = %5B%5D%0A for f in files:%0A f = f.decode(sys.stdout.encoding)%0A if f.endswith('.py'):%0A if not check_file(os.path.join(path, f)):%0A incompatible.append(f)%0A return incompatible%0A%0A%0Adef __main__(argv):%0A if len(argv) != 2:%0A print('Usage: %25s %3Crepo path%3E' %25 __file__)%0A sys.exit(1)%0A incompatible = check_repo(argv%5B1%5D)%0A if len(incompatible) %3E 0:%0A print('Incompatible Python scripts:')%0A for f in incompatible:%0A print(f)%0A sys.exit(1)%0A%0A%0Aif __name__ == '__main__':%0A __main__(sys.argv)%0A
4402506527cbc7dfbf648a90e4e2c665e27a5a34
Add new package: py-rbtools (#18963)
var/spack/repos/builtin/packages/py-rbtools/package.py
var/spack/repos/builtin/packages/py-rbtools/package.py
Python
0.000001
@@ -0,0 +1,1224 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyRbtools(PythonPackage):%0A %22%22%22RBTools is a set of command line tools and a rich Python API for%0A use with Review Board.%22%22%22%0A%0A homepage = %22https://github.com/reviewboard/rbtools%22%0A url = %22https://github.com/reviewboard/rbtools/archive/release-1.0.2.tar.gz%22%0A%0A version('1.0.2', sha256='dd7aa95691be91f394d085120e44bcec3dc440b01a8f7e2742e09a8d756c831c')%0A version('1.0.1', sha256='bc5e3c511a2273ec61c43a82f56b4cef0b23beae81e277cecbb37ce6761edf29')%0A version('1.0', sha256='dbab2cc89d798462c7e74952d43ba1ff1c97eb9c8f92876e600c6520f72454c9')%0A%0A depends_on('python@2.7:2.8,3.5:', type=('build', 'run'))%0A depends_on('py-setuptools', type=('build', 'run'))%0A depends_on('py-colorama', type=('build', 'run'))%0A depends_on('py-texttable', type=('build', 'run'))%0A depends_on('py-tqdm', type=('build', 'run'))%0A depends_on('py-six@1.8.0:', type=('build', 'run'))%0A depends_on('py-backports-shutil-get-terminal-size', when='%5Epython@:2', type=('build', 'run'))%0A
88d9e6bd216bee0c78f437bdf15362efbebe2e0b
Create new package. (#6504)
var/spack/repos/builtin/packages/r-bookdown/package.py
var/spack/repos/builtin/packages/r-bookdown/package.py
Python
0
@@ -0,0 +1,1881 @@ +##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass RBookdown(RPackage):%0A %22%22%22Output formats and utilities for authoring books and technical%0A documents with R Markdown.%22%22%22%0A%0A homepage = %22https://cran.r-project.org/package=bookdown%22%0A url = %22https://cran.rstudio.com/src/contrib/bookdown_0.5.tar.gz%22%0A list_url = %22https://cran.rstudio.com/src/contrib/Archive/bookdown%22%0A%0A version('0.5', '7bad360948e2b22d28397870b9319f17')%0A%0A depends_on('r-yaml@2.1.14:', type=('build', 'run'))%0A depends_on('r-rmarkdown@1.5:', type=('build', 'run'))%0A depends_on('r-knitr@1.16:', type=('build', 'run'))%0A depends_on('r-htmltools@0.3.6:', type=('build', 'run'))%0A
5558cce438134c722a8c96d7d2badc03b6fd45f5
Create new package. (#6214)
var/spack/repos/builtin/packages/r-fracdiff/package.py
var/spack/repos/builtin/packages/r-fracdiff/package.py
Python
0
@@ -0,0 +1,1716 @@ +##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass RFracdiff(RPackage):%0A %22%22%22Maximum likelihood estimation of the parameters of a%0A fractionally differenced ARIMA(p,d,q) model (Haslett and%0A Raftery, Appl.Statistics, 1989).%22%22%22%0A%0A homepage = %22https://cran.r-project.org/package=fracdiff%22%0A url = %22https://cran.r-project.org/src/contrib/fracdiff_1.4-2.tar.gz%22%0A list_url = %22https://cran.r-project.org/src/contrib/Archive/fracdiff%22%0A%0A version('1.4-2', '6a6977d175ad963d9675736a8f8d41f7')%0A
28c6f1ddc23ee170522b1225bbf60f9b1d244189
Add new package: logrotate (#18786)
var/spack/repos/builtin/packages/logrotate/package.py
var/spack/repos/builtin/packages/logrotate/package.py
Python
0
@@ -0,0 +1,1127 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass Logrotate(AutotoolsPackage):%0A %22%22%22The logrotate utility is designed to simplify the administration of%0A log files on a system which generates a lot of log files. %22%22%22%0A%0A homepage = %22https://github.com/logrotate/logrotate%22%0A url = %22https://github.com/logrotate/logrotate/archive/3.17.0.tar.gz%22%0A%0A version('3.17.0', sha256='c25ea219018b024988b791e91e9f6070c34d2056efa6ffed878067866c0ed765')%0A version('3.16.0', sha256='bc6acfd09925045d48b5ff553c24c567cfd5f59d513c4ac34bfb51fa6b79dc8a')%0A version('3.15.1', sha256='a7b20f5184c9598c36546f9200d3bd616d561478a0423ab8074e97a1cd7b1c25')%0A%0A depends_on('autoconf', type='build')%0A depends_on('automake', type='build')%0A depends_on('libtool', type='build')%0A depends_on('m4', type='build')%0A depends_on('popt')%0A depends_on('acl')%0A%0A def setup_run_environment(self, env):%0A env.prepend_path('PATH', self.prefix.sbin)%0A
8fe2be0010e45f6b2ba339f5a7fe350bb7efed42
add new package (#24045)
var/spack/repos/builtin/packages/py-nipype/package.py
var/spack/repos/builtin/packages/py-nipype/package.py
Python
0
@@ -0,0 +1,1523 @@ +# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyNipype(PythonPackage):%0A %22%22%22Neuroimaging in Python: Pipelines and Interfaces.%22%22%22%0A%0A homepage = %22http://nipy.org/nipype%22%0A pypi = %22nipype/nipype-1.6.0.tar.gz%22%0A%0A version('1.6.0', sha256='bc56ce63f74c9a9a23c6edeaf77631377e8ad2bea928c898cc89527a47f101cf')%0A%0A depends_on('python@3.6:', type=('build', 'run'))%0A depends_on('py-setuptools', type='build')%0A%0A depends_on('py-click@6.6.0:', type=('build', 'run'))%0A depends_on('py-networkx@2.0:', type=('build', 'run'))%0A depends_on('py-nibabel@2.1.0:', type=('build', 'run'))%0A depends_on('py-numpy@1.13:', type=('build', 'run'), when='%5Epython@:3.6.999')%0A depends_on('py-numpy@1.15.3:', type=('build', 'run'), when='%5Epython@3.7:')%0A depends_on('py-packaging', type=('build', 'run'))%0A depends_on('py-prov@1.5.2:', type=('build', 'run'))%0A depends_on('py-pydot@1.2.3:', type=('build', 'run'))%0A depends_on('py-python-dateutil@2.2:', type=('build', 'run'))%0A depends_on('py-rdflib@5.0.0:', type=('build', 'run'))%0A depends_on('py-scipy@0.14:', type=('build', 'run'))%0A depends_on('py-simplejson@3.8.0:', type=('build', 'run'))%0A depends_on('py-traits@4.6:4.99,5.1:', type=('build', 'run'))%0A depends_on('py-filelock@3.0.0:', type=('build', 'run'))%0A depends_on('py-etelemetry@0.2.0:', type=('build', 'run'))%0A
9363331f96805bcc180a081cf9d28b5dab70e25b
Create undoclose.py
HexChat/undoclose.py
HexChat/undoclose.py
Python
0.000003
@@ -0,0 +1,1190 @@ +from sys import platform%0Afrom collections import deque%0Aimport hexchat%0A%0A__module_name__ = %22Undo Close%22%0A__module_version__ = %220.1%22%0A__module_description__ = %22Adds keybinding to undo close tab%22%0A__module_author__ = %22TingPing%22%0A%0Aif platform == 'win32':%0A%09shiftctrlmod = '5'%0Aelif platform == 'darwin':%0A%09shiftctrlmod = '268435473'%0Aelse:%0A%09shiftctrlmod = '21'%0A%0Aclose_history = deque(maxlen=30)%0A%0Adef contextclosed_cb(word, word_eol, userdata):%0A%09global close_history%0A%0A%09ctx = hexchat.get_context()%0A%09for chan in hexchat.get_list('channels'):%0A%09%09if chan.context == ctx:%0A%09%09%09if chan.type != 2: # Only want channels%0A%09%09%09%09return%0A%0A%09net = hexchat.get_info('network')%0A%09if not net:%0A%09%09net = hexchat.get_info('server')%0A%09if not net:%0A%09%09return%0A%09%0A%09chan = hexchat.get_info('channel')%0A%09if not chan:%0A%09%09return%0A%0A%09close_history.append('irc://%7B%7D/%7B%7D'.format(net, chan))%0A%0Adef keypress_cb(word, word_eol, userdata):%0A%09global close_history%0A%0A%09key, mod = word%5B0%5D, word%5B1%5D%0A%09%0A%09if (key, mod) == ('84', shiftctrlmod): # Ctrl+Shift+t%0A%09%09try:%0A%09%09%09last = close_history.pop()%0A%09%09%09hexchat.command('url %7B%7D'.format(last))%0A%09%09except IndexError:%0A%09%09%09pass%0A%0Ahexchat.hook_print(%22Close Context%22, contextclosed_cb)%0Ahexchat.hook_print('Key Press', keypress_cb)%0A
37cc64eec2681c4a1e8d3ad3c7f5971ce4c0c6e8
add home view
kitty/views.py
kitty/views.py
Python
0
@@ -0,0 +1,118 @@ +from django.shortcuts import render_to_response%0A%0Adef home(request):%0A return render_to_response('welcome_page.html')
e9813045f95b8d524e17c7938db0f4df7c29e7bf
day 14
2019/14.py
2019/14.py
Python
0.999563
@@ -0,0 +1,2237 @@ +#!/usr/bin/env python3%0A%0Aimport sys%0A%0Adef parse(s):%0A a, b = s.split(%22 %22)%0A return int(a), b%0A%0Adef has(side, x):%0A return any(x == s%5B1%5D for s in side)%0A%0Adef consumes(rxn, x):%0A return has(rxn%5B0%5D, x)%0A%0Adef produces(rxn, x):%0A return has(rxn%5B1%5D, x)%0A%0A%0Adef go(producers, num):%0A required = %7B%22FUEL%22: num%7D%0A produced = %7B%7D%0A while True:%0A pending = %7Bk for k, v in required.items() if v %3E produced.get(k, 0)%7D%0A if pending == %7B'ORE'%7D: break%0A to_try = next(x for x in pending if x != 'ORE')%0A%0A rule = producers%5Bto_try%5D%5B0%5D%0A # print(rule)%0A num_produced = next(v for v, e in rule%5B1%5D if e == to_try)%0A # print(produced)%0A times = (required%5Bto_try%5D - produced.get(to_try, 0) + (num_produced-1)) // num_produced%0A for v, e in rule%5B0%5D:%0A required%5Be%5D = required.get(e, 0) + times*v%0A for v, e in rule%5B1%5D:%0A produced%5Be%5D = produced.get(e, 0) + times*v%0A%0A # print(required, produced)%0A%0A return required%5B'ORE'%5D%0A%0A%0A%0Adef main():%0A data = %5Bs.strip() for s in sys.stdin%5D%0A rxns = %5B%5D%0A for line in data:%0A l, r = line.split(%22 =%3E %22)%0A rxns.append((%5Bparse(x) for x in l.split(%22, %22)%5D, %5Bparse(x) for x in r.split(%22, %22)%5D))%0A%0A elements = %7By for rxn in rxns for x, y in rxn%5B1%5D%7D%0A%0A producers = %7B%7D%0A consumers = %7B%7D%0A for element in elements:%0A for rxn in rxns:%0A if consumes(rxn, element):%0A consumers.setdefault(element, %5B%5D).append(rxn)%0A if produces(rxn, element):%0A producers.setdefault(element, %5B%5D).append(rxn)%0A%0A # These let me figure out that what producer to use was fixed%0A # print(%7Bk: len(v) for k, v in producers.items()%7D)%0A # print(%7Bk: len(v) for k, v in consumers.items()%7D)%0A%0A part1 = go(producers, 1)%0A%0A # binary search for it%0A n = 1%0A x = part1%0A while x %3C 1000000000000:%0A n *= 2%0A x = go(producers, n)%0A print(n, x)%0A%0A lo = n // 2%0A hi = n%0A while lo %3C hi:%0A mid = (lo + hi) // 2%0A n = mid%0A x = go(producers, n)%0A print(n, x)%0A if x %3C 1000000000000:%0A lo = mid + 1%0A else:%0A hi = mid%0A%0A part2 = lo - 1%0A print(part1)%0A print(part2)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
f226ab5b8ecd4faa80a349ab033702d716a6864c
Add initial migration
timer/migrations/0001_initial.py
timer/migrations/0001_initial.py
Python
0
@@ -0,0 +1,655 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A %5D%0A%0A operations = %5B%0A migrations.CreateModel(%0A name='Timer',%0A fields=%5B%0A ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),%0A ('name', models.CharField(max_length=255)),%0A ('seconds', models.PositiveIntegerField(default=0, verbose_name=b'Time in Seconds')),%0A %5D,%0A options=%7B%0A %7D,%0A bases=(models.Model,),%0A ),%0A %5D%0A
e3665928c80da9df192f8edb5dc28e3200e34fdc
Add a "image me [thing]" handler
toolbot/scripts/google_images.py
toolbot/scripts/google_images.py
Python
0.999936
@@ -0,0 +1,1021 @@ +import re%0Aimport json%0Aimport asyncio%0Aimport random%0Aimport aiohttp%0A%0A%0AGOOGLE_IMAGE_API = 'http://ajax.googleapis.com/ajax/services/search/images'%0A%0A%0Adef plugin(bot):%0A @bot.respond(re.compile(r'(image%7Cimg)( me)? (.*)', re.I))%0A def image_me(msg):%0A asyncio.Task(imageMe(msg, msg.match.group(3), cb=msg.reply))%0A%0A%0A@asyncio.coroutine%0Adef imageMe(msg, query, animated=False, faces=False, cb=None):%0A q = %7B'v': '1.0', 'rsz': '8', 'q': query, 'safe': 'active'%7D%0A if animated:%0A q%5B'imgtype'%5D = 'animated'%0A elif faces:%0A q%5B'imgtype'%5D = 'face'%0A resp = yield from aiohttp.request(%22get%22, GOOGLE_IMAGE_API, params=q)%0A data = yield from resp.read()%0A%0A images = json.loads(data.decode('utf8'))%5B'responseData'%5D%5B'results'%5D%0A if images:%0A img = random.choice(images)%0A cb(ensureImageExtension(img%5B'unescapedUrl'%5D))%0A%0A%0Adef ensureImageExtension(url):%0A ext = url.rsplit('.', 1)%5B1%5D%0A if ext.lower() in ('png', 'jpeg', 'jpg', 'gif'):%0A return url%0A else:%0A return url + %22.png%22%0A
fbc5b10b977d20cff340cfb130cec22d49842b5a
Add repos admin
api/repos/admin.py
api/repos/admin.py
Python
0
@@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import absolute_import, division, print_function%0A%0Afrom django.contrib import admin%0A%0Afrom repos.models import Repo, ExternalRepo%0A%0Aadmin.site.register(Repo)%0Aadmin.site.register(ExternalRepo)%0A
f1189f4774e469e39097e4d10159425a9ed40757
Bump version to 2013.1
nova/version.py
nova/version.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack 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 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. NOVA_VERSION = ['2012', '2', None] YEAR, COUNT, REVISION = NOVA_VERSION FINAL = False # This becomes true at Release Candidate time def canonical_version_string(): return '.'.join(filter(None, NOVA_VERSION)) def version_string(): if FINAL: return canonical_version_string() else: return '%s-dev' % (canonical_version_string(),) def vcs_version_string(): return 'LOCALBRANCH:LOCALREVISION' def version_string_with_vcs(): return '%s-%s' % (canonical_version_string(), vcs_version_string())
Python
0
@@ -671,14 +671,14 @@ '201 -2 +3 ', ' -2 +1 ', N
1681651b7d606436550aad3d696f5f1ba335caa9
Add dump_useractivity migration helper tool.
zephyr/management/commands/dump_useractivity.py
zephyr/management/commands/dump_useractivity.py
Python
0
@@ -0,0 +1,2037 @@ +from optparse import make_option%0Afrom django.core.management.base import BaseCommand%0Afrom zephyr.models import Realm, UserProfile, UserActivity, get_client%0Aimport simplejson%0Afrom zephyr.lib.time import datetime_to_timestamp, timestamp_to_datetime%0A%0Adef dump():%0A pointers = %5B%5D%0A for activity in UserActivity.objects.select_related(%22user_profile__user__email%22,%0A %22client__name%22).all():%0A pointers.append((activity.user_profile.user.email, activity.client.name,%0A activity.query, activity.count,%0A datetime_to_timestamp(activity.last_visit)))%0A file(%22dumped-activity%22, %22w%22).write(simplejson.dumps(pointers) + %22%5Cn%22)%0A%0Adef restore(change):%0A for (email, client_name, query, count, timestamp) in simplejson.loads(file(%22dumped-activity%22).read()):%0A user_profile = UserProfile.objects.get(user__email=email)%0A client = get_client(client_name)%0A last_visit = timestamp_to_datetime(timestamp)%0A print %22%25s: activity for %25s,%25s%22 %25 (email, client_name, query)%0A if change:%0A activity, created = UserActivity.objects.get_or_create(user_profile=user_profile,%0A query=query, client=client,%0A defaults=%7B%22last_visit%22: last_visit,%0A %22count%22: count%7D)%0A if not created:%0A activity.count += count%0A activity.last_visit = max(last_visit, activity.last_visit)%0A activity.save()%0A%0Aclass Command(BaseCommand):%0A option_list = BaseCommand.option_list + (%0A make_option('--restore', default=False, action='store_true'),%0A make_option('--dry-run', '-n', default=False, action='store_true'),)%0A%0A def handle(self, *args, **options):%0A if options%5B%22restore%22%5D:%0A restore(change=not options%5B'dry_run'%5D)%0A else:%0A dump()%0A
9d76f77feebdf20b993385f7022334a4e964e0ad
Create ExampleImport.py
ExampleImport.py
ExampleImport.py
Python
0
@@ -0,0 +1,67 @@ +#!/usr/bin/python%0A%0Aprint (%22This is from the ExampleImport Module%22)%0A
ef8d86704c0930091b8b8f07842e46ffff5bfc34
Correct empty lines in imported files
correct_empty_lines.py
correct_empty_lines.py
Python
0.000039
@@ -0,0 +1,1965 @@ +print('%5Cn%5Cn%5Cn%5Cn')%0Aprint('Now:%5Cn')%0A%0A%0Afor p in c.all_positions():%0A try:%0A # Corrects empty lines around @language python%5Cn@tabwidth -4%0A if p.h.startswith('@clean') and p.h.endswith('py'):%0A # Corrects empty lines after @first%0A if p.h == '@clean manage.py':%0A splited = p.b.partition('%22%22%22%5CnMain starter script for Django%5Cn%22%22%22')%0A p.b = ''.join((splited%5B0%5D.rstrip(), '%5Cn', splited%5B1%5D, splited%5B2%5D))%0A%0A try:%0A if '@language python%5Cn@tabwidth -4' in p.b:%0A splited = p.b.partition('@language python%5Cn@tabwidth -4')%0A p.b = ''.join((splited%5B0%5D.rstrip(), '%5Cn', splited%5B1%5D, '%5Cn', splited%5B2%5D.lstrip()))%0A print(p.h)%0A%0A except Exception as exc:%0A print('---------------------------- Exception: -------------------- %7B%7D'.format(exc))%0A%0A # Corrects empty lines between main blocks%0A else:%0A parent = p.parent().h%0A if parent.startswith('@clean'):%0A siblings = %5Bpos.gnx for pos in p.self_and_siblings()%5D%0A # Corrects empty lines between main blocks%0A if p.gnx != siblings%5B-1%5D:%0A p.b = '%7B%7D%5Cn%5Cn%5Cn'.format(p.b.rstrip())%0A # Corrects empty lines at end of file%0A else:%0A p.b = '%7B%7D%5Cn'.format(p.b.rstrip())%0A # Corrects empty lines between methods%0A elif parent.startswith('class'):%0A siblings = %5Bpos.gnx for pos in p.self_and_siblings()%5D%0A # Corrects empty lines between main blocks%0A if p.gnx != siblings%5B-1%5D:%0A p.b = '%7B%7D%5Cn%5Cn'.format(p.b.rstrip())%0A # Corrects empty lines at end of file%0A else:%0A p.b = '%7B%7D%5Cn'.format(p.b.rstrip())%0A%0A except Exception as exc:%0A print('---------------------------- Exception: -------------------- %7B%7D'.format(exc))
08e6a7821283da3898d2eeb4418b6e035effb2f0
Create spelling_bee.py
spelling_bee.py
spelling_bee.py
Python
0.999938
@@ -0,0 +1,880 @@ +#Kunal Gautam%0A#Codewars : @Kunalpod%0A#Problem name: Spelling Bee%0A#Problem level: 6 kyu%0A%0Adef how_many_bees(hive):%0A if not hive: return 0%0A count = 0%0A for i in range(len(hive)):%0A for j in range(len(hive%5Bi%5D)):%0A try: %0A if hive%5Bi%5D%5Bj%5D=='b' and hive%5Bi%5D%5Bj+1%5D=='e' and hive%5Bi%5D%5Bj+2%5D=='e': count += 1 %0A except: pass%0A try: %0A if j-2%3E=0 and hive%5Bi%5D%5Bj%5D=='b' and hive%5Bi%5D%5Bj-1%5D=='e' and hive%5Bi%5D%5Bj-2%5D=='e': count += 1 %0A except: pass%0A try: %0A if hive%5Bi%5D%5Bj%5D=='b' and hive%5Bi+1%5D%5Bj%5D=='e' and hive%5Bi+2%5D%5Bj%5D=='e': count += 1 %0A except: pass%0A try: %0A if i-2%3E=0 and hive%5Bi%5D%5Bj%5D=='b' and hive%5Bi-1%5D%5Bj%5D=='e' and hive%5Bi-2%5D%5Bj%5D=='e': count += 1%0A except: pass%0A return count%0A
706f29660c9fe6f21af3544ea7871ffdfd56db4a
Create sprintreport.py
sprintreport.py
sprintreport.py
Python
0.000001
@@ -0,0 +1,1375 @@ +from jirawrapper import JIRAWrapper%0Aimport sys%0Aimport getopt%0A%0Aif __name__ == %22__main__%22:%0A argv = sys.argv%5B1:%5D%0A print_help = lambda: print('sprintreport.py %5B-p project%5D -c %3Cusername:password%3E')%0A try:%0A opts, args = getopt.getopt(argv, %22p:c:%22, %5B%22project=%22, %22credentials=%22%5D)%0A except getopt.GetoptError:%0A print_help()%0A sys.exit(2)%0A%0A project = 'HSD'%0A username = None%0A password = None%0A for opt, arg in opts:%0A if opt in ('-p', '--project'):%0A project = arg%0A elif opt in ('-c', '--credentials'):%0A if ':' in arg:%0A username = arg.split(':')%5B0%5D%0A password = arg.split(':')%5B1%5D%0A%0A if username is None or password is None:%0A print_help()%0A sys.exit(2)%0A%0A try:%0A jira_wrapper = JIRAWrapper(username, password, project)%0A print('Stories in current sprint:')%0A for issue in jira_wrapper.current_sprint_user_stories():%0A if issue.fields.status.name == 'Completed':%0A percent = 100%0A else:%0A percent = issue.fields.aggregateprogress.percent%0A print('%7B0%7D - %7B1%7D%25 - %7B2%7D'.format(issue.key, str(percent), issue.fields.summary))%0A print('Sprint completed at %7B0%7D%25'.format(str(jira_wrapper.current_sprint_progress())))%0A except:%0A print('ERROR: An error occurred while contacting JIRA!')%0A
729ab39844bcf6700ccdeb28955e90220d2bab86
convert ip v4
base/convert_ip.py
base/convert_ip.py
Python
0.999975
@@ -0,0 +1,414 @@ +import socket%0Afrom binascii import hexlify%0A%0Adef convert_ip4_address():%0A for ip_addr in %5B'127.0.0.1','192.168.0.1'%5D:%0A packed_ip_addr = socket.inet_aton(ip_addr)%0A unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr)%0A print %22IP Address : %25s =%3E Packed: %25s, Unpacked: %25s%22%5C%0A %25(ip_addr, hexlify(packed_ip_addr), unpacked_ip_addr)%0A %0Aif __name__ == '__main__':%0A convert_ip4_address()
d427012df993dcffb77de05502fcc170cff6cdcb
Add Notebook test
datasciencebox/tests/salt/test_notebook.py
datasciencebox/tests/salt/test_notebook.py
Python
0
@@ -0,0 +1,653 @@ +import pytest%0A%0Aimport requests%0A%0Aimport utils%0A%0Adef setup_module(module):%0A utils.invoke('install', 'notebook')%0A%0A%0A@utils.vagranttest%0Adef test_salt_formulas():%0A project = utils.get_test_project()%0A%0A kwargs = %7B'test': 'true', '--out': 'json', '--out-indent': '-1'%7D%0A out = project.salt('state.sls', args=%5B'ipython.notebook'%5D, target='master', kwargs=kwargs)%0A utils.check_all_true(out, none_is_ok=True)%0A%0A%0A@utils.vagranttest%0Adef test_notebook_ui():%0A project = utils.get_test_project()%0A%0A project = utils.get_test_project()%0A nn_ip = project.cluster.master.ip%0A%0A r = requests.get('http://%25s:8888/' %25 nn_ip)%0A assert r.status_code == 200%0A
1380ee2a9eff29bd1271eb0e920b75752f7346c7
Add (transitional?) db_oldrotate.py that finds exif rotate in old posts.
db_oldrotate.py
db_oldrotate.py
Python
0
@@ -0,0 +1,460 @@ +#!/usr/bin/env python%0A# -*- coding: iso-8859-1 -*-%0A%0Afrom pyexiv2 import Image as ExivImage%0Afrom db_add import exif2rotation%0Afrom dbclient import dbclient%0A%0Aclient = dbclient()%0Aposts = client._search_post(%22SPFrotate%22, %5B%22rotate%22%5D)%0Aprint len(posts), %22posts%22%0Afor post in posts:%0A%09if post%5B%22rotate%22%5D == -1:%0A%09%09m = post%5B%22md5%22%5D%0A%09%09exif = ExivImage(client.image_path(m))%0A%09%09exif.readMetadata()%0A%09%09rot = exif2rotation(exif)%0A%09%09if rot %3E= 0:%0A%09%09%09client.modify_post(m, rotate=rot)%0A
4da034ab29619eef5396b45e766e42fe89e16b3f
use fn_get_authorized_regions_by_user to get recursive region ids based on permissinos.
datapoints/api/base.py
datapoints/api/base.py
from django.core import urlresolvers from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from tastypie.authorization import Authorization from tastypie.authentication import ApiKeyAuthentication from tastypie.resources import ModelResource, Resource, ALL from datapoints.models import RegionType,Region,RegionHeirarchy,RegionPermission class BaseModelResource(ModelResource): ''' This is the top level class all other Resource Classes inherit from this. The API Key authentication is defined here and thus is required by all other resources. This class enherits fro the Tastyppie "ModelResource" See Here: http://django-tastypie.readthedocs.org/en/latest/resources.html?highlight=modelresource ''' class Meta(): # authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True allowed_methods = ['get','post','put','patch', 'delete'] filtering = { "id": ALL, } class BaseNonModelResource(Resource): ''' This is the top level class all other Resource Classes inherit from this. The API Key authentication is defined here and thus is required by all other resources. This class enherits fro the Tastyppie "ModelResource" See Here: http://django-tastypie.readthedocs.org/en/latest/resources.html?highlight=modelresource ''' class Meta(): # authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True def parse_url_strings(self,query_dict): self.region__in, self.region_type_id, self.parent_region__in = \ None, None, None ## REGION_ID try: self.region__in = [int(r) for r in query_dict['region__in']\ .split(',')] except KeyError: pass except ValueError: pass ## REGION TYPE ## try: self.region_type_id = RegionType.objects.get(name = query_dict\ ['level'].lower()).id except KeyError: pass except ObjectDoesNotExist: all_r_types = RegionType.objects.all().values_list('name',flat=True) err = 'region type doesnt exist. options are: %s' % all_r_types return err, [] try: self.parent_region__in = [int(r) for r in query_dict['parent_region__in']\ .split(',')] except KeyError: pass except ValueError: pass return None def get_regions_to_return_from_url(self,request): ''' 1 region__in returns geo data for the regions requested 2. parent_region__in + level should return the shapes for all the child regions at the specified level that are within the region specified 3. passing only parent_region__in should return the shapes for all the immediate children in that region if no level parameter is supplied 4. no params - return top 10 regions ''' ## attach these to self and return only error # err = self.parse_url_strings(request.GET) if err: self.err = err return err, [] ## CASE 1 ## if self.region__in is not None: region_ids = Region.objects.filter(id__in = self.region__in)\ .values_list('id',flat=True) ## CASE 2 ## elif self.parent_region__in is not None and self.region_type_id is not None: region_ids = RegionHeirarchy.objects.filter( contained_by_region_id__in = self.parent_region__in, \ region_type_id = self.region_type_id)\ .values_list('region_id',flat=True) if len(region_ids) == 0: err = 'no regions of region_type_id: %s exists under region_id\ %s ' % (self.region_type_id, self.parent_region__in) return err, region_ids ## CASE 3 # elif self.parent_region__in is not None and self.region_type_id is None: region_ids = Region.objects.filter(parent_region__in = \ self.parent_region__in) else: region_ids = Region.objects.all().values_list('id',flat=True) permitted_region_ids = set(RegionPermission.objects.filter(user_id=\ self.user_id).values_list('region_id',flat=True)) final_region_ids = list(set(region_ids).intersection(set(permitted_region_ids))) print final_region_ids return None, final_region_ids def get_list(self, request, **kwargs): ''' Overriding this just so i can access the user_id attribute within the resource. ''' self.user_id = request.user.id args = [] return super(BaseNonModelResource, self).get_list(request, **kwargs) def html_decorator(func): """ This decorator wraps the output in html. (From http://stackoverflow.com/a/14647943) """ def _decorated(*args, **kwargs): response = func(*args, **kwargs) wrapped = ("<html><body>", response.content, "</body></html>") return HttpResponse(wrapped) return _decorated @html_decorator def debug(request): """ Debug endpoint that uses the html_decorator, """ path = request.META.get("PATH_INFO") api_url = path.replace("debug/", "") view = urlresolvers.resolve(api_url) accept = request.META.get("HTTP_ACCEPT") accept += ",application/json" request.META["HTTP_ACCEPT"] = accept res = view.func(request, **view.kwargs) return HttpResponse(res._container)
Python
0
@@ -4356,116 +4356,115 @@ s = -set( + Region -Permission.objects.filter(user_id=%5C%0A self.user_id).values_list('region_id',flat=True))%0A +.objects.raw(%22SELECT * FROM%5C%0A fn_get_authorized_regions_by_user(%25s,NULL)%22,%5Bself.user_id%5D) %0A%0A @@ -4530,51 +4530,46 @@ set( -permitted_region_ids)))%0A print final +%5Br.id for r %5C%0A in permitted _reg @@ -4567,32 +4567,36 @@ itted_region_ids +%5D))) %0A%0A return
35eee909fa90d06efa34a39667db6345725bc177
Add tool _list paging test
Allura/allura/tests/functional/test_tool_list.py
Allura/allura/tests/functional/test_tool_list.py
# 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 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. from allura.tests import TestController from allura.tests import decorators as td class TestToolListController(TestController): @td.with_wiki @td.with_tool('test', 'Wiki', 'wiki2') def test_default(self): """Test that list page contains a link to all tools of that type.""" r = self.app.get('/p/test/_list/wiki') assert len(r.html.find('a', dict(href='/p/test/wiki/'))) == 1, r assert len(r.html.find('a', dict(href='/p/test/wiki2/'))) == 1, r
Python
0
@@ -1215,33 +1215,482 @@ -assert len(r.html +content = r.html.find('div', id='content_base')%0A assert content.find('a', dict(href='/p/test/wiki/')), r%0A assert content.find('a', dict(href='/p/test/wiki2/')), r%0A%0A @td.with_wiki%0A @td.with_tool('test', 'Wiki', 'wiki2')%0A def test_paging(self):%0A %22%22%22Test that list page handles paging correctly.%22%22%22%0A r = self.app.get('/p/test/_list/wiki?limit=1&page=0')%0A content = r.html.find('div', id='content_base')%0A assert content .find('a @@ -1715,30 +1715,24 @@ est/wiki/')) -) == 1 , r%0A @@ -1742,18 +1742,206 @@ ert -len(r.html +not content.find('a', dict(href='/p/test/wiki2/')), r%0A r = self.app.get('/p/test/_list/wiki?limit=1&page=1')%0A content = r.html.find('div', id='content_base')%0A assert not content .fin @@ -1974,19 +1974,77 @@ wiki -2 /')) -) == 1 +, r%0A assert content.find('a', dict(href='/p/test/wiki2/')) , r%0A
64b03bd53f6f494398818199caabe10138469719
Create couples-holding-hands.py
Python/couples-holding-hands.py
Python/couples-holding-hands.py
Python
0.000001
@@ -0,0 +1,808 @@ +# Time: O(n)%0A# Space: O(n)%0A%0Aclass Solution(object):%0A def minSwapsCouples(self, row):%0A %22%22%22%0A :type row: List%5Bint%5D%0A :rtype: int%0A %22%22%22%0A N = len(row)//2%0A couples = %5B%5B%5D for _ in xrange(N)%5D%0A for seat, num in enumerate(row):%0A couples%5Bnum//2%5D.append(seat//2)%0A adj = %5B%5B%5D for _ in xrange(N)%5D%0A for couch1, couch2 in couples:%0A adj%5Bcouch1%5D.append(couch2)%0A adj%5Bcouch2%5D.append(couch1)%0A %0A result = N%0A for couch in xrange(N):%0A if not adj%5Bcouch%5D: continue%0A result -= 1%0A couch1, couch2 = couch, adj%5Bcouch%5D.pop()%0A while couch2 != couch:%0A adj%5Bcouch2%5D.remove(couch1)%0A couch1, couch2 = couch2, adj%5Bcouch2%5D.pop()%0A return result%0A
364de0a95b868bba980bfe6445cd80f55b39bb63
add amber ti estimator test code
src/alchemlyb/tests/test_ti_estimators_amber.py
src/alchemlyb/tests/test_ti_estimators_amber.py
Python
0.000061
@@ -0,0 +1,1120 @@ +%22%22%22Tests for all TI-based estimators in %60%60alchemlyb%60%60.%0A%0A%22%22%22%0Aimport pytest%0A%0Aimport pandas as pd%0A%0Afrom alchemlyb.parsing import amber %0Afrom alchemlyb.estimators import TI%0Aimport alchemtest.amber%0A%0A%0Adef amber_simplesolvated_charge_dHdl():%0A dataset = alchemtest.amber.load_simplesolvated()%0A%0A dHdl = pd.concat(%5Bamber.extract_dHdl(filename)%0A for filename in dataset%5B'data'%5D%5B'charge'%5D%5D)%0A%0A return dHdl%0A%0Adef amber_simplesolvated_vdw_dHdl():%0A dataset = alchemtest.amber.load_simplesolvated()%0A%0A dHdl = pd.concat(%5Bamber.extract_dHdl(filename)%0A for filename in dataset%5B'data'%5D%5B'vdw'%5D%5D)%0A%0A return dHdl%0A%0A%0Aclass TIestimatorMixin:%0A%0A @pytest.mark.parametrize('X_delta_f', ((amber_simplesolvated_charge_dHdl(), -60.114),%0A (amber_simplesolvated_vdw_dHdl(), 3.824)))%0A def test_get_delta_f(self, X_delta_f):%0A est = self.cls().fit(X_delta_f%5B0%5D)%0A delta_f = est.delta_f_.iloc%5B0, -1%5D%0A assert X_delta_f%5B1%5D == pytest.approx(delta_f, rel=1e-3)%0A%0Aclass TestTI(TIestimatorMixin):%0A %22%22%22Tests for TI.%0A%0A %22%22%22%0A cls = TI %0A%0A
a8f4d9252016aa9c656ad6d06558b520af06b489
Create spyne_webservice.py
PythonTests/spyne_webservice.py
PythonTests/spyne_webservice.py
Python
0.000001
@@ -0,0 +1,1301 @@ +%22%22%22%0AUSE: Wizdler Chrome Extension%0Afrom suds.client import Client%0Ac = Client('http://localhost:8008/...?wsdl')%0Ac.service.SmokeTest('XXX')%0A%22%22%22%0A%0Aresponse_file = '$RESP_FILE'%0A%0Afrom spyne import Application, rpc, ServiceBase, Iterable, Integer, Unicode%0Afrom spyne.protocol.soap import Soap11%0Afrom spyne.server.wsgi import WsgiApplication%0A%0A%0Aclass TestService(ServiceBase):%0A __service_url_path__ = '/TestCenter/UC1/smoke.test'%0A #__in_protocol__ = Soap11(validator='lxml')%0A #__out_protocol__ = Soap11()%0A%0A @rpc(Unicode, _returns=Unicode)%0A def SmokeTest(ctx, req):%0A %22%22%22Test stub%0A %3Cb%3EBase test:%3C/b%3E%0A @req input request %0A @return predefined file content%0A %22%22%22%0A%09f = open(response_file, 'r')%0A%09return req%0A return f.read()%0A%0A%0Aapplication = Application(%5BTestService%5D, 'TestServiceNamespace',%0A in_protocol=Soap11(validator='lxml'),%0A out_protocol=Soap11()%0A )%0A%0Awsgi_application = WsgiApplication(application)%0A%0A%0Aif __name__ == '__main__':%0A import logging%0A%0A from wsgiref.simple_server import make_server%0A%0A logging.basicConfig(level=logging.DEBUG)%0A logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)%0A%0A logging.info(%22Service started%22)%0A%0A server = make_server('127.0.0.1', 8008, wsgi_application)%0A server.serve_forever()%0A
4e4fc8bdc573f297c5ea7c6d9ade012ae0c3706f
Use utf-8 encoding for files
src/robot/serializing/serialize_log.py
src/robot/serializing/serialize_log.py
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # 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. from __future__ import with_statement import os import re import robot from robot import utils PATH = os.path.join(os.path.dirname(robot.__file__),'webcontent') LOG_TEMPLATE = os.path.join(PATH,'log.html') REPORT_TEMPLATE = os.path.join(PATH, 'report.html') JS_FILE_REGEXP = re.compile('src=\"([^\"]+)\"') def serialize_log(test_output_datamodel, log_path, title=None): if log_path is None: return _build_file(log_path, test_output_datamodel, title, None, LOG_TEMPLATE) def serialize_report(test_output_datamodel, report_path, title=None, background=None, log_path=None): if report_path is None: return relative_log_path = _build_relative_log_path(report_path, log_path) _build_file(report_path, test_output_datamodel, title, _resolve_background_colors(background), REPORT_TEMPLATE, relative_log_path) def _build_relative_log_path(report, log): if not log: return None return utils.get_link_path(log, os.path.dirname(report)) def _build_file(outpath, test_output_datamodel, title, background, template, log_path=None): with open(outpath, 'w') as outfile: populator = _Populator(outfile, test_output_datamodel, title, background, log_path) with open(template, 'r') as templ: for line in templ: populator.line(line) def _resolve_background_colors(color_str): if color_str and color_str.count(':') not in [1, 2]: #LOGGER.error("Invalid background color '%s'." % color_str) color_str = None if not color_str: color_str = '#99FF66:#FF3333' colors = color_str.split(':', 2) return colors if len(colors) == 3 else [colors[0], colors[0], colors[1]] class _Populator(object): def __init__(self, log, test_output_datamodel, title, background, log_path=None): self._log = log self._log_path=log_path self._test_output_datamodel = test_output_datamodel self._title = title self._parsing = self._normal_parsing self._backgrounds = {"/* BACKGROUND: critical pass */": background[0] if background else None, "/* BACKGROUND: non critical fail */": background[1] if background else None, "/* BACKGROUND: critical fail */": background[2] if background else None} def line(self, line): self._parsing(line) def _normal_parsing(self, line): if self._is_begin_scripts(line): self._start_script() elif self._is_title_line_to_handle(line): self._write_title() elif self._is_background_line_to_handle(line): self._write_background(line) elif self._is_log_path_line_to_handle(line): self._replace_log_path(line) else: self._log.write(line) def _is_begin_scripts(self, line): return line == '<!-- BEGIN SCRIPTS -->\n' def _is_title_line_to_handle(self, line): return self._title is not None and line.startswith('<title>') def _write_title(self): self._log.write('<title>%s</title>\n' % self._title) def _is_log_path_line_to_handle(self, line): return self._log_path and 'log.html' in line def _replace_log_path(self, line): self._log.write(line.replace('log.html', self._log_path)) def _is_background_line_to_handle(self, line): for marker in self._backgrounds: if marker in line: return True return False def _write_background(self, line): for marker in self._backgrounds: if marker in line: self._log.write(" background: %s;\n" % self._backgrounds[marker]) def _in_script(self, line): if self._is_end_scripts(line): self._end_script() elif self._is_output_js(line): self._write_output_js() else: self._write_lines_js(line) def _is_end_scripts(self, line): return line == '<!-- END SCRIPTS -->\n' def _end_script(self): self._log.write('</script>\n') self._parsing = self._normal_parsing def _is_output_js(self, line): return line.startswith('<!-- OUTPUT JS -->') def _write_output_js(self): self._test_output_datamodel.write_to(self._log) def _write_lines_js(self, line): self._write_js(self._parse_js_file_name(line)) def _start_script(self): self._log.write('<script type="text/javascript">\n') self._parsing = self._in_script def _parse_js_file_name(self, line): return os.path.join(PATH, JS_FILE_REGEXP.search(line).group(1).replace('/', os.path.sep)) def _write_js(self, js_file): with open(js_file, 'r') as js: for jsline in js: self._log.write(jsline) self._log.write('\n\n') if __name__ == '__main__': import jsparser jsparser.parse('output.xml', 'output.js') serialize_log('output.js', 'logjsx.html')
Python
0.000001
@@ -637,16 +637,30 @@ atement%0A +import codecs%0A import o @@ -1695,24 +1695,31 @@ ):%0A with +codecs. open(outpath @@ -1723,16 +1723,34 @@ ath, 'w' +, encoding='UTF-8' ) as out @@ -5329,24 +5329,31 @@ with +codecs. open(js_file @@ -5353,24 +5353,42 @@ js_file, 'r' +, encoding='UTF-8' ) as js:%0A
f4b1ad081dc6a7e83d0342d00c82549cde72c3fa
improve user search capabilities
src/sentry/api/endpoints/user_index.py
src/sentry/api/endpoints/user_index.py
from __future__ import absolute_import import six from django.db.models import Q from sentry.api.base import Endpoint from sentry.api.paginator import DateTimePaginator from sentry.api.permissions import SuperuserPermission from sentry.api.serializers import serialize from sentry.db.models.query import in_iexact from sentry.models import User from sentry.search.utils import tokenize_query class UserIndexEndpoint(Endpoint): permission_classes = (SuperuserPermission,) def get(self, request): queryset = User.objects.distinct() query = request.GET.get('query') if query: tokens = tokenize_query(query) for key, value in six.iteritems(tokens): if key == 'query': value = ' '.join(value) queryset = queryset.filter( Q(name__icontains=value) | Q(username__icontains=value) | Q(email__icontains=value) | Q(emails__email__icontains=value) ) elif key == 'name': queryset = queryset.filter( in_iexact('name', value) ) elif key == 'email': queryset = queryset.filter( in_iexact('email', value) ) elif key == 'username': queryset = queryset.filter( in_iexact('username', value) ) status = request.GET.get('status') if status == 'active': queryset = queryset.filter( is_active=True, ) elif status == 'disabled': queryset = queryset.filter( is_active=False, ) order_by = '-date_joined' paginator_cls = DateTimePaginator return self.paginate( request=request, queryset=queryset, order_by=order_by, on_results=lambda x: serialize(x, request.user), paginator_cls=paginator_cls, )
Python
0.000001
@@ -1058,32 +1058,174 @@ )%0A + elif key == 'id':%0A queryset = queryset.filter(%0A id__in=value,%0A )%0A @@ -1674,32 +1674,101 @@ ) +%0A else:%0A queryset = queryset.none() %0A%0A status
ecabc90a6f55fdd2fa0d0ed789b72d3196d3e2eb
Correct query to members and pending members
src/sentry/web/forms/teams.py
src/sentry/web/forms/teams.py
""" sentry.web.forms.teams ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from django import forms from sentry.models import Team, TeamMember, PendingTeamMember from sentry.web.forms.fields import UserField from django.utils.translation import ugettext_lazy as _ class RemoveTeamForm(forms.Form): pass class NewTeamForm(forms.ModelForm): name = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': _('e.g. My Team Name')})) slug = forms.SlugField(help_text=_('A slug is a URL-safe word and must be unique across all teams.'), widget=forms.TextInput(attrs={'placeholder': _('e.g. my-team-name')})) class Meta: fields = ('name', 'slug') model = Team class NewTeamAdminForm(forms.ModelForm): name = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': _('e.g. My Team Name')})) slug = forms.SlugField(help_text=_('A slug is a URL-safe word and must be unique across all teams.'), widget=forms.TextInput(attrs={'placeholder': _('e.g. my-team-name')})) owner = UserField(required=False) class Meta: fields = ('name', 'slug', 'owner') model = Team class EditTeamForm(forms.ModelForm): class Meta: fields = ('name',) model = Team class EditTeamAdminForm(EditTeamForm): owner = UserField(required=False) class Meta: fields = ('name', 'owner',) model = Team class SelectTeamForm(forms.Form): team = forms.ChoiceField(choices=()) def __init__(self, team_list, data, *args, **kwargs): super(SelectTeamForm, self).__init__(data=data, *args, **kwargs) self.team_list = dict((str(t.pk), t) for t in team_list.itervalues()) self.fields['team'].choices = [c for c in sorted(self.team_list.iteritems(), key=lambda x: x[1].name)] self.fields['team'].choices.insert(0, ('', '-' * 8)) self.fields['team'].widget.choices = self.fields['team'].choices def clean_team(self): value = self.cleaned_data.get('team') if not value: return value return self.team_list.get(value) class BaseTeamMemberForm(forms.ModelForm): class Meta: fields = ('type',) model = TeamMember def __init__(self, project, *args, **kwargs): self.project = project super(BaseTeamMemberForm, self).__init__(*args, **kwargs) EditTeamMemberForm = BaseTeamMemberForm class InviteTeamMemberForm(BaseTeamMemberForm): class Meta: fields = ('type', 'email') model = PendingTeamMember def clean_email(self): value = self.cleaned_data['email'] if not value: return None if self.project.member_set.filter(user__email__iexact=value).exists(): raise forms.ValidationError(_('There is already a member with this email address')) if self.project.pending_member_set.filter(email__iexact=value).exists(): raise forms.ValidationError(_('There is already a pending invite for this user')) return value class NewTeamMemberForm(BaseTeamMemberForm): user = UserField() class Meta: fields = ('type', 'user') model = TeamMember def clean_user(self): value = self.cleaned_data['user'] if not value: return None if self.project.member_set.filter(user=value).exists(): raise forms.ValidationError(_('User is already a member of this team')) return value
Python
0.998939
@@ -2797,32 +2797,37 @@ if self.project. +team. member_set.filte @@ -2986,16 +2986,21 @@ project. +team. pending_
9a6fe771ba03cd64c4f6d764125457ed808feca2
Add datacite harvester
scrapi/harvesters/datacite.py
scrapi/harvesters/datacite.py
Python
0.000001
@@ -0,0 +1,1137 @@ +'''%0AHarvester for the DataCite MDS for the SHARE project%0A%0AExample API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc%0A'''%0Afrom __future__ import unicode_literals%0A%0Afrom scrapi.base import OAIHarvester%0Afrom scrapi.base.helpers import updated_schema, oai_extract_dois%0A%0A%0Aclass DataciteHarvester(OAIHarvester):%0A short_name = 'datacite'%0A long_name = 'DataCite MDS'%0A url = 'http://oai.datacite.org/oai'%0A%0A base_url = 'http://oai.datacite.org/oai'%0A property_list = %5B'date', 'identifier', 'setSpec', 'description'%5D%0A timezone_granularity = True%0A%0A @property%0A def schema(self):%0A return updated_schema(self._schema, %7B%0A %22description%22: (%22//dc:description/node()%22, get_second_description),%0A %22uris%22: %7B%0A %22canonicalUri%22: ('//dc:identifier/node()', oai_extract_dois),%0A %22objectUris%22: ('//dc:identifier/node()', oai_extract_dois)%0A %7D%0A %7D)%0A%0A%0Adef get_second_description(descriptions):%0A if descriptions:%0A if len(descriptions) %3E 1:%0A return descriptions%5B1%5D%0A else:%0A return descriptions%5B0%5D%0A return ''%0A
d0839799c1fc3ec6da6cda701a9d4699b4fcb168
Update workstation.py
erpnext/manufacturing/doctype/workstation/workstation.py
erpnext/manufacturing/doctype/workstation/workstation.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, cint, getdate, formatdate, comma_and, time_diff_in_seconds, to_timedelta from frappe.model.document import Document from dateutil.parser import parse class WorkstationHolidayError(frappe.ValidationError): pass class NotInWorkingHoursError(frappe.ValidationError): pass class OverlapError(frappe.ValidationError): pass class Workstation(Document): def validate(self): self.hour_rate = (flt(self.hour_rate_labour) + flt(self.hour_rate_electricity) + flt(self.hour_rate_consumable) + flt(self.hour_rate_rent)) def on_update(self): self.validate_overlap_for_operation_timings() self.update_bom_operation() def validate_overlap_for_operation_timings(self): """Check if there is no overlap in setting Workstation Operating Hours""" for d in self.get("working_hours"): existing = frappe.db.sql_list("""select idx from `tabWorkstation Working Hour` where parent = %s and name != %s and ( (start_time between %s and %s) or (end_time between %s and %s) or (%s between start_time and end_time)) """, (self.name, d.name, d.start_time, d.end_time, d.start_time, d.end_time, d.start_time)) if existing: frappe.throw(_("Row #{0}: Timings conflicts with row {1}").format(d.idx, comma_and(existing)), OverlapError) def update_bom_operation(self): bom_list = frappe.db.sql("""select DISTINCT parent from `tabBOM Operation` where workstation = %s""", self.name) for bom_no in bom_list: frappe.db.sql("""update `tabBOM Operation` set hour_rate = %s where parent = %s and workstation = %s""", (self.hour_rate, bom_no[0], self.name)) @frappe.whitelist() def get_default_holiday_list(): return frappe.db.get_value("Company", frappe.defaults.get_user_default("Company"), "default_holiday_list") def check_if_within_operating_hours(workstation, operation, from_datetime, to_datetime): if from_datetime and to_datetime: if not cint(frappe.db.get_value("Manufacturing Settings", "None", "allow_production_on_holidays")): check_workstation_for_holiday(workstation, from_datetime, to_datetime) if not cint(frappe.db.get_value("Manufacturing Settings", None, "allow_overtime")): is_within_operating_hours(workstation, operation, from_datetime, to_datetime) def is_within_operating_hours(workstation, operation, from_datetime, to_datetime): operation_length = time_diff_in_seconds(to_datetime, from_datetime) workstation = frappe.get_doc("Workstation", workstation) for working_hour in workstation.working_hours: slot_length = (to_timedelta(working_hour.end_time or "") - to_timedelta(working_hour.start_time or "")).total_seconds() if slot_length >= operation_length: return frappe.throw(_("Operation {0} longer than any available working hours in workstation {1}, break down the operation into multiple operations").format(operation, workstation.name), NotInWorkingHoursError) def check_workstation_for_holiday(workstation, from_datetime, to_datetime): holiday_list = frappe.db.get_value("Workstation", workstation, "holiday_list") if holiday_list and from_datetime and to_datetime: applicable_holidays = [] for d in frappe.db.sql("""select holiday_date from `tabHoliday` where parent = %s and holiday_date between %s and %s """, (holiday_list, getdate(from_datetime), getdate(to_datetime))): applicable_holidays.append(formatdate(d[0])) if applicable_holidays: frappe.throw(_("Workstation is closed on the following dates as per Holiday List: {0}") .format(holiday_list) + "\n" + "\n".join(applicable_holidays), WorkstationHolidayError)
Python
0.000001
@@ -2710,16 +2710,73 @@ _hours:%0A +%09%09if working_hour.start_time and working_hour.end_time:%0A%09 %09%09slot_l @@ -2891,16 +2891,17 @@ nds()%0A%09%09 +%09 if slot_ @@ -2928,16 +2928,17 @@ length:%0A +%09 %09%09%09retur
c63f2e2993b0c32d7bc2de617dfb147c0f6a2d89
patch fix
erpnext/patches/v7_0/make_is_group_fieldtype_as_check.py
erpnext/patches/v7_0/make_is_group_fieldtype_as_check.py
import frappe def execute(): for doctype in ["Sales Person", "Customer Group", "Item Group", "Territory"]: frappe.reload_doctype(doctype) #In MySQL, you can't modify the same table which you use in the SELECT part. frappe.db.sql(""" update `tab{doctype}` set is_group = 1 where name in (select parent_{field} from (select distinct parent_{field} from `tab{doctype}` where parent_{field} != '') as dummy_table) """.format(doctype=doctype, field=doctype.strip().lower().replace(' ','_')))
Python
0.000001
@@ -1,8 +1,48 @@ +from __future__ import unicode_literals%0A import f @@ -146,122 +146,32 @@ %22%5D:%0A -%0A %09%09 -frappe.reload_doctype(doctype)%0A%0A%09%09#In MySQL, you can't modify the same table which you use in the SELECT part.%0A +%0A%09%09# convert to 1 or 0 %0A%09%09f @@ -188,11 +188,8 @@ ql(%22 -%22%22 upda @@ -225,161 +225,206 @@ p = -1%0A%09%09%09where name in (select parent_%7Bfield%7D from (select distinct parent_%7Bfield%7D from %60tab%7Bdoctype%7D%60%0A%09%09%09%09where parent_%7Bfield%7D != '') as dummy_table) +if(is_group='Yes',1,0) %22%0A%09%09%09.format(doctype=doctype))%0A%0A%09%09frappe.db.commit()%0A%0A%09%09# alter fields to int%0A%09%09%09%09%0A%09%09frappe.db.sql(%22alter table %60tab%7Bdoctype%7D%60 change is_group is_group int(1) default '0'%22 %0A%09%09%09 -%22%22%22 .for @@ -446,55 +446,41 @@ type -, field=doctype.strip().lower().replace(' ','_')) +))%0A%0A%09%09frappe.reload_doctype(doctype )%0A
70b2fcb7ca85878b2012cab8c476b40f2624e7ee
Add migration new_name
geotrek/trekking/migrations/0003_auto_20181113_1755.py
geotrek/trekking/migrations/0003_auto_20181113_1755.py
Python
0.000009
@@ -0,0 +1,565 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.14 on 2018-11-13 16:55%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('trekking', '0002_trek_pois_excluded'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='trek',%0A name='pois_excluded',%0A field=models.ManyToManyField(db_table=b'l_r_troncon_poi_exclus', related_name='excluded_treks', to='trekking.POI', verbose_name='Excluded POIs'),%0A ),%0A %5D%0A
43fbaa6c109c51a77832d6f09e0543794882b518
Add scripts printing special:mode.yml from model.npz
scripts/contrib/model_info.py
scripts/contrib/model_info.py
Python
0
@@ -0,0 +1,1073 @@ +#!/usr/bin/env python3%0A%0Aimport sys%0Aimport argparse%0Aimport numpy as np%0Aimport yaml%0A%0A%0ADESC = %22Prints version and model type from model.npz file.%22%0AS2S_SPECIAL_NODE = %22special:model.yml%22%0A%0A%0Adef main():%0A args = parse_args()%0A%0A model = np.load(args.model)%0A if S2S_SPECIAL_NODE not in model:%0A print(%22No special Marian YAML node found in the model%22)%0A exit(1)%0A%0A yaml_text = bytes(model%5BS2S_SPECIAL_NODE%5D).decode('ascii')%0A if not args.key:%0A print(yaml_text)%0A exit(0)%0A%0A # fix the invalid trailing unicode character '#x0000' added to the YAML%0A # string by the C++ cnpy library%0A try:%0A yaml_node = yaml.load(yaml_text)%0A except yaml.reader.ReaderError:%0A yaml_node = yaml.load(yaml_text%5B:-1%5D)%0A%0A print(yaml_node%5Bargs.key%5D)%0A%0A%0Adef parse_args():%0A parser = argparse.ArgumentParser(description=DESC)%0A parser.add_argument(%22-m%22, %22--model%22, help=%22model file%22, required=True)%0A parser.add_argument(%22-k%22, %22--key%22, help=%22print value for specific key%22)%0A return parser.parse_args()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
af5e58c2fefdffa8046ecace238a3fd1a2a43387
Add Naive Bayes base class:
ML/naivebayes.py
ML/naivebayes.py
Python
0.000001
@@ -0,0 +1,1545 @@ +%22%22%22%0ANaive Bayes Classifier%0AIncludes gaussian, bernoulli and multinomial models%0A%22%22%22%0A%0Aimport abc%0Aimport numpy as np%0A%0Aclass NaiveBayes:%0A %22%22%22%0A Naive Bayes Classifier%0A Given class label, assumes features are independent%0A %22%22%22%0A __metaclass__ = abc.ABCMeta%0A%0A def __init__(self):%0A %22%22%22%0A Attributes:%0A learned (bool): Keeps track of if classifier has been fit%0A class_names (np.ndarray): array of class names. %5B0, 1%5D for example.%0A class_priors (dict): prior probability of each class.%0A determined via fraction of training samples in each class%0A class_parameters (dict): dict of parameters for each class%0A%0A %22%22%22%0A self.learned = False%0A self.class_names = %5B%5D%0A self.class_priors = %7B%7D%0A self.class_parameters = %7B%7D%0A %0A @abc.abstractmethod%0A def fit(self, X, y):%0A %22%22%22%0A Fits Naive Bayes classifier%0A %0A Args:%0A X (np.ndarray): Training data of shape%5Bn_samples, n_features%5D%0A y (np.ndarray): Target values of shape%5Bn_samples, 1%5D%0A%0A Returns: an instance of self%0A %0A %22%22%22%0A return self%0A %0A @abc.abstractmethod%0A def predict(self, X):%0A %22%22%22%0A Args:%0A x (np.array): Training data of shape%5B1, n_features%5D%0A Currently, only vector of single sample is supported%0A %0A Returns: predicted class of sample%0A%0A Raises:%0A ValueError if model has not been fit%0A %22%22%22%0A return self%0A%0A
837e9db39b2c9010a5cc43f21821b5dec90a18b1
add rdds.fileio to setup.py
python/setup.py
python/setup.py
#!/usr/bin/env python from setuptools import setup import thunder setup( name='thunder-python', version=str(thunder.__version__), description='Large-scale neural data analysis in Spark', author='The Freeman Lab', author_email='the.freeman.lab@gmail.com', url='https://github.com/freeman-lab/thunder', packages=['thunder', 'thunder.clustering', 'thunder.decoding', 'thunder.factorization', 'thunder.lib', 'thunder.rdds', 'thunder.regression', 'thunder.standalone', 'thunder.utils', 'thunder.viz'], scripts = ['bin/thunder', 'bin/thunder-submit', 'bin/thunder-ec2'], package_data = {'thunder.utils': ['data/fish.txt', 'data/iris.txt'], 'thunder.lib': ['thunder_2.10-' + str(thunder.__version__) + '.jar']}, long_description=open('README.rst').read(), install_requires=open('requirements.txt').read().split() )
Python
0
@@ -509,24 +509,61 @@ nder.rdds',%0A + 'thunder.rdds.fileio',%0A
ee3b5d0d14403bd5964f0609eb48848833bff2c0
Add a draft for a backup class
quilt/backup.py
quilt/backup.py
Python
0
@@ -0,0 +1,1608 @@ +# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:%0A%0A# python-quilt - A Python implementation of the quilt patch system%0A#%0A# Copyright (C) 2012 Bj%C3%B6rn Ricks %3Cbjoern.ricks@googlemail.com%3E%0A#%0A# This library is free software; you can redistribute it and/or%0A# modify it under the terms of the GNU Lesser General Public%0A# License as published by the Free Software Foundation; either%0A# version 2.1 of the License, or (at your option) any later version.%0A%0A# This library is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU%0A# Lesser General Public License for more details.%0A%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this library; if not, write to the Free Software%0A# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA%0A# 02110-1301 USA%0A%0Afrom quilt.utils import Directory, File%0A%0Aclass Backup(object):%0A%0A %22%22%22 Class to backup files%0A%0A This class should be exented in future to support all functions of quilts%0A backup-files script.%0A %22%22%22%0A%0A def __init__(self, filename):%0A self.filename = filename%0A%0A def backup(self, dest_dir):%0A file = File(self.filename)%0A if file.exists():%0A if not isinstance(dest_dir, Directory):%0A dest_dir = Directory(dest_dir)%0A dest_dir.create()%0A file.copy(dest_dir)%0A else:%0A dest_dir = dest_dir + file.get_directory()%0A dest_dir.create()%0A dest_file = dest_dir + file%0A dest_file.touch()%0A%0A
3ab998b022ff69c21c470de397f12557a1141168
Add tests for photo.utils
src/photo/tests/test_utils.py
src/photo/tests/test_utils.py
Python
0
@@ -0,0 +1,2478 @@ +%22%22%22%0ATests for photo.utils%0A%22%22%22%0Aimport uuid%0A%0Afrom django.test import TestCase%0A%0Afrom photo import utils%0A%0A# pylint: disable=too-few-public-methods%0Aclass DummyInstance:%0A %22%22%22%0A Dummy instance object for passing into UploadToPathAndRename%0A %22%22%22%0A pk = None # pylint: disable=invalid-name%0A%0Aclass UploadToPathAndRenameTestCase(TestCase):%0A %22%22%22%0A Tests for utils.UploadToPathAndRename%0A %22%22%22%0A def setUp(self):%0A self.upload_to_path_and_rename = utils.UploadToPathAndRename('test')%0A self.instance = DummyInstance()%0A%0A def test_extension_preserved(self):%0A %22%22%22%0A Verify that UploadToPathAndRename preserves file extensions.%0A %22%22%22%0A result = self.upload_to_path_and_rename(self.instance, %22filename.jpg%22)%0A ext = result.split('.')%5B-1%5D%0A self.assertEqual(ext, 'jpg', %22New filename has wrong extension%22)%0A%0A def test_path_appended(self):%0A %22%22%22%0A Verify that UploadToPathAndRename appends specified path.%0A %22%22%22%0A result = self.upload_to_path_and_rename(self.instance, %22filename.jpg%22)%0A path = result.split('/')%5B0%5D%0A self.assertEqual(path, 'test', %22New filename has wrong path%22)%0A%0A def test_instance_with_no_pk(self):%0A %22%22%22%0A Verify handling when instance does not have a primary key%0A %22%22%22%0A result = self.upload_to_path_and_rename(self.instance, %22filename.jpg%22)%0A generated_uuid_string = result.split('/')%5B1%5D.split('.')%5B0%5D%0A generated_uuid = uuid.UUID(generated_uuid_string, version=4)%0A self.assertNotEqual(generated_uuid, self.instance.pk,%0A %22New filename did not get a random UUID%22)%0A%0A def test_instance_with_uuid_pk(self):%0A %22%22%22%0A Verify handling when instance has a UUID primary key%0A %22%22%22%0A self.instance.pk = uuid.uuid4() # pylint: disable=invalid-name%0A result = self.upload_to_path_and_rename(self.instance, %22filename.jpg%22)%0A generated_uuid_string = result.split('/')%5B1%5D.split('.')%5B0%5D%0A generated_uuid = uuid.UUID(generated_uuid_string, version=4)%0A self.assertEqual(generated_uuid, self.instance.pk,%0A %22New filename does not match UUID of instance%22)%0A%0A def test_insance_with_non_uuid_pk(self):%0A %22%22%22%0A Verify handling when instance has a non-UUID primary key%0A %22%22%22%0A self.instance.pk = %22test%22%0A with self.assertRaises(TypeError):%0A self.upload_to_path_and_rename(self.instance, %22filename.jpg%22)%0A
5bad99e17f62c325f9cb9dad1efae993b9c2a4f2
Add Custom Attributes to assessment template
src/ggrc/models/assessment_template.py
src/ggrc/models/assessment_template.py
# Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: peter@reciprocitylabs.com # Maintained By: peter@reciprocitylabs.com """A module containing the implementation of the assessment template entity.""" import json from sqlalchemy.orm import validates from ggrc import db from ggrc.models.exceptions import ValidationError from ggrc.models.mixins import Base from ggrc.models.mixins import Slugged from ggrc.models.mixins import Titled from ggrc.models import assessment from ggrc.models.mixins import CustomAttributable from ggrc.models.reflection import PublishOnly from ggrc.models.relationship import Relatable from ggrc.models.types import JsonType class AssessmentTemplate(assessment.AuditRelationship, Slugged, Base, Relatable, Titled, CustomAttributable, db.Model): """A class representing the assessment template entity. An Assessment Template is a template that allows users for easier creation of multiple Assessments that are somewhat similar to each other, avoiding the need to repeatedly define the same set of properties for every new Assessment object. """ __tablename__ = "assessment_templates" _mandatory_default_people = ("assessors", "verifiers") # the type of the object under assessment template_object_type = db.Column(db.String, nullable=True) # whether to use the control test plan as a procedure test_plan_procedure = db.Column(db.Boolean, nullable=False, default=False) # procedure description procedure_description = db.Column(db.Text, nullable=True) # the people that should be assigned by default to each assessment created # within the releated audit default_people = db.Column(JsonType, nullable=False) # labels to show to the user in the UI for various default people values DEFAULT_PEOPLE_LABELS = { "Object Owners": "Object Owners", "Audit Lead": "Audit Lead", "Auditors": "Auditors", "Primary Assessor": "Principal Assessor", "Secondary Assessors": "Secondary Assessors", "Primary Contact": "Primary Contact", "Secondary Contact": "Secondary Contact", } _title_uniqueness = False # REST properties _publish_attrs = [ "template_object_type", "test_plan_procedure", "procedure_description", "default_people", PublishOnly("DEFAULT_PEOPLE_LABELS") ] _aliases = { "default_assessors": { "display_name": "Default Assessors", "mandatory": True, "filter_by": "_nop_filter", }, "default_verifier": { "display_name": "Default Verifier", "mandatory": True, "filter_by": "_nop_filter", }, "default_test_plan": { "display_name": "Default Test Plan", "filter_by": "_nop_filter", }, "test_plan_procedure": { "display_name": "Use Control Test Plan", "mandatory": False, }, "template_object_type": { "display_name": "Object Under Assessment", "mandatory": True, }, } @classmethod def _nop_filter(cls, _): """No operation filter. This is used for objects for which we can not implement a normal sql query filter. Example is default_verifier field that is a json string in the db and we can not create direct queries on json fields. """ return None @classmethod def generate_slug_prefix_for(cls, obj): return "TEMPLATE" @validates('default_people') def validate_default_people(self, key, value): """Check that default people lists are not empty. Check if the default_people contains both assessors and verifiers. The values of those fields must be truthy, and if the value is a string it must be a valid default people label. If the value is not a string, it should be a list of valid user ids, but that is too expensive to test in this validator. """ # pylint: disable=unused-argument parsed = json.loads(value) for mandatory in self._mandatory_default_people: mandatory_value = parsed.get(mandatory) if (not mandatory_value or isinstance(mandatory_value, list) and any(not isinstance(p_id, int) for p_id in mandatory_value) or isinstance(mandatory_value, basestring) and mandatory_value not in self.DEFAULT_PEOPLE_LABELS): raise ValidationError( 'Invalid value for default_people.{field}. Expected a people ' 'label in string or a list of int people ids, recieved {value}.' .format(field=mandatory, value=mandatory_value), ) return value
Python
0
@@ -633,24 +633,73 @@ ttributable%0A +from ggrc.models.reflection import AttributeInfo%0A from ggrc.mo @@ -3187,16 +3187,192 @@ %7D,%0A + %22template_custom_attributes%22: %7B%0A %22display_name%22: %22Custom Attributes%22,%0A %22mandatory%22: True,%0A %22type%22: AttributeInfo.Type.SPECIAL_MAPPING,%0A %7D, %0A %7D%0A%0A
dea182f5618f7590ee7e8fb6d2872ac60c6b6069
Add setup.py to afni.
nipype/interfaces/afni/setup.py
nipype/interfaces/afni/setup.py
Python
0.000178
@@ -0,0 +1,343 @@ +def configuration(parent_package='',top_path=None):%0A from numpy.distutils.misc_util import Configuration%0A%0A config = Configuration('afni', parent_package, top_path)%0A%0A config.add_data_dir('tests')%0A%0A return config%0A%0Aif __name__ == '__main__':%0A from numpy.distutils.core import setup%0A setup(**configuration(top_path='').todict())%0A
fdf6dfbb7f82252cfe1e07719e3658fc529f47aa
Create hello-friend.py
baby-steps/hello-friend.py
baby-steps/hello-friend.py
Python
0.992038
@@ -0,0 +1,21 @@ +print %22hell0-fr1end%22%0A
545bc9ae80fb9b141613e8a107560d6d868b5bcd
adding Solar System Universe
EXOSIMS/SimulatedUniverse/SolarSystemUniverse.py
EXOSIMS/SimulatedUniverse/SolarSystemUniverse.py
Python
0.998929
@@ -0,0 +1,2190 @@ +from EXOSIMS.Prototypes.SimulatedUniverse import SimulatedUniverse%0Aimport numpy as np%0Afrom EXOSIMS.util.eccanom import eccanom%0Aimport astropy.units as u%0Aimport astropy.constants as const%0A%0Aclass SolarSystemUniverse(SimulatedUniverse):%0A %22%22%22Simulated Universe module based on SAG13 Planet Population module.%0A %0A %22%22%22%0A%0A def __init__(self, **specs):%0A %0A SimulatedUniverse.__init__(self, **specs)%0A%0A def gen_physical_properties(self, **specs):%0A %22%22%22Generating universe based on SAG13 planet radius and period sampling.%0A %0A All parameters except for albedo and mass are sampled, while those are%0A calculated via the physical model.%0A %0A %22%22%22%0A %0A PPop = self.PlanetPopulation%0A PPMod = self.PlanetPhysicalModel%0A TL = self.TargetList%0A %0A %0A nPlans = 8*TL.nStars #occurrence rate per system is fixed at 8%0A self.nPlans = nPlans%0A plan2star = np.ones(nPlans)*8%0A self.plan2star = plan2star.astype(int)%0A %0A # sample all of the orbital and physical parameters%0A self.I, self.O, self.w = PPop.gen_angles(self.nPlans)%0A if self.commonSystemInclinations == True: #OVERWRITE I with TL.I+dI%0A self.I = TL.I%5Bself.plan2star%5D%0A%0A self.a, self.e, self.p, self.Rp = PPop.gen_plan_params(self.nPlans)%0A%0A self.gen_M0() # initial mean anomaly%0A self.Mp = self.gen_solar_system_planet_mass(self.nPlans) # mass #TODO grab from Tables%0A self.phiIndex = np.tile(np.arange(8),(TL.nStars)) #assign planet phase functions to planets%0A%0A def gen_solar_system_planet_mass(self,nPlans):%0A %22%22%22 Generated planet masses for each planet%0A Args:%0A float:%0A nPlan, the number of planets%0A Returns:%0A ndarray:%0A Mp_tiled, the masses of each planet in kg%0A %22%22%22%0A%0A Mp_orig = np.asarray(%5B3.3022*10**23,4.869*10**24,5.9742*10**24,6.4191*10**23,1.8988*10**27,5.685*10**26,8.6625*10**25,1.0278*10**26%5D)*u.kg%0A %0A #Tile them%0A numTiles = int(nPlans/8)%0A Mp_tiled = np.tile(Mp_orig,(numTiles))%0A return Mp_tiled%0A%0A
709ec407d333a624ff4476a81bc0f6ebb86f055a
add comments handle python file
data/Reddit/moderators_subreddit_comments.py
data/Reddit/moderators_subreddit_comments.py
Python
0
@@ -0,0 +1,1645 @@ +# -*- coding: utf-8 -*-%0A# @Author: Lich_%0A# @Date: 2016-11-26 18:14:52%0A# @Last Modified by: LichAmnesia%0A# @Last Modified time: 2016-11-26 13:53:35%0A%0Aimport json%0Aimport os%0A%0A%0A# generate the moderators from moderators file. the output is the moderators_subreddit file%0A%0Adef getmoderators():%0A file = open('moderators_subreddit.csv', 'w')%0A file.write('moderators' + '%5Ct' + 'subreddit' + '%5Cn')%0A with open('E:%5C%5CWorkspace%5C%5CNetworkData%5C%5Cmoderators') as fileobject:%0A for line in fileobject:%0A js = json.loads(line.replace('%5Cn',''))%0A moderators = js%5B'moderators'%5D%0A for moderator in moderators:%0A file.write(moderator%5B'name'%5D + '%5Ct' + js%5B'subreddit'%5D + '%5Cn')%0A # print(moderator%5B'name'%5D, js%5B'subreddit'%5D)%0A file.close()%0A%0A# This is to generate the comments%0A# the line of the RC 2016-09 is 67,000,000 lines%0Adef getComments():%0A moderators_set = set(%5B%5D)%0A with open('moderators_subreddit') as fileobject:%0A for line in fileobject:%0A moderators_set.add(line.split()%5B0%5D)%0A cnt = 0%0A with open('E:%5C%5CWorkspace%5C%5CNetworkData%5C%5CRC_2016-09', 'r') as fileobject:%0A with open('comments', 'w+') as file:%0A for line in fileobject:%0A js = json.loads(line.replace('%5Cn',''))%0A author = js%5B'author'%5D%0A if author in moderators_set:%0A del js%5B'body'%5D%0A file.write(json.dumps(js) + '%5Cn')%0A cnt += 1%0A if cnt %25 1000000 == 0:%0A file.flush()%0A os.fsync(file)%0A print(cnt)%0A file.close()%0A%0Agetmoderators()
5c278ec8afe7fd97c0f3a4b45c0acc25706afd1e
add python_solve.py
dune-burgers/pymor-wrapper/python_solve.py
dune-burgers/pymor-wrapper/python_solve.py
Python
0.998873
@@ -0,0 +1,472 @@ +import sys%0A%0Afrom pymor.tools import mpi%0Afrom pymor.discretizations.mpi import mpi_wrap_discretization%0Afrom pymor.vectorarrays.mpi import MPIVectorArrayAutoComm%0A%0Afrom dune_burgers import discretize_dune_burgers%0A%0Afilename = sys.argv%5B1%5D%0Aexponent = float(sys.argv%5B2%5D)%0A%0Aobj_id = mpi.call(mpi.function_call_manage, discretize_dune_burgers, filename)%0Ad = mpi_wrap_discretization(obj_id, use_with=True, with_apply2=False, array_type=MPIVectorArrayAutoComm)%0A%0AU = d.solve(exponent)%0A
b4729cfbff3bdf11da73436d4f927f0ffb9d1b40
Add montage func
mnefun/misc.py
mnefun/misc.py
Python
0.000001
@@ -0,0 +1,1796 @@ +# -*- coding: utf-8 -*-%0A%22%22%22Miscellaneous utilities.%22%22%22%0A%0Aimport numpy as np%0A%0Aimport mne%0A%0A%0Adef make_montage(info, kind, check=False):%0A from . import _reorder%0A assert kind in ('mgh60', 'mgh70', 'uw_70', 'uw_60')%0A picks = mne.pick_types(info, meg=False, eeg=True, exclude=())%0A if kind in ('mgh60', 'mgh70'):%0A ch_names = mne.utils._clean_names(%0A %5Binfo%5B'ch_names'%5D%5Bpick%5D for pick in picks%5D, remove_whitespace=True)%0A if kind == 'mgh60':%0A assert len(ch_names) in (59, 60)%0A else:%0A assert len(ch_names) in (70,)%0A montage = mne.channels.read_montage(kind, ch_names=ch_names)%0A else:%0A ch_names = getattr(_reorder, 'ch_names_' + kind)%0A ch_names = ch_names%0A montage = mne.channels.read_montage('standard_1020', ch_names=ch_names)%0A assert len(montage.ch_names) == len(ch_names)%0A montage.ch_names = %5B'EEG%2503d' %25 ii for ii in range(1, 61)%5D%0A sphere = mne.make_sphere_model('auto', 'auto', info)%0A montage.pos /= np.linalg.norm(montage.pos, axis=-1, keepdims=True)%0A montage.pos *= sphere.radius%0A montage.pos += sphere%5B'r0'%5D%0A info = mne.pick_info(info, picks)%0A eeg_pos = np.array(%5Bch%5B'loc'%5D%5B:3%5D for ch in info%5B'chs'%5D%5D)%0A assert len(eeg_pos) == len(montage.pos), (len(eeg_pos), len(montage.pos))%0A if check:%0A from mayavi import mlab%0A mlab.figure(size=(800, 800))%0A mlab.points3d(*sphere%5B'r0'%5D, scale_factor=2 * sphere.radius,%0A color=(0., 0., 1.), opacity=0.1, mode='sphere')%0A mlab.points3d(*montage.pos.T, scale_factor=0.01,%0A color=(1, 0, 0), mode='sphere', opacity=0.5)%0A mlab.points3d(*eeg_pos.T, scale_factor=0.005, color=(1, 1, 1),%0A mode='sphere', opacity=1)%0A return montage, sphere%0A
3ed04c4ba438c9dcbea94e6b48a06316fcdac4d3
diofant task 002
diofant/diofant_002.py
diofant/diofant_002.py
Python
0.99999
@@ -0,0 +1,718 @@ +#!/usr/bin/env python3%0A%0A# %D0%98%D0%BC%D0%B5%D0%B5%D1%82%D1%81%D1%8F %D1%80%D1%8F%D0%B4 %D1%87%D0%B8%D1%81%D0%B5%D0%BB %D0%A4%D0%B8%D0%B1%D0%BE%D0%BD%D0%B0%D1%87%D1%87%D0%B8: 1, 1, 2, 3, 5, 8, 13, 21,...%0A# (%D0%BA%D0%B0%D0%B6%D0%B4%D1%8B%D0%B9 %D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9 %D1%87%D0%BB%D0%B5%D0%BD %D1%80%D1%8F%D0%B4%D0%B0 %D1%80%D0%B0%D0%B2%D0%B5%D0%BD %D1%81%D1%83%D0%BC%D0%BC%D0%B5 %D0%B4%D0%B2%D1%83%D1%85 %D0%BF%D1%80%D0%B5%D0%B4%D1%8B%D0%B4%D1%83%D1%89%D0%B8%D1%85, %D0%BD%D0%B0%D1%87%D0%B8%D0%BD%D0%B0%D0%B5%D1%82%D1%81%D1%8F %D1%80%D1%8F%D0%B4 %D1%81 %D0%B4%D0%B2%D1%83%D1%85 %D0%B5%D0%B4%D0%B8%D0%BD%D0%B8%D1%86).%0A# %D0%9D%D0%B0%D0%B9%D1%82%D0%B8 %D1%81%D1%83%D0%BC%D0%BC%D1%83 %D1%87%D0%BB%D0%B5%D0%BD%D0%BE%D0%B2 %D1%8D%D1%82%D0%BE%D0%B3%D0%BE %D1%80%D1%8F%D0%B4%D0%B0, %D0%BC%D0%B5%D0%BD%D1%8C%D1%88%D0%B8%D1%85 %D0%BE%D0%B4%D0%BD%D0%BE%D0%B3%D0%BE %D0%BC%D0%B8%D0%BB%D0%BB%D0%B8%D0%B0%D1%80%D0%B4%D0%B0 %D0%B8 %D0%BD%D0%B0%D1%85%D0%BE%D0%B4%D1%8F%D1%89%D0%B8%D1%85%D1%81%D1%8F %D0%BD%D0%B0 %D0%BD%D0%B5%D1%87%D0%B5%D1%82%D0%BD%D1%8B%D1%85 %D0%BF%D0%BE%D0%B7%D0%B8%D1%86%D0%B8%D1%8F%D1%85.%0A# %D0%92%D0%BD%D0%B8%D0%BC%D0%B0%D0%BD%D0%B8%D0%B5! %D0%9E%D1%82%D0%B2%D0%B5%D1%82%D0%BE%D0%BC %D0%BD%D0%B0 %D0%B7%D0%B0%D0%B4%D0%B0%D1%87%D1%83 %D1%8F%D0%B2%D0%BB%D1%8F%D0%B5%D1%82%D1%81%D1%8F %D1%86%D0%B5%D0%BB%D0%BE%D0%B5 %D1%87%D0%B8%D1%81%D0%BB%D0%BE %D0%B2 %D0%B4%D0%B5%D1%81%D1%8F%D1%82%D0%B8%D1%87%D0%BD%D0%BE%D0%B9 %D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8 %D0%B1%D0%B5%D0%B7 %D0%BF%D1%80%D0%BE%D0%B1%D0%B5%D0%BB%D0%BE%D0%B2.%0A%0Avalue = 1%0Aprev_value = 0%0Acur_position = 1%0Atotal = 0%0A%0Adef next_num(position, number, prev_number):%0A return (number + prev_number, number)%0A%0Awhile(value %3C 1000000000):%0A if cur_position %25 2 != 0:%0A total = total + value%0A value, prev_value = next_num(cur_position, value, prev_value)%0A cur_position = cur_position + 1%0A%0Aprint(%22Total: %7B%7D%22.format(total))%0A
ded9c39402ca9cf7adfaaebbf06c196048d48db9
Add presubmit check for run-bindings-tests
Source/bindings/PRESUBMIT.py
Source/bindings/PRESUBMIT.py
Python
0.000071
@@ -0,0 +1,2733 @@ +# Copyright (C) 2013 Google Inc. All rights reserved.%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions are%0A# met:%0A#%0A# * Redistributions of source code must retain the above copyright%0A# notice, this list of conditions and the following disclaimer.%0A# * Redistributions in binary form must reproduce the above%0A# copyright notice, this list of conditions and the following disclaimer%0A# in the documentation and/or other materials provided with the%0A# distribution.%0A# * Neither the name of Google Inc. nor the names of its%0A# contributors may be used to endorse or promote products derived from%0A# this software without specific prior written permission.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS%0A# %22AS IS%22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT%0A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR%0A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT%0A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,%0A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT%0A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,%0A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY%0A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT%0A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE%0A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.%0A%0A%22%22%22Blink bindings presubmit script%0A%0ASee http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts%0Afor more details about the presubmit API built into gcl.%0A%22%22%22%0A%0A%0Adef _RunBindingsTests(input_api, output_api):%0A if input_api.is_committing:%0A message_type = output_api.PresubmitError%0A else:%0A message_type = output_api.PresubmitPromptWarning%0A%0A pardir = input_api.os_path.pardir%0A run_bindings_tests_path = input_api.os_path.join(input_api.PresubmitLocalPath(), pardir, pardir, 'Tools', 'Scripts', 'run-bindings-tests')%0A cmd_name = 'run-bindings-tests'%0A if input_api.platform == 'win32':%0A # Windows needs some help.%0A cmd = %5Binput_api.python_executable, run_bindings_tests_path%5D%0A else:%0A cmd = %5Brun_bindings_tests_path%5D%0A test_cmd = input_api.Command(%0A name=cmd_name,%0A cmd=cmd,%0A kwargs=%7B%7D,%0A message=message_type)%0A if input_api.verbose:%0A print('Running ' + cmd_name)%0A return input_api.RunTests(%5Btest_cmd%5D)%0A%0A%0Adef CheckChangeOnUpload(input_api, output_api):%0A return _RunBindingsTests(input_api, output_api)%0A%0A%0Adef CheckChangeOnCommit(input_api, output_api):%0A return _RunBindingsTests(input_api, output_api)%0A
e94d5f86d983f6b930d41abaed56cba05e5fa030
test run_async
corehq/apps/userreports/tests/test_async_indicators.py
corehq/apps/userreports/tests/test_async_indicators.py
Python
0.000005
@@ -0,0 +1,2340 @@ +from django.test import SimpleTestCase%0A%0Afrom corehq.apps.userreports.models import DataSourceConfiguration%0Afrom corehq.apps.userreports.util import get_indicator_adapter%0A%0A%0Aclass RunAsynchronousTest(SimpleTestCase):%0A def _create_data_source_config(self, indicators=None):%0A default_indicator = %5B%7B%0A %22type%22: %22expression%22,%0A %22column_id%22: %22laugh_sound%22,%0A %22datatype%22: %22string%22,%0A %22expression%22: %7B%0A 'type': 'named',%0A 'name': 'laugh_sound'%0A %7D%0A %7D%5D%0A%0A return DataSourceConfiguration.wrap(%7B%0A 'display_name': 'Mother Indicators',%0A 'doc_type': 'DataSourceConfiguration',%0A 'domain': 'test',%0A 'referenced_doc_type': 'CommCareCase',%0A 'table_id': 'mother_indicators',%0A 'configured_filter': %7B%7D,%0A 'configured_indicators': indicators or default_indicator%0A %7D)%0A%0A def test_async_not_configured(self):%0A indicator_configuration = self._create_data_source_config()%0A adapter = get_indicator_adapter(indicator_configuration)%0A self.assertFalse(adapter.run_asynchronous)%0A%0A def test_async_configured(self):%0A indicator_configuration = self._create_data_source_config()%0A indicator_configuration.asynchronous = True%0A adapter = get_indicator_adapter(indicator_configuration)%0A self.assertTrue(adapter.run_asynchronous)%0A%0A def test_related_doc_expression(self):%0A indicator_configuration = self._create_data_source_config(%5B%7B%0A %22datatype%22: %22string%22,%0A %22type%22: %22expression%22,%0A %22column_id%22: %22confirmed_referral_target%22,%0A %22expression%22: %7B%0A %22type%22: %22related_doc%22,%0A %22related_doc_type%22: %22CommCareUser%22,%0A %22doc_id_expression%22: %7B%0A %22type%22: %22property_path%22,%0A %22property_path%22: %5B%22form%22, %22meta%22, %22userID%22%5D%0A %7D,%0A %22value_expression%22: %7B%0A %22type%22: %22property_path%22,%0A %22property_path%22: %5B%0A %22user_data%22,%0A %22confirmed_referral_target%22%0A %5D%0A %7D%0A %7D%0A %7D%5D)%0A%0A adapter = get_indicator_adapter(indicator_configuration)%0A self.assertTrue(adapter.run_asynchronous)%0A
d9d8e68c92fc808e43cf5ffe897541738f90d428
Add manage.py to support running project scripts
manage.py
manage.py
Python
0
@@ -0,0 +1,123 @@ +from flask_script import Manager%0A%0Afrom app import app%0A%0Amanager = Manager(app)%0A%0Aif __name__ == %22__main__%22:%0A manager.run()
6b34500741b4ef1f73fac0045805ab49dad579ba
product expression
doing-math-with-python/product_expression.py
doing-math-with-python/product_expression.py
Python
0.960891
@@ -0,0 +1,579 @@ +# -*- coding: utf-8 -*-%0A%22%22%22%0AProduct of two expressions%0A%0ACreated on Tue Feb 16 14:38:14 2016%0A%0A@author: Liu Lixiang%0A%22%22%22%0A%0Afrom sympy import expand, sympify, pprint%0Afrom sympy.core.sympify import SympifyError%0A%0A%0Adef product(expr1, expr2):%0A prod = expand(expr1*expr2)%0A pprint(prod)%0A%0Aif __name__=='__main__':%0A expr1 = input('Enter the first expression:')%0A expr2 = input('Enter the second expression:')%0A %0A try:%0A expr1 = sympify(expr1)%0A expr2 = sympify(expr2)%0A except SympifyError:%0A print('Invalid Input')%0A else:%0A product(expr1, expr2)%0A
fbd179d9d22a2eef6c2fb24152a441b85133e556
Add missing component of previous commit
lowfat/utils.py
lowfat/utils.py
Python
0.000002
@@ -0,0 +1,562 @@ +%22%22%22%0AThis module contains small utility classes and functions which do not clearly belong to one part of the project.%0A%22%22%22%0A%0Aimport enum%0A%0A%0Aclass ChoicesEnum(enum.Enum):%0A %22%22%22%0A Abstract Enum class to represent values in a Django CharField choices.%0A %22%22%22%0A @classmethod%0A def choices(cls):%0A %22%22%22%0A Get the list of choices for this class.%0A%0A The name of the enum field is used as the human readable name.%0A The value of the enum field is stored in the database.%0A %22%22%22%0A return tuple((tag.value, tag.name) for tag in cls)%0A
9199563bb21276102ca58dc6b7c99f593db863d4
Add test for call_actions_during_tree_build
tests/func/test_build_tree.py
tests/func/test_build_tree.py
Python
0.000002
@@ -0,0 +1,994 @@ +import pytest # noqa%0Afrom parglare import Grammar, Parser%0A%0A%0Adef test_call_actions_during_tree_build():%0A grammar = %22%22%22%0A Program: %22begin%22 MoveCommand* %22end%22;%0A MoveCommand: %22move%22 Direction;%0A Direction: %22up%22 %7C %22down%22 %7C %22left%22 %7C %22right%22;%0A %22%22%22%0A%0A g = Grammar.from_string(grammar)%0A%0A code = %22%22%22%0A begin%0A move left%0A move left%0A move up%0A move down%0A end%0A %22%22%22%0A%0A left_moves = %5B%5D%0A%0A def left_dir_collector(_, nodes):%0A %22%22%22Finds all 'left' moves and adds them into a list.%22%22%22%0A term = nodes%5B0%5D%0A if term.value == %22left%22:%0A left_moves.append(term)%0A%0A parser = Parser(g, build_tree=True,%0A actions=%7B%22Direction%22: left_dir_collector%7D)%0A parser.parse(code)%0A%0A # call_actions_during_tree_build is False by default, so left_dir_collector%0A # will not be called.%0A assert len(left_moves) == 0%0A%0A parser.call_actions_during_tree_build = True%0A parser.parse(code)%0A%0A assert len(left_moves) == 2%0A
9140b3249820d0dd86f7f85270327d9264841b50
Test for selecting mysql search backend
tests/search_backend_mysql.py
tests/search_backend_mysql.py
Python
0
@@ -0,0 +1,682 @@ +from wolis.test_case import WolisTestCase%0Afrom wolis import utils%0A%0Aclass SearchBackendMysqlTest(WolisTestCase):%0A @utils.restrict_database('mysql*')%0A @utils.restrict_phpbb_version('%3E=3.1.0')%0A def test_set_search_backend(self):%0A self.login('morpheus', 'morpheus')%0A self.acp_login('morpheus', 'morpheus')%0A %0A self.change_acp_knob(%0A link_text='Search settings',%0A check_page_text='Here you can define what search backend will be used',%0A name='config%5Bsearch_type%5D',%0A value='phpbb_search_fulltext_mysql',%0A confirm=True,%0A )%0A%0Aif __name__ == '__main__':%0A import unittest%0A unittest.main()%0A
3c3fe1e1f1884df47157c71584b7b6087bde7f10
add owner check, code borrowed from RoboDanny
cogs/utils/checks.py
cogs/utils/checks.py
Python
0
@@ -0,0 +1,200 @@ +from discord.ext import commands%0A%0Adef is_owner_check(message):%0A return message.author.id == '103714384802480128'%0A%0Adef is_owner():%0A return commands.check(lambda ctx: is_owner_check(ctx.message))%0A
ee88f6927dee820318bc821081138374b8f754f2
Create data_functions.py
data_functions.py
data_functions.py
Python
0.000261
@@ -0,0 +1,1619 @@ +import pandas as pd%0Aimport numpy as np%0A%0Adef load_data(path):%0A '''%0A (str) -%3E (pandas.DataFrame)%0A Loads the database and cleans the whitespace in STATIONS_ID.%0A %0A IMPORTANT: This function assumes you have the database stored in a text file in the directory.%0A '''%0A data = pd.read_csv(path, index_col = 2)%0A data%5B%22STATIONS_ID%22%5D = data%5B%22STATIONS_ID%22%5D.str.replace(' ', '')%0A data%5B%22STATIONS_ID%22%5D = data%5B%22STATIONS_ID%22%5D.convert_objects(convert_numeric=True)%0A return data%0A%0A%0Adef get_data(data, station_id, category = 3):%0A %22%22%22%0A (pandas.Dataframe, int, list) -%3E (pandas.DataFrame)%0A Returns desired information from the database about requested city and categories. Index is based on and sorted by date.%0A %0A station_id: The code for the requested city/station%0A %0A category: Can be an int or a list of desired variable(s). By default gets the air temperature.%0A %0A The codes for variables:%0A 0: Numerical Index%0A 1: STATIONS_ID%0A 2: QUALITAETS_NIVEAU%0A 3: Air Temperature / LUFTTEMPERATUR%0A 4: DAMPFDRUCK%0A 5: BEDECKUNGSGRAD%0A 6: LUFTDRUCK_STATIONSHOEHE%0A 7: REL_FEUCHTE%0A 8: WINDGESCHWINDIGKEIT%0A 9: Max Air Temperature%0A 10: Min Air Temperature%0A 11: LUFTTEMP_AM_ERDB_MINIMUM (?)%0A 12: Max Wind Speed / WINDSPITZE_MAXIMUM%0A 13: Precipitation Height / NIEDERSCHLAGSHOEHE (?)%0A 14: NIEDERSCHLAGSHOEHE_IND (?)%0A 15: Sunshine Duration%0A 16: Snow Height%0A %22%22%22%0A rlv_station = data%5Bdata.iloc%5B:, 1%5D == station_id%5D%0A selected = rlv_station.iloc%5B:, category%5D%0A return selected%0A
82906d8dabfd551c997569f2f36ecdfc1ef3057f
Create duplicates.py
Python/duplicates.py
Python/duplicates.py
Python
0.000391
@@ -0,0 +1,377 @@ +#The rem_dep method removes the duplicate values while maintaining the original order of the list.%0A%0Adef rem_dup(values):%0A output=%5B%5D%0A seen=set()%0A for val in values:%0A if val not in seen:%0A output.append(val)%0A seen.add(val)%0A return output %0A%0A#sample list to test code.%0A%0Avalues=%5B3,4,5,6,4,3,44,5,32,4,35,4,4,5,5%5D%0A%0Aprint rem_dup(values)%0A
8611ea1e23b8958be98a6d5c15bd66f08e46859f
Handle connection error when sending event to consul.
meerkat_libs/consul_client/__init__.py
meerkat_libs/consul_client/__init__.py
import json import logging import jwt import collections from os import environ import backoff as backoff import requests from meerkat_libs import authenticate CONSUL_URL = environ.get("CONSUL_URL", "http://nginx/consul") SUBMISSIONS_BUFFER_SIZE = environ.get("CONSUL_SUBMISSIONS_BUFFER_SIZE", 1000) DHIS2_EXPORT_ENABLED = environ.get("DHIS2_EXPORT_ENABLED", False) events_buffer = collections.defaultdict(list) def send_dhis2_events(uuid=None, raw_row=None, form_id=None, auth_token=None): if not DHIS2_EXPORT_ENABLED: return if not auth_token: logging.error("No authentication token provided.") return global events_buffer upload_payload = {'token': '', 'content': 'record', 'formId': form_id, 'formVersion': '', 'data': raw_row, 'uuid': uuid } # TODO: Should md5 be generated here? md5_of_body = "" events_buffer[form_id].append( { 'MessageId': uuid, 'ReceiptHandle': 'test-receipt-handle-1', 'MD5OfBody': md5_of_body, 'Body': upload_payload, 'Attributes': { 'test-attribute': 'test-attribute-value' } } ) if len(events_buffer[form_id]) > SUBMISSIONS_BUFFER_SIZE: logging.info("Sending batch of events to consul.") __send_events_from_buffer(form_id=form_id, auth_token=auth_token) def flush_dhis2_events(auth_token=None): if not DHIS2_EXPORT_ENABLED: return if not auth_token: logging.error("No authentication token provided.") return for form_id in events_buffer: logging.info("Clearing Consul Client event buffer for %s.", form_id) __send_events_from_buffer(form_id=form_id, auth_token=auth_token) def __send_events_from_buffer(form_id=None, auth_token=None): global events_buffer json_payload = json.dumps( {"formId": form_id, "Messages": events_buffer[form_id]} ) requests.post(CONSUL_URL + "/dhis2/export/submissions", headers=_auth_headers(auth_token), json=json_payload) events_buffer[form_id] = [] def _auth_headers(token): return {'authorization': f"Bearer {token}"}
Python
0
@@ -1997,24 +1997,37 @@ _id%5D%7D%0A )%0A + try:%0A requests @@ -2128,16 +2128,20 @@ ayload)%0A + even @@ -2164,16 +2164,164 @@ d%5D = %5B%5D%0A + except requests.exceptions.ChunkedEncodingError:%0A logging.error(%22Failed to send chunk of events. Count %25i%22, len(events_buffer%5Bform_id%5D))%0A %0A%0Adef _a
f666560f9ffa2323b8a125e3ad3d3faf6bd5b3de
add command to grant sms gateway permissions
corehq/apps/smsbillables/management/commands/add_sms_gateway_permissions.py
corehq/apps/smsbillables/management/commands/add_sms_gateway_permissions.py
Python
0.000009
@@ -0,0 +1,3066 @@ +from django.contrib.auth.models import User%0Afrom django.core.management import BaseCommand%0A%0Afrom django_prbac.models import Grant, Role, UserRole%0A%0Afrom corehq import privileges%0A%0A%0Aclass Command(BaseCommand):%0A help = 'Grants the user(s) specified the privilege to access global sms gateways'%0A%0A def add_arguments(self, parser):%0A parser.add_argument(%0A 'usernames',%0A nargs=%22*%22,%0A )%0A parser.add_argument(%0A '--remove-user',%0A action='store_true',%0A default=False,%0A help='Remove the users specified from the DEV_SUPPORT_TEAM privilege',%0A )%0A%0A def handle(self, usernames, **options):%0A dev_support_role = Role.objects.get_or_create(%0A name=%22Dimagi Dev and Support Team%22,%0A slug=privileges.DEV_SUPPORT_TEAM,%0A )%5B0%5D%0A global_sms_gateway_access = Role.objects.get_or_create(%0A name=%22Accounting Admin%22,%0A slug=privileges.GLOBAL_SMS_GATEWAY,%0A )%5B0%5D%0A if not dev_support_role.has_privilege(global_sms_gateway_access):%0A Grant.objects.create(%0A from_role=dev_support_role,%0A to_role=global_sms_gateway_access,%0A )%0A remove_user = options%5B'remove_user'%5D%0A%0A for username in usernames:%0A try:%0A user = User.objects.get(username=username)%0A try:%0A user_role = UserRole.objects.get(user=user)%0A except UserRole.DoesNotExist:%0A user_privs = Role.objects.get_or_create(%0A name=%22Privileges for %25s%22 %25 user.username,%0A slug=%22%25s_privileges%22 %25 user.username,%0A )%5B0%5D%0A user_role = UserRole.objects.create(%0A user=user,%0A role=user_privs,%0A )%0A%0A if remove_user:%0A try:%0A # remove grant object%0A grant = Grant.objects.get(%0A from_role=user_role.role,%0A to_role=dev_support_role%0A )%0A grant.delete()%0A print(%22Removed %25s from the operations team%22%0A %25 user.username)%0A except Grant.DoesNotExist:%0A print(%22The user %25s was never part of the operations %22%0A %22team. Leaving alone.%22 %25 user.username)%0A elif not user_role.has_privilege(dev_support_role):%0A Grant.objects.create(%0A from_role=user_role.role,%0A to_role=dev_support_role,%0A )%0A print(%22Added %25s to the Dev and Support team%22 %25 user.username)%0A else:%0A print(%22User %25s is already part of the Dev and Support team%22%0A %25 user.username)%0A%0A except User.DoesNotExist:%0A print(%22User %25s does not exist%22 %25 username)%0A
ff82f56b8ea901a30478b11a61f8ca52b23346bd
Add a test case for guessing the BuildDir associated with a subdirectory argument.
test/BuildDir/guess-subdir.py
test/BuildDir/guess-subdir.py
Python
0.997656
@@ -0,0 +1,2127 @@ +#!/usr/bin/env python%0A#%0A# __COPYRIGHT__%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining%0A# a copy of this software and associated documentation files (the%0A# %22Software%22), to deal in the Software without restriction, including%0A# without limitation the rights to use, copy, modify, merge, publish,%0A# distribute, sublicense, and/or sell copies of the Software, and to%0A# permit persons to whom the Software is furnished to do so, subject to%0A# the following conditions:%0A#%0A# The above copyright notice and this permission notice shall be included%0A# in all copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY%0A# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE%0A# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND%0A# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE%0A# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION%0A# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION%0A# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.%0A#%0A%0A__revision__ = %22__FILE__ __REVISION__ __DATE__ __DEVELOPER__%22%0A%0A%22%22%22%0ATest that the logic that %22guesses%22 the associated BuildDir for a%0Asubdirectory correctly builds targets in the BuildDir subdirectory.%0A%22%22%22%0A%0Aimport TestSCons%0A%0Atest = TestSCons.TestSCons()%0A%0Atest.subdir(%5B'work'%5D, %5B'work', 'src'%5D)%0A%0Atest.write(%5B'work', 'SConstruct'%5D, %22%22%22%0Ac_builddir = r'%25s'%0ABuildDir(c_builddir, '.', duplicate=0)%0ASConscript(c_builddir + '/SConscript')%0A%22%22%22 %25 test.workpath('debug'))%0A%0Atest.write(%5B'work', 'SConscript'%5D, %22%22%22%0ASConscript('src/SConscript')%0A%22%22%22)%0A%0Atest.write(%5B'work', 'src', 'SConscript'%5D, %22%22%22%0Aenv = Environment(OBJSUFFIX='.obj',%0A PROGSUFFIX='.exe')%0Aenv.Program('test.cpp')%0A%22%22%22)%0A%0Atest.write(%5B'work', 'src', 'test.cpp'%5D, %22%22%22%5C%0A#include %3Cstdio.h%3E%0A#include %3Cstdlib.h%3E%0Aint%0Amain(int argc, char *argv%5B%5D)%0A%7B%0A printf(%22work/src/test.cpp%5C%5Cn%22);%0A%7D%0A%22%22%22)%0A%0Atest.run(chdir = 'work', arguments = '.')%0A%0Atest.must_exist(test.workpath('debug', 'src', 'test.obj'))%0Atest.must_exist(test.workpath('debug', 'src', 'test.exe'))%0A%0Atest.pass_test()%0A
f8fbf47ede2536d2d2a40ef70a648b11ea928132
Replace libraries of plumbing/models/exporters.py (issue #11).
imagedownloader/plumbing/models/exporters.py
imagedownloader/plumbing/models/exporters.py
from django.db import models from core import Process, Stream, FileStatus, File from libs.file import netcdf as nc import os import calendar import collections from libs import matrix class Compact(Process): class Meta: app_label = 'plumbing' extension = models.TextField() resultant_stream = models.ForeignKey(Stream, null=True, default=None) def do(self, stream): filename = "%spkg.%s.nc" % (self.resultant_stream.root_path,stream.tags.make_filename()) file = self.do_file(filename,stream) fs = FileStatus(file=file,stream=self.resultant_stream) fs.save() return self.resultant_stream def getdatetimenow(self): return datetime.utcnow().replace(tzinfo=pytz.UTC) def do_file(self, filename, stream): # create compact file and initialize basic settings begin_time = self.getdatetimenow() root, is_new = nc.open(filename) if is_new: sample, n = nc.open(stream.files.all()[0].file.completepath()) shape = sample.variables['data'].shape nc.getdim(root,'northing', shape[1]) nc.getdim(root,'easting', shape[2]) nc.getdim(root,'timing') v_lat = nc.getvar(root,'lat', 'f4', ('northing','easting',), 4) v_lon = nc.getvar(root,'lon', 'f4', ('northing','easting',), 4) v_lon[:] = nc.getvar(sample, 'lon')[:] v_lat[:] = nc.getvar(sample, 'lat')[:] nc.close(sample) nc.sync(root) self.do_var(root, 'data', stream) # save the content inside the compact file if not root is None: nc.close(root) f = File(localname=filename) f.save() return f def do_var(self, root, var_name, stream): count = 0 file_statuses = stream.sorted_files() shape = nc.getvar(root,'lat').shape for fs in file_statuses: # join the distributed content ch = fs.file.channel() v_ch = nc.getvar(root,var_name, 'f4', ('timing','northing','easting',), 4) v_ch_t = nc.getvar(root,var_name + '_time', 'f4', ('timing',)) try: rootimg, n = nc.open(fs.file.completepath()) data = (nc.getvar(rootimg, 'data'))[:] # Force all the channels to the same shape if not (data.shape[1:3] == shape): print data.shape[1:3], shape data = matrix.adapt(data, shape) if v_ch.shape[1] == data.shape[1] and v_ch.shape[2] == data.shape[2]: index = v_ch.shape[0] v_ch[index,:] = data v_ch_t[index] = calendar.timegm(fs.file.datetime().utctimetuple()) nc.close(rootimg) nc.sync(root) except RuntimeError, e: print fs.file.completepath()
Python
0
@@ -119,63 +119,74 @@ ort -os%0Aimport calendar%0Aimport collections%0Afrom libs +calendar%0Afrom libs import matrix%0Aimport pytz%0Afrom datetime import matr @@ -181,22 +181,24 @@ import -matrix +datetime %0A%0A%0Aclass
88e5b5117c747f21cc868503d2e5c123ca976585
Add tests for decorators
kolibri/core/tasks/test/test_decorators.py
kolibri/core/tasks/test/test_decorators.py
Python
0
@@ -0,0 +1,2731 @@ +import pytest%0A%0Afrom kolibri.core.tasks.decorators import task%0Afrom kolibri.core.tasks.exceptions import FunctionNotRegisteredAsJob%0Afrom kolibri.core.tasks.job import JobRegistry%0Afrom kolibri.core.tasks.job import RegisteredJob%0Afrom kolibri.core.tasks.utils import stringify_func%0A%0A%0A@pytest.fixture%0Adef registered_jobs():%0A JobRegistry.REGISTERED_JOBS.clear()%0A yield JobRegistry.REGISTERED_JOBS%0A JobRegistry.REGISTERED_JOBS.clear()%0A%0A%0Aclass TestTaskDecorators(object):%0A def test_task_register_without_args(self, registered_jobs):%0A @task.register%0A def add(x, y):%0A return x + y%0A%0A @task.register()%0A def subtract(x, y):%0A return x - y%0A%0A add_funcstr = stringify_func(add)%0A subtract_funcstr = stringify_func(subtract)%0A%0A assert isinstance(registered_jobs%5Badd_funcstr%5D, RegisteredJob)%0A assert isinstance(registered_jobs%5Bsubtract_funcstr%5D, RegisteredJob)%0A%0A def test_task_register_with_args(self, registered_jobs):%0A @task.register(%0A job_id=%22test%22, validator=id, permission=id, priority=task.priority.HIGH%0A )%0A def add(x, y):%0A return x + y%0A%0A add_funcstr = stringify_func(add)%0A%0A assert isinstance(registered_jobs%5Badd_funcstr%5D, RegisteredJob)%0A%0A assert add.task.job_id == %22test%22%0A assert add.task.validator == id%0A assert add.task.permission == id%0A assert add.task.priority == task.priority.HIGH%0A%0A def test_task_config_without_args(self, registered_jobs):%0A @task.config%0A @task.register%0A def add(x, y):%0A return x + y%0A%0A @task.config()%0A @task.register%0A def subtract(x, y):%0A return x - y%0A%0A assert add.task.group is None%0A assert add.task.track_progress is False%0A assert add.task.cancellable is False%0A%0A assert subtract.task.group is None%0A assert subtract.task.track_progress is False%0A assert subtract.task.cancellable is False%0A%0A def test_config_with_args(self, registered_jobs):%0A @task.config(group=%22math%22, cancellable=True, track_progress=True)%0A @task.register%0A def add(x, y):%0A return x + y%0A%0A assert add.task.group == %22math%22%0A assert add.task.cancellable is True%0A assert add.task.track_progress is True%0A%0A def test_task_config_without_register(self, registered_jobs):%0A with pytest.raises(FunctionNotRegisteredAsJob):%0A%0A @task.config%0A def add(x, y):%0A return x + y%0A%0A def test_task_register_config_preserves_functionality(self, registered_jobs):%0A @task.config%0A @task.register%0A def add(x, y):%0A return x + y%0A%0A assert add(2, 40) == 42%0A
a6be0447e07d388f5dc4942d7f9e391366185c78
Create solution.py
leetcode/easy/count_and_say/py/solution.py
leetcode/easy/count_and_say/py/solution.py
Python
0.000018
@@ -0,0 +1,544 @@ +class Solution(object):%0A def countAndSay(self, n):%0A %22%22%22%0A :type n: int%0A :rtype: str%0A %22%22%22%0A s = '1'%0A %0A while n %3E 1:%0A t = ''%0A cnt = 1%0A %0A for i in range(len(s)):%0A if i + 1 %3C len(s) and s%5Bi%5D == s%5Bi + 1%5D:%0A cnt += 1%0A else:%0A t += str(cnt) + s%5Bi%5D %0A cnt = 1%0A %0A s = t %0A n -= 1%0A %0A return s%0A
ff187730fa1ebd64984dbb6e91a8f04edae84548
Introduce module for CLI commands; implement data generating command
ngx_task/cli.py
ngx_task/cli.py
Python
0
@@ -0,0 +1,660 @@ +import os%0Afrom concurrent.futures import ThreadPoolExecutor, as_completed%0A%0Afrom ngx_task import settings, utils%0A%0A%0Adef generate_data():%0A if not os.path.exists(settings.DATA_DIR):%0A os.mkdir(settings.DATA_DIR, 0o755)%0A%0A files_to_submit = %5B'arc-%7B%7D.zip'.format(arc_num) for arc_num in range(1, 51)%5D%0A%0A with ThreadPoolExecutor() as pool:%0A futures_to_process = %7Bpool.submit(utils.archive_documents, filename): filename%0A for filename in files_to_submit%7D%0A for fut in as_completed(futures_to_process):%0A print('Complete %7B%7D'.format(futures_to_process%5Bfut%5D))%0A%0A print('All data has been generated')%0A
4ccf9b6135ca5c6317502ffd663d5de4d180eea3
Add migration for commit b52f572646f30a8a4f2fc2bec6fc31c8f498f33f
mcf_standard_browser/standards_review/migrations/0032_auto_20160307_1802.py
mcf_standard_browser/standards_review/migrations/0032_auto_20160307_1802.py
Python
0.000001
@@ -0,0 +1,1254 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.3 on 2016-03-07 18:02%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Aimport django.db.models.deletion%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('standards_review', '0031_auto_20160209_1255'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='dataset',%0A name='intrument',%0A field=models.TextField(default=''),%0A ),%0A migrations.AddField(%0A model_name='fragmentationspectrum',%0A name='collision_energy',%0A field=models.TextField(default=''),%0A ),%0A migrations.AddField(%0A model_name='fragmentationspectrum',%0A name='ms1_intensity',%0A field=models.FloatField(default=0.0),%0A ),%0A migrations.AddField(%0A model_name='xic',%0A name='collision',%0A field=models.TextField(default=''),%0A ),%0A migrations.AlterField(%0A model_name='standard',%0A name='molecule',%0A field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE,%0A to='standards_review.Molecule'),%0A ),%0A %5D%0A
bc5105d7e8263bcaf0be8cc88bff8438fa1972a4
add import script for ryedale
polling_stations/apps/data_collection/management/commands/import_ryedale.py
polling_stations/apps/data_collection/management/commands/import_ryedale.py
Python
0
@@ -0,0 +1,1616 @@ +%22%22%22%0AImports Ryedale%0A%22%22%22%0Afrom django.contrib.gis.geos import Point, GEOSGeometry%0A%0Afrom data_collection.management.commands import BaseKamlImporter%0A%0Aclass Command(BaseKamlImporter):%0A %22%22%22%0A Imports the Polling Station data from Ryedale Council%0A %22%22%22%0A council_id = 'E07000167'%0A districts_name = 'Thirsk_and_Malton_Wards.kml'%0A stations_name = 'Polling Stations Malton and Thirsk 07 05 2015.csv'%0A%0A def district_record_to_dict(self, record):%0A # this kml has no altitude co-ordinates so the data is ok as it stands%0A geojson = record.geom.geojson%0A%0A # The SRID for the KML is 4326 but the CSV is 2770 so we%0A # set it each time we create the polygon.%0A # We could probably do with a more elegant way of doing%0A # this longer term.%0A self._srid = self.srid%0A self.srid = 4326%0A poly = self.clean_poly(GEOSGeometry(geojson, srid=self.srid))%0A self.srid = self._srid%0A return %7B%0A 'internal_council_id': record%5B'Name'%5D.value,%0A 'name' : record%5B'Name'%5D.value,%0A 'area' : poly%0A %7D%0A%0A def station_record_to_dict(self, record):%0A location = Point(float(record.easting), float(record.northin), srid=self.srid)%0A address_parts = record.address.split(' ')%0A address = ' '.join(address_parts%5B:-2%5D)%0A return %7B%0A 'internal_council_id': record.postcode, # no id supplied, so we'll use the postcode%0A 'postcode': record.postcode,%0A 'address': address,%0A 'location': location%0A %7D%0A
d44bf960aa597e5a38fbc2f8f7dd18fbd704cf7c
add nova start vm to recovery
drcontroller/recovery/nova_start_vm.py
drcontroller/recovery/nova_start_vm.py
Python
0
@@ -0,0 +1,513 @@ +import novaclient.v1_1.client as novaclient%0Aimport ConfigParser%0A%0Adef start_vm(server_id):%0A cf=ConfigParser.ConfigParser()%0A cf.read(%22/home/eshufan/projects/drcontroller/drcontroller/conf/set.conf%22)%0A drc_ncred=%7B%7D%0A drc_ncred%5B'auth_url'%5D= cf.get(%22drc%22,%22auth_url%22)%0A drc_ncred%5B'username'%5D= cf.get(%22drc%22,%22user%22)%0A drc_ncred%5B'api_key'%5D = cf.get(%22drc%22,%22password%22)%0A drc_ncred%5B'project_id'%5D=cf.get(%22drc%22,%22tenant_name%22)%0A drc_nova = novaclient.Client(**drc_ncred)%0A drc_nova.servers.start(server_id)%0A%0A
6d03266160ce95a41b94561d707e399df78aae14
Add sanity test case comm_wifi_connect
lib/oeqa/runtime/sanity/comm_wifi_connect.py
lib/oeqa/runtime/sanity/comm_wifi_connect.py
Python
0.000143
@@ -0,0 +1,1568 @@ +import time%0Afrom oeqa.oetest import oeRuntimeTest%0A%0Aclass CommWiFiTest(oeRuntimeTest):%0A '''WiFi test by connmanctl'''%0A def test_wifi_connect_nopassword(self):%0A '''connmanctl to connect a no-password wifi AP'''%0A # un-block software rfkill lock%0A self.target.run('rfkill unblock all')%0A # Enable WiFi%0A (status, output) = self.target.run('connmanctl enable wifi')%0A self.assertEqual(status, 0, msg=%22Error messages: %25s%22 %25 output)%0A%0A # Scan nearby to get service of Guest%0A (status, output) = self.target.run('connmanctl scan wifi')%0A self.assertEqual(status, 0, msg=%22Error messages: %25s%22 %25 output)%0A (status, services) = self.target.run(%22connmanctl services %7C grep Guest %7C awk '%7Bprint $NF%7D'%22)%0A self.assertEqual(status, 0, msg=%22Not found AP service for Guest%22)%0A%0A # Do connection%0A (status, output) = self.target.run('connmanctl disconnect %25s' %25 services)%0A time.sleep(2)%0A i = 0%0A (status, output) = self.target.run('connmanctl connect %25s' %25 services)%0A while ( 'Connected ' not in output ):%0A (status, output) = self.target.run('connmanctl connect %25s' %25 services)%0A i = i + 1%0A if (i == 4):%0A break%0A %0A self.assertEqual(status, 0, msg=%22Error messages: %25s%22 %25 output)%0A time.sleep(15)%0A%0A # Check ip address by ifconfig command%0A (status, output) = self.target.run(%22ifconfig wlp2s0 %7C grep 'inet addr:'%22)%0A self.assertEqual(status, 0, msg=%22Error messages: %25s%22 %25 output)%0A %0A%0A
2cc6edec8295a216261fff09388a35e0805f474c
Add test to validate service names
tests/functional/test_service_names.py
tests/functional/test_service_names.py
Python
0.000001
@@ -0,0 +1,2437 @@ +# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22). You%0A# may not use this file except in compliance with the License. A copy of%0A# the License is located at%0A#%0A# http://aws.amazon.com/apache2.0/%0A#%0A# or in the %22license%22 file accompanying this file. This file is%0A# distributed on an %22AS IS%22 BASIS, WITHOUT WARRANTIES OR CONDITIONS OF%0A# ANY KIND, either express or implied. See the License for the specific%0A# language governing permissions and limitations under the License.%0Aimport re%0A%0Afrom nose.tools import assert_true%0Afrom botocore.session import get_session%0A%0ABLACKLIST = %5B%0A 'runtime.sagemaker',%0A%5D%0A%0A%0A# Service names are limited here to 50 characters here as that seems like a%0A# reasonable limit in the general case. Services can be added to the%0A# blacklist above to be given an exception.%0AVALID_NAME_REGEX = re.compile(%0A (%0A '%5Ba-z%5D' # Starts with a letter%0A '%5Ba-z0-9%5D*' # Followed by any number of letters or digits%0A '(-%5Ba-z0-9%5D+)*$' # Dashes are allowed as long as they aren't%0A # consecutive or at the end%0A ), re.M)%0AVALID_NAME_EXPLANATION = (%0A 'Service names must be made up entirely of lowercase alphanumeric '%0A 'characters and dashes. The name must start with a letter and may not end '%0A 'with a dash'%0A)%0AMIN_SERVICE_NAME_LENGTH = 2%0AMAX_SERVICE_NAME_LENGTH = 50%0A%0A%0Adef _assert_name_length(service_name):%0A if service_name not in BLACKLIST:%0A service_name_length = len(service_name)%0A assert_true(service_name_length %3E= MIN_SERVICE_NAME_LENGTH,%0A 'Service name must be greater than or equal to 2 '%0A 'characters in length.')%0A assert_true(service_name_length %3C= MAX_SERVICE_NAME_LENGTH,%0A 'Service name must be less than or equal to 50 '%0A 'characters in length.')%0A%0A%0Adef _assert_name_pattern(service_name):%0A if service_name not in BLACKLIST:%0A valid = VALID_NAME_REGEX.match(service_name) is not None%0A assert_true(valid, VALID_NAME_EXPLANATION)%0A%0A%0Adef test_service_names_are_valid():%0A session = get_session()%0A loader = session.get_component('data_loader')%0A service_names = loader.list_available_services('service-2')%0A for service_name in service_names:%0A yield _assert_name_length, service_name%0A yield _assert_name_pattern, service_name%0A
6ad9b8e65562c00607fe0fe9f92cdba3c022ef2b
Add initial version Teach First Oauth2 backend.
lms/djangoapps/student_account/teachfirst.py
lms/djangoapps/student_account/teachfirst.py
Python
0
@@ -0,0 +1,2121 @@ +from django.conf import settings%0Afrom social_core.backends.oauth import BaseOAuth2%0Aimport logging%0A%0Alog = logging.getLogger(__name__)%0A%0A%0Aclass TeachFirstOAuth2(BaseOAuth2):%0A %22%22%22TeachFirst OAuth2 authentication backend.%22%22%22%0A settings_dict = settings.CUSTOM_BACKENDS.get('teachfirst')%0A name = 'teachfirst-oauth2'%0A REDIRECT_STATE = False%0A STATE_PARAMETER = False%0A AUTHORIZATION_URL = settings_dict.get('AUTH_URL')%0A ACCESS_TOKEN_URL = settings_dict.get('ACCESS_TOKEN_URL')%0A USER_DATA_URL = settings_dict.get('USER_DATA_URL')%0A ACCESS_TOKEN_METHOD = 'POST'%0A%0A def auth_complete(self, *args, **kwargs):%0A %22%22%22Completes login process, must return user instance%22%22%22%0A self.process_error(self.data)%0A state = self.validate_state()%0A%0A response = self.request_access_token(%0A self.access_token_url(),%0A data=self.auth_complete_params(state),%0A headers=self.auth_headers(),%0A auth=self.auth_complete_credentials(),%0A method=self.ACCESS_TOKEN_METHOD%0A )%0A self.process_error(response)%0A return self.do_auth(response%5B'access_token'%5D, response=response,%0A *args, **kwargs)%0A%0A def auth_complete_params(self, state=None):%0A client_id, client_secret = self.get_key_and_secret()%0A return %7B%0A 'state': state,%0A 'grant_type': 'authorization_code',%0A 'code': self.data.get('code', ''), # server response code%0A 'client_id': client_id,%0A 'client_secret': client_secret,%0A 'redirect_uri': self.get_redirect_uri(state)%0A %7D%0A%0A def get_user_details(self, response):%0A return %7B'username': response.get('username'),%0A 'email': response.get('mail'),%0A 'fullname': response.get('fullname')%7D%0A%0A def user_data(self, access_token, *args, **kwargs):%0A response = self.get_json(self.USER_DATA_URL, headers=%7B%0A 'Authorization': 'Bearer %7B%7D'.format(access_token)%0A %7D)%0A return response%5B0%5D%0A%0A def get_user_id(self, details, response):%0A return details.get('email')%0A
fde3496e41c9c00231d0f4d309147ff7dbae0f16
Improve heredoc
cms/wizards/wizard_base.py
cms/wizards/wizard_base.py
# -*- coding: utf-8 -*- from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django.forms.models import ModelForm from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ( override as force_language, force_text, ugettext as _ ) class WizardBase(object): template_name = None def __init__(self, title, weight, form, model=None, template_name=None, description=None): """ :param title: This is used on the start form. :param weight: Used for determining the order of the wizards on the creation form. :param form: :param model: Required either here or in the form's Meta class. This is used to determine uniqueness of the wizards, so, only one wizard per model. :param template_name: The full-path to the template to use, if any. :param description: This is used on the start form. """ # NOTE: If class attributes or properties are changed, consider updating # cms.templatetags.cms_wizard_tags.WizardProperty too. self.title = title self.weight = weight self.form = form self.model = model if description is not None: self.description = description elif self.model: model_name = model._meta.verbose_name self.description = _(u"Create a new %s instance.") % model_name if template_name is not None: self.template_name = template_name @python_2_unicode_compatible class Wizard(WizardBase): template_name = 'cms/wizards/create.html' @property def id(self): return self.__class__.__name__ def __str__(self): return self.title def __repr__(self): return 'Wizard: "{0}"'.format(force_text(self.title)) def user_has_add_permission(self, user, **kwargs): """ Returns whether the given «user» has permission to add instances of this wizard's associated model. Can be overridden as required for more complex situations. :param user: The current user using the wizard. :return: True if the user should be able to use this wizard. """ model = self.get_model() app_label = model._meta.app_label model_name = model.__name__.lower() return user.has_perm("%s.%s_%s" % (app_label, "add", model_name)) def get_success_url(self, obj, **kwargs): """ This should return the URL of the created object, «obj». """ if 'language' in kwargs: with force_language(kwargs['language']): return obj.get_absolute_url() else: return obj.get_absolute_url() def get_model(self): if self.model: return self.model if issubclass(self.form, ModelForm): model = self.form._meta.model if model: return model raise ImproperlyConfigured(u"Please set entry 'model' attribute or use " u"ModelForm subclass as a form")
Python
0.000001
@@ -710,16 +710,33 @@ am form: + The form to use. %0A
372469139dc103f75003f96616ac53bce8986274
Add prediction module
src/righter/predict.py
src/righter/predict.py
Python
0.000001
@@ -0,0 +1,679 @@ +import json%0Aimport argparse%0A%0Aimport righter%0A%0Aif __name__ == '__main__':%0A parser = argparse.ArgumentParser()%0A parser.add_argument('-i', '--input-file', help='File with one json per line containing the key text', required=True)%0A parser.add_argument('-o', '--file-output', help='Save analysis to output file', required=True)%0A args = parser.parse_args()%0A%0A with open(args.input_file, 'r') as input_fp:%0A with open(args.file_output, 'w') as output_fp:%0A for line in input_fp:%0A writing = json.loads(line.strip())%0A writing%5B'changes'%5D = righter.check(writing%5B'text'%5D)%0A print(json.dumps(writing), file=output_fp)%0A
1490aa8b11f9a7766eb03883214ded87ce1de439
Generate a sample binomial distribution
stats/binomial_plot.py
stats/binomial_plot.py
Python
0.999999
@@ -0,0 +1,805 @@ +import numpy as np%0Aimport random%0Aimport matplotlib.pylab as plt%0A%0Afrom collections import Counter%0A%0A%0Adef run_trial():%0A coin_tosses = 10%0A p = 0.5%0A successes = 0%0A for t in range(coin_tosses):%0A if random.random() %3C p:%0A successes = successes + 1%0A return successes%0A%0A%0Adef main():%0A trials = 100000%0A counts = %5Brun_trial() for n in range(trials)%5D%0A counts = %5Brun_trial() for n in range(trials)%5D%0A print Counter(counts)%0A plt.figure()%0A _, _, _ = plt.hist(counts, range(12), normed=1, align='left', fill=True)%0A plt.xlim(%5B-0.5, 10.5%5D)%0A plt.show()%0A%0A # Equivalent way to generate binomial distribution using numpy%0A n, p = 10, .5 # number of trials, probability of each trial%0A counts = np.random.binomial(n, p, 100000)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
15daff9a7823ddd7dbc3fb6f141d539d6b636301
Add description field to Config
project/timeslot/migrations/0008_auto_20160622_0937.py
project/timeslot/migrations/0008_auto_20160622_0937.py
Python
0.000001
@@ -0,0 +1,433 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('timeslot', '0007_auto_20160616_0049'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='config',%0A name='description',%0A field=models.TextField(max_length=4000, null=True, blank=True),%0A ),%0A %5D%0A
757812e63c42f38ad065c31744427c5902a5d322
Move some Utils outside of the main script.
data-preprocessor/listFile.py
data-preprocessor/listFile.py
Python
0
@@ -0,0 +1,540 @@ +# -*- coding: utf-8 -*-%0D%0A%22%22%22%0D%0ACreated on Sun Sep 11 10:23:38 2016%0D%0A%0D%0A@author: SISQUAKE%0D%0A%22%22%22%0D%0Aimport os%0D%0Adef listFilePath(path):%0D%0A File = %5B%5D;%0D%0A Dir = %5B%5D;%0D%0A%0D%0A for (dirpath, dirnames, filenames) in os.walk(path):%0D%0A for name in filenames:%0D%0A tmp = os.path.join(dirpath, name);%0D%0A File.append(%7B'path':tmp,'name':name%7D);%0D%0A for name in dirnames:%0D%0A tmp = os.path.join(dirpath, name);%0D%0A Dir.append(%7B'path':tmp,'name':name%7D);%0D%0A break%0D%0A%0D%0A return %7B'file' : File , 'dir' : Dir%7D;
1bf55df37a12af7984f08eb429e61a2c3a7cd836
Add initial server states
blitz/io/server_states.py
blitz/io/server_states.py
Python
0.000001
@@ -0,0 +1,2828 @@ +__author__ = 'Will Hart'%0A%0Afrom blitz.constants import *%0Afrom blitz.io.client_states import BaseState%0A%0A%0Adef validate_command(tcp, msg, commands):%0A %22%22%22%0A Helper function which checks to see if a message is in the list of valid commands%0A and sends an appropriate response over the TCP network%0A %22%22%22%0A if msg.split(' ')%5B0%5D not in commands:%0A tcp.send(%22ERROR 2%22)%0A else:%0A tcp.send(%22ERROR 1%22)%0A%0A%0Aclass ServerIdleState(BaseState):%0A%0A def enter_state(self, tcp, state):%0A print %22Calling ServerIdleState.enter_state: %22 + state.__name__%0A tcp.send(%22READY%22)%0A return self%0A%0A def process_message(self, tcp, msg):%0A %22%22%22%0A Handle the various requests from the client including to start and stop logging%0A %22%22%22%0A%0A print %22Calling ServerIdleState.process_message: %22 + msg%0A # check if it is a command which causes a change of state%0A if msg == %22START%22:%0A tcp.send(%22ACK%22)%0A return self.go_to_state(tcp, ServerLoggingState)%0A elif msg%5B0:8%5D == %22DOWNLOAD%22:%0A return self.go_to_state(tcp, ServerDownloadingState)%0A%0A if msg == %22STOP%22 or msg == %22STATUS%22:%0A # huh? We are not logging!?%0A tcp.send(%22NOSESSION%22)%0A else:%0A validate_command(tcp, msg, VALID_SERVER_COMMANDS)%0A%0A return self%0A%0A%0Aclass ServerLoggingState(BaseState):%0A%0A def enter_state(self, tcp, state):%0A print %22Calling ServerLoggingState.enter_state: %22 + state.__name__%0A%0A # TODO raise signal to start logging%0A print %22%5BSIGNAL%5D Start logging%22%0A%0A return self%0A%0A def process_message(self, tcp, msg):%0A print %22Calling ServerLoggingState.process_message: %22 + msg%0A%0A if msg == %22STOP%22:%0A%0A # TODO raise signal to stop logging%0A print %22%5BSIGNAL%5D Stop logging%22%0A tcp.send(%22ACK%22)%0A return self.go_to_state(tcp, ServerIdleState)%0A%0A if msg == %22STATUS%22:%0A # TODO raise signal to send status%0A print %22%5BSIGNAL%5D send status%22%0A%0A else:%0A validate_command(tcp, msg, VALID_SERVER_COMMANDS)%0A%0A return self%0A%0A%0Aclass ServerDownloadingState(BaseState):%0A def download_complete(self, tcp):%0A print %22Calling ServerLoggingState.download_complete%22%0A return self.go_to_state(tcp, ServerIdleState)%0A%0A def process_message(self, tcp, msg):%0A validate_command(tcp, msg, VALID_SERVER_COMMANDS)%0A return self%0A%0A%0Aclass ServerClosedState(BaseState):%0A def process_message(self, tcp, msg):%0A print %22Calling ServerClosedState.process_message%22 + msg%0A raise Exception(%22Attempted to receive message on closed server%22 + msg)%0A%0A def send_message(self, tcp, msg):%0A print %22Calling ServerClosedState.send_message%22 + msg%0A raise Exception(%22Attempted to send message on closed server%22 + msg)%0A
8e8cb549251b6914a34a729bb06c02462ed95af9
convert old wizard into osv memory wizard for configuration
bin/addons/base/module/wizard/base_module_configuration.py
bin/addons/base/module/wizard/base_module_configuration.py
Python
0.000002
@@ -0,0 +1,1340 @@ +# -*- coding: utf-8 -*-%0A##############################################################################%0A#%0A# OpenERP, Open Source Management Solution%0A# Copyright (C) 2004-2010 Tiny SPRL (%3Chttp://tiny.be%3E).%0A#%0A# This program is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as%0A# published by the Free Software Foundation, either version 3 of the%0A# License, or (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A#%0A##############################################################################%0A%0Aimport pooler%0Afrom osv import osv, fields%0A%0Aclass base_module_configuration(osv.osv_memory):%0A%0A _name = %22base.module.configuration%22%0A%0A def config(self, cr, uid, data, context=None):%0A return self.pool.get('res.config').next(cr, uid, %5B%5D, context=context)%0A%0Abase_module_configuration()%0A%0A# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:%0A
90c27c1444f80b6d746c8f92b6b79e38ae5ce87e
Update TFRT dependency to use revision http://github.com/tensorflow/runtime/commit/1a04c55547456cffd9b9d250dc8680eb9d89f750.
third_party/tf_runtime/workspace.bzl
third_party/tf_runtime/workspace.bzl
"""Provides the repository macro to import TFRT.""" load("//third_party:repo.bzl", "tf_http_archive") def repo(): """Imports TFRT.""" # Attention: tools parse and update these lines. TFRT_COMMIT = "5e36ba4f8e42a4022062a10a75684d5a2dfb1b53" TFRT_SHA256 = "3bf90326b6dd4f938825dd7ab3424abbee7cc86b370f24e285ff60440c3db360" tf_http_archive( name = "tf_runtime", sha256 = TFRT_SHA256, strip_prefix = "runtime-{commit}".format(commit = TFRT_COMMIT), urls = [ "http://mirror.tensorflow.org/github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT), "https://github.com/tensorflow/runtime/archive/{commit}.tar.gz".format(commit = TFRT_COMMIT), ], # A patch file can be provided for atomic commits to both TF and TFRT. # The job that bumps the TFRT_COMMIT also resets patch_file to 'None'. patch_file = None, )
Python
0.000002
@@ -210,133 +210,133 @@ = %22 -5e36ba4f8e42a4022062a10a75684d5a2dfb1b53%22%0A TFRT_SHA256 = %223bf90326b6dd4f938825dd7ab3424abbee7cc86b370f24e285ff60440c3db360 +1a04c55547456cffd9b9d250dc8680eb9d89f750%22%0A TFRT_SHA256 = %22296130004f8b3ce22b46b9f263c9379dd462eff53c2332f2ddd2d5ab26ab87ec %22%0A%0A
f099d055279abfea2bd58c8e0b28c2fa162ac8cd
modify zqplant crawler script
crawler/DzwBaikeCrawler.py
crawler/DzwBaikeCrawler.py
Python
0
@@ -0,0 +1,735 @@ +import hashlib%0A%0A%0A'''%0Acurl%0A-H 'Host: api.dzwbaike.xyz'%0A-H 'Content-Type: text/html;charset=UTF-8'%0A-H 'Accept: */*' -H 'Accept-Language: zh-cn'%0A-H 'token: 05e33d91-dd85-40d5-aa67-a90130270a95'%0A-H 'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 MicroMessenger/6.5.15 NetType/WIFI Language/zh_CN'%0A-H 'sign: b59fc7995e1dae61de5b768f58ea3367'%0A-H 'timestamp: 1505011126698'%0A-H 'Referer: https://servicewechat.com/wx56f5e9f2dde583b2/4/page-frame.html'%0A--compressed%0A'https://api.dzwbaike.xyz/api/tdouroubaikenew/list?page=6&limit=20'%0A'''%0Am2 = hashlib.md5()%0Asign = 'https://api.dzwbaike.xyz/api/tdouroubaikenew/list?page=6&limit=20'%0Am2.update(sign)%0Aprint m2.hexdigest()%0A
32a569f0f6f33ef5cf11031bb359989379582489
add script to create cloudtrail table in Athena
create_cloudtrail_table.py
create_cloudtrail_table.py
Python
0
@@ -0,0 +1,2253 @@ +import boto3%0A%0A%0A# Create AWS session%0Atry:%0A session = boto3.session.Session(profile_name='training')%0Aexcept Exception as e:%0A session = boto3.session.Session()%0A%0A# Connect to Athena%0Aathena = session.client('athena', region_name='us-east-1')%0A%0A%0Adef lambda_handler(event, context):%0A # You must submit the AWS account number within the event parameter%0A # Run the create cloudtrail table query%0A creation = athena.start_query_execution(QueryString=create_table,%0A ResultConfiguration=config%0A )%0A return creation%0A%0A%0A# Query Configurations%0Aconfig = %7B%0A 'OutputLocation': 's3://security-fairy/tables/',%0A 'EncryptionConfiguration': %7B%0A 'EncryptionOption': 'SSE_S3'%0A %7D%0A%7D%0A%0Acreate_table = %22%22%22%0Acreate external table if not exists aws_logs.cloudtrail (%0A eventVersion string,%0A userIdentity%0A struct%3C%0A type: string,%0A principalId: string,%0A arn: string,%0A accountId: string,%0A userName: string,%0A invokedBy: string,%0A accesskeyid:string,%0A sessioncontext:%0A struct%3C%0A attributes:%0A struct%3C%0A mfaauthenticated:string,%0A creationdate:string%0A %3E,%0A sessionIssuer:%0A struct%3C%0A type:string,%0A principalId:string,%0A arn:string,%0A accountId:string,%0A userName:string%0A %3E%0A %3E%0A %3E,%0A eventTime string,%0A eventSource string,%0A eventName string,%0A awsRegion string,%0A sourceIPAddress string,%0A userAgent string,%0A errorCode string,%0A errorMessage string,%0A requestID string,%0A eventID string,%0A resources%0A array%3C%0A struct%3C%0A ARN:string,%0A accountId:string,%0A type:string%0A %3E%0A %3E,%0A eventType string,%0A apiVersion string,%0A readOnly boolean,%0A recipientAccountId string,%0A sharedEventID string,%0A vpcEndpointId string%0A)%0Arow format serde 'com.amazon.emr.hive.serde.CloudTrailSerde'%0Astored as inputformat 'com.amazon.emr.cloudtrail.CloudTrailInputFormat'%0Aoutputformat 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'%0Alocation 's3://1strategy-training-traillogs/AWSLogs/%7Baccount_number%7D/CloudTrail/'%0A;%0A%22%22%22.format(account_number=event.get(accountId))%0A
4d6cbf52620c7af6b5b0698839712e35e303ff8f
Use self.get_column_types()
csvkit/utilities/in2csv.py
csvkit/utilities/in2csv.py
#!/usr/bin/env python import agate import agatedbf # noqa import agateexcel # noqa from csvkit import convert from csvkit.convert.fixed import fixed2csv from csvkit.convert.geojs import geojson2csv from csvkit.cli import CSVKitUtility SUPPORTED_FORMATS = ['csv', 'dbf', 'fixed', 'geojson', 'json', 'ndjson', 'xls', 'xlsx'] class In2CSV(CSVKitUtility): description = 'Convert common, but less awesome, tabular data formats to CSV.' epilog = 'Some command-line flags only pertain to specific input formats.' override_flags = ['f'] def add_arguments(self): self.argparser.add_argument(metavar="FILE", nargs='?', dest='input_path', help='The CSV file to operate on. If omitted, will accept input on STDIN.') self.argparser.add_argument('-f', '--format', dest='filetype', help='The format of the input file. If not specified will be inferred from the file type. Supported formats: %s.' % ', '.join(sorted(SUPPORTED_FORMATS))) self.argparser.add_argument('-s', '--schema', dest='schema', help='Specifies a CSV-formatted schema file for converting fixed-width files. See documentation for details.') self.argparser.add_argument('-k', '--key', dest='key', help='Specifies a top-level key to use look within for a list of objects to be converted when processing JSON.') self.argparser.add_argument('--sheet', dest='sheet', help='The name of the Excel sheet to operate on.') self.argparser.add_argument('-y', '--snifflimit', dest='sniff_limit', type=int, help='Limit CSV dialect sniffing to the specified number of bytes. Specify "0" to disable sniffing entirely.') self.argparser.add_argument('--no-inference', dest='no_inference', action='store_true', help='Disable type inference when parsing CSV input.') def main(self): # Determine the file type. if self.args.filetype: filetype = self.args.filetype if filetype not in SUPPORTED_FORMATS: self.argparser.error('"%s" is not a supported format' % self.args.filetype) elif self.args.schema: filetype = 'fixed' elif self.args.key: filetype = 'json' else: if not self.args.input_path or self.args.input_path == '-': self.argparser.error('You must specify a format when providing data via STDIN (pipe).') filetype = convert.guess_format(self.args.input_path) if not filetype: self.argparser.error('Unable to automatically determine the format of the input file. Try specifying a format with --format.') # Buffer standard input if the input file is in CSV format or if performing type inference. self.buffers_input = filetype == 'csv' or not self.args.no_inference # Set the input file. if filetype in ('xls', 'xlsx'): self.input_file = open(self.args.input_path, 'rb') else: self.input_file = self._open_input_file(self.args.input_path) # Set the reader's arguments. kwargs = {} if self.args.schema: schema = self._open_input_file(self.args.schema) elif filetype == 'fixed': raise ValueError('schema must not be null when format is "fixed"') if self.args.sheet: kwargs['sheet'] = self.args.sheet if filetype == 'csv': kwargs.update(self.reader_kwargs) kwargs['sniff_limit'] = self.args.sniff_limit kwargs['header'] = not self.args.no_header_row elif self.args.no_inference: # Streaming CSV musn't set column_types, but other formats should. kwargs['column_types'] = agate.TypeTester(limit=0) # Convert the file. if filetype == 'csv' and self.args.no_inference: reader = agate.csv.reader(self.input_file, **self.reader_kwargs) writer = agate.csv.writer(self.output_file, **self.writer_kwargs) writer.writerows(reader) elif filetype == 'fixed': self.output_file.write(fixed2csv(self.input_file, schema, output=self.output_file, **kwargs)) elif filetype == 'geojson': self.output_file.write(geojson2csv(self.input_file, **kwargs)) elif filetype in ('csv', 'dbf', 'json', 'ndjson', 'xls', 'xlsx'): if filetype == 'csv': table = agate.Table.from_csv(self.input_file, **kwargs) elif filetype == 'json': table = agate.Table.from_json(self.input_file, key=self.args.key, **kwargs) elif filetype == 'ndjson': table = agate.Table.from_json(self.input_file, key=self.args.key, newline=True, **kwargs) elif filetype == 'xls': table = agate.Table.from_xls(self.input_file, sheet=kwargs.get('sheet')) elif filetype == 'xlsx': table = agate.Table.from_xlsx(self.input_file, sheet=kwargs.get('sheet')) elif filetype == 'dbf': if not hasattr(self.input_file, 'name'): raise ValueError('DBF files can not be converted from stdin. You must pass a filename.') table = agate.Table.from_dbf(self.input_file.name, **kwargs) table.to_csv(self.output_file) self.input_file.close() if self.args.schema: schema.close() def launch_new_instance(): utility = In2CSV() utility.run() if __name__ == '__main__': launch_new_instance()
Python
0.000003
@@ -3776,24 +3776,25 @@ der_row%0A +%0A elif sel @@ -3789,115 +3789,29 @@ -el if -self.args.no_inference:%0A # Streaming CSV musn't set column_types, but other formats should. +filetype != 'dbf': %0A @@ -3848,32 +3848,30 @@ %5D = -agate.TypeTester(limit=0 +self.get_column_types( )%0A%0A
f693949a21864938991904ed1503ae5303426c90
Revert "Remove test stub"
test/TestLineNumber.py
test/TestLineNumber.py
Python
0
@@ -0,0 +1,1952 @@ +# Copyright (c) 2020 Albin Vass %3Calbin.vass@gmail.com%3E%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do so, subject to the following conditions:%0A#%0A# The above copyright notice and this permission notice shall be included in%0A# all copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0A# THE SOFTWARE.%0A%0Aimport ansiblelint.skip_utils%0A%0Afrom ansiblelint import AnsibleLintRule%0A%0A%0AMAGIC_NUMBER = 7007%0A%0A%0Aclass LinenumberRule(AnsibleLintRule):%0A id = 'TEST0003'%0A shortdesc = 'Linenumber is returned'%0A description = 'This is a rule that return a linenumber'%0A%0A tags = %7B'fake', 'dummy', 'test3'%7D%0A%0A def matchplay(self, file, play):%0A return %5B('Linenumber returned', self.shortdesc, MAGIC_NUMBER)%5D%0A%0A%0Adef test_rule_linenumber(monkeypatch):%0A%0A def mock_response(*args, **kwargs):%0A return %5B%7B'skipped_rules': %5B%5D%7D%5D%0A%0A monkeypatch.setattr(ansiblelint.skip_utils,%0A %22append_skipped_rules%22,%0A mock_response)%0A%0A text = %22- debug:%5Cn msg: a%22%0A rule = LinenumberRule()%0A matches = rule.matchyaml(dict(path=%22%22, type='tasklist'), text)%0A assert matches%5B0%5D.linenumber == MAGIC_NUMBER%0A
4404f1e81d9be6d7493388ca98300abf916136a6
Fix typo in the power of H.
pyflation/analysis/deltaprel.py
pyflation/analysis/deltaprel.py
''' pyflation.analysis.deltaprel - Module to calculate relative pressure perturbations. Author: Ian Huston For license and copyright information see LICENSE.txt which was distributed with this file. ''' from __future__ import division import numpy as np def soundspeeds(Vphi, phidot, H): """Sound speeds of the background fields Arguments --------- Vphi: array_like First derivative of the potential with respect to the fields phidot: array_like First derivative of the field values with respect to efold number N. H: array_like The Hubble parameter All the arguments should have the same number of dimensions. Vphi and phidot should be arrays of the same size, but H should have a dimension of size 1 corresponding to the "field" dimension of the other variables. """ try: calphasq = 1 + 2*Vphi/(3*H**2*phidot) except ValueError: raise ValueError("""Arrays need to have the correct shape. Vphi and phidot should have exactly the same shape, and H should have a dimension of size 1 corresponding to the field dimension of the others.""") return calphasq def rhodots(phidot, H): """Derivative in e-fold time of the energy densities of the individual fields. Arguments --------- phidot: array_like First derivative of the field values with respect to efold number N. H: array_like The Hubble parameter Both arrays should have the same number of dimensions, but H should have a dimension of size 1 corresponding to the field dimension of phidot. """ return -3*H**3*(phidot**2) def fullrhodot(phidot, H, axis=-1): """Combined derivative in e-fold time of the energy density of the field. Arguments --------- phidot: array_like First derivative of the field values with respect to efold number N. H: array_like The Hubble parameter axis: integer, optional Specifies which axis is the field dimension, default is the last one. """ return np.sum(rhodots(phidot, H), axis=axis) def deltarhosmatrix(Vphi, phidot, H, modes, modesdot, axis): """Matrix of the first order perturbed energy densities of the field components. Arguments --------- Vphi: array_like First derivative of the potential with respect to the fields phidot: array_like First derivative of the field values with respect to efold number N. H: array_like The Hubble parameter modes: array_like Mode matrix of first order perturbations. Component array should have two dimensions of length nfields. modesdot: array_like Mode matrix of N-derivative of first order perturbations. Component array should have two dimensions of length nfields. axis: integer Specifies which axis is first in mode matrix, e.g. if modes has shape (100,3,3,10) with nfields=3, then axis=1. The two mode matrix axes are assumed to be beside each other so (100,3,10,3) would not be valid. """ mshape = modes.shape if mshape[axis+1] != mshape[axis]: raise ValueError("The mode matrix dimensions are not together.") if mshape != modesdot.shape: raise ValueError("Mode matrix and its derivative should be the same shape.") mshapelist = list(mshape) del mshapelist[axis] #Make Vphi, phidot and H into at least 1-d arrays Vphi, phidot, H = np.atleast_1d(Vphi, phidot, H) #If Vphi doesn't have k axis then add it if len(Vphi.shape) < len(phidot.shape): Vphi = np.expand_dims(Vphi, axis=-1) if len(mshapelist) != len(Vphi.shape) != len(phidot.shape): raise ValueError("Vphi, phidot and modes arrays must have correct shape.") #If H doesn't have a field axis then add one if len(H.shape) < len(phidot.shape): H = np.expand_dims(H, axis) #Change shape of phidot, Vphi, H to add extra dimension of modes Vphi = np.expand_dims(Vphi, axis+1) phidot = np.expand_dims(phidot, axis+1) H = np.expand_dims(H, axis+1) #Do first sum over beta index internalsum = np.sum(phidot*modes, axis=axis) #Add another dimension to internalsum result internalsum = np.expand_dims(internalsum, axis) result = H*phidot*modesdot result -= 0.5*H**3*phidot**2*internalsum result += Vphi*modes return result def deltaprelmodes(Vphi, phidot, H, modes, modesdot, axis): """Perturbed relative pressure of the fields given as quantum mode functions. Arguments --------- Vphi: array_like First derivative of the potential with respect to the fields phidot: array_like First derivative of the field values with respect to efold number N. H: array_like The Hubble parameter modes: array_like Mode matrix of first order perturbations. Component array should have two dimensions of length nfields. modesdot: array_like Mode matrix of N-derivative of first order perturbations. Component array should have two dimensions of length nfields. axis: integer Specifies which axis is first in mode matrix, e.g. if modes has shape (100,3,3,10) with nfields=3, then axis=1. The two mode matrix axes are assumed to be beside each other so (100,3,10,3) would not be valid. """ mshape = modes.shape if mshape[axis+1] != mshape[axis]: raise ValueError("The mode matrix dimensions are not together.") if mshape != modesdot.shape: raise ValueError("Mode matrix and its derivative should be the same shape.") mshapelist = list(mshape) del mshapelist[axis] #Make Vphi, phidot and H into at least 1-d arrays Vphi, phidot, H = np.atleast_1d(Vphi, phidot, H) #If Vphi doesn't have k axis then add it if len(Vphi.shape) < len(phidot.shape): Vphi = np.expand_dims(Vphi, axis=-1) if len(mshapelist) != len(Vphi.shape) != len(phidot.shape): raise ValueError("Vphi, phidot and modes arrays must have correct shape.") #If H doesn't have a field axis then add one if len(H.shape) < len(phidot.shape): H = np.expand_dims(H, axis) cs = soundspeeds(Vphi, phidot, H) rdots = rhodots(phidot, H) rhodot = fullrhodot(phidot, H, axis) drhos = deltarhosmatrix(Vphi, phidot, H, modes, modesdot, axis) res_shape = list(drhos.shape) del res_shape[axis] result = np.zeros(res_shape) for ix in np.ndindex(tuple(res_shape[:axis])): for i in range(res_shape[axis]): for a in range(rdots.shape[axis]): for b in range(rdots.shape[axis]): if a != b: result[ix+(i,)] += (1/(2*rhodot[ix]) * (cs[ix+(a,)]**2 - cs[ix+(b,)]**2) * (rdots[ix+(b,)]*drhos[ix+(a,i)] - rdots[ix+(a,)]*drhos[ix+(b,i)])) return result def deltaprelspectrum(): """Power spectrum of the full perturbed relative pressure.""" pass
Python
0.001612
@@ -4574,16 +4574,19 @@ ult = H* +*2* phidot*m
3bb43f31263cce7ceebab943a1eed9e8c83cb90d
Set dbtable for models to use the "celery_" prefix not "djcelery".
djcelery/models.py
djcelery/models.py
import django from django.db import models from django.utils.translation import ugettext_lazy as _ from picklefield.fields import PickledObjectField from celery import conf from celery import states from djcelery.managers import TaskManager, TaskSetManager TASK_STATUSES_CHOICES = zip(states.ALL_STATES, states.ALL_STATES) class TaskMeta(models.Model): """Task result/status.""" task_id = models.CharField(_(u"task id"), max_length=255, unique=True) status = models.CharField(_(u"task status"), max_length=50, default=states.PENDING, choices=TASK_STATUSES_CHOICES) result = PickledObjectField(null=True, default=None) date_done = models.DateTimeField(_(u"done at"), auto_now=True) traceback = models.TextField(_(u"traceback"), blank=True, null=True) objects = TaskManager() class Meta: """Model meta-data.""" verbose_name = _(u"task meta") verbose_name_plural = _(u"task meta") def to_dict(self): return {"task_id": self.task_id, "status": self.status, "result": self.result, "date_done": self.date_done, "traceback": self.traceback} def __unicode__(self): return u"<Task: %s state->%s>" % (self.task_id, self.status) class TaskSetMeta(models.Model): """TaskSet result""" taskset_id = models.CharField(_(u"task id"), max_length=255, unique=True) result = PickledObjectField() date_done = models.DateTimeField(_(u"done at"), auto_now=True) objects = TaskSetManager() class Meta: """Model meta-data.""" verbose_name = _(u"taskset meta") verbose_name_plural = _(u"taskset meta") def to_dict(self): return {"taskset_id": self.taskset_id, "result": self.result, "date_done": self.date_done} def __unicode__(self): return u"<TaskSet: %s>" % (self.taskset_id) if (django.VERSION[0], django.VERSION[1]) >= (1, 1): # keep models away from syncdb/reset if database backend is not # being used. if conf.RESULT_BACKEND != 'database': TaskMeta._meta.managed = False TaskSetMeta._meta.managed = False
Python
0
@@ -942,24 +942,61 @@ %22task meta%22) +%0A db_table = %22celery_taskmeta%22 %0A%0A def to @@ -1723,16 +1723,56 @@ t meta%22) +%0A db_table = %22celery_tasksetmeta%22 %0A%0A de
00990b531f1f78b372b0b08a649a84e6168a3c0e
Use ugettext_lazy for import-time translations.
debug_toolbar/panels/timer.py
debug_toolbar/panels/timer.py
from __future__ import absolute_import, unicode_literals try: import resource # Not available on Win32 systems except ImportError: resource = None import time from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from debug_toolbar.panels import Panel class TimerPanel(Panel): """ Panel that displays the time a response took in milliseconds. """ def nav_subtitle(self): stats = self.get_stats() if hasattr(self, '_start_rusage'): utime = self._end_rusage.ru_utime - self._start_rusage.ru_utime stime = self._end_rusage.ru_stime - self._start_rusage.ru_stime return _("CPU: %(cum)0.2fms (%(total)0.2fms)") % { 'cum': (utime + stime) * 1000.0, 'total': stats['total_time'] } elif 'total_time' in stats: return _("Total: %0.2fms") % stats['total_time'] else: return '' has_content = resource is not None title = _("Time") template = 'debug_toolbar/panels/timer.html' @property def content(self): stats = self.get_stats() rows = ( (_("User CPU time"), _("%(utime)0.3f msec") % stats), (_("System CPU time"), _("%(stime)0.3f msec") % stats), (_("Total CPU time"), _("%(total)0.3f msec") % stats), (_("Elapsed time"), _("%(total_time)0.3f msec") % stats), (_("Context switches"), _("%(vcsw)d voluntary, %(ivcsw)d involuntary") % stats), ) return render_to_string(self.template, {'rows': rows}) def process_request(self, request): self._start_time = time.time() if self.has_content: self._start_rusage = resource.getrusage(resource.RUSAGE_SELF) def process_response(self, request, response): stats = {} if hasattr(self, '_start_time'): stats['total_time'] = (time.time() - self._start_time) * 1000 if hasattr(self, '_start_rusage'): self._end_rusage = resource.getrusage(resource.RUSAGE_SELF) stats['utime'] = 1000 * self._elapsed_ru('ru_utime') stats['stime'] = 1000 * self._elapsed_ru('ru_stime') stats['total'] = stats['utime'] + stats['stime'] stats['vcsw'] = self._elapsed_ru('ru_nvcsw') stats['ivcsw'] = self._elapsed_ru('ru_nivcsw') stats['minflt'] = self._elapsed_ru('ru_minflt') stats['majflt'] = self._elapsed_ru('ru_majflt') # these are documented as not meaningful under Linux. If you're running BSD # feel free to enable them, and add any others that I hadn't gotten to before # I noticed that I was getting nothing but zeroes and that the docs agreed. :-( # # stats['blkin'] = self._elapsed_ru('ru_inblock') # stats['blkout'] = self._elapsed_ru('ru_oublock') # stats['swap'] = self._elapsed_ru('ru_nswap') # stats['rss'] = self._end_rusage.ru_maxrss # stats['srss'] = self._end_rusage.ru_ixrss # stats['urss'] = self._end_rusage.ru_idrss # stats['usrss'] = self._end_rusage.ru_isrss self.record_stats(stats) def _elapsed_ru(self, name): return getattr(self._end_rusage, name) - getattr(self._start_rusage, name)
Python
0
@@ -262,16 +262,21 @@ ugettext +_lazy as _%0Afr
317c74fb6a31aad82f080b3bb8383c4047ae2f63
Create tests.py
demo/openmrs/openmrs/tests.py
demo/openmrs/openmrs/tests.py
Python
0.000001
@@ -0,0 +1,1869 @@ +import unittest%0Afrom BaseOpenmrsObject import *%0A%0Aclass TestOrderFunctions(unittest.TestCase):%0A%0A def setUp(self):%0A self.order = Order()%0A self.order.setOrderId(9112)%0A self.order.setOrderNumber('911')%0A %0A def test_copy_methods(self):%0A copy1 = self.order.copy()%0A copy2 = self.order.copyForModification()%0A self.assertEqual(self.order.OrderAction.ORDER, 'ORDER')%0A self.assertEqual(self.order.Urgency.ROUTINE, 'ROUTINE')%0A self.assertIs(copy2, self.order)%0A self.assertIsNot(copy1, self.order)%0A self.assertIsNot(copy1, copy2)%0A self.assertEqual(self.order.hashCode(), self.order.getOrderId())%0A%0A def test_date_methods(self):%0A self.assertTrue(self.order.isCurrent())%0A checkDate = datetime(2013, 12, 25)%0A%0A autoExpireDate = datetime(2017, 12, 25)%0A self.order.setAutoExpireDate(autoExpireDate)%0A self.assertTrue(self.order.isCurrent(checkDate))%0A %0A discontinuedDate = datetime(2015, 12, 25)%0A self.order.setDiscontinuedDate(discontinuedDate)%0A self.assertTrue(self.order.isCurrent(checkDate))%0A self.assertFalse(self.order.isDiscontinued(checkDate))%0A %0A startDate = datetime(2014, 12, 25)%0A self.order.setStartDate(startDate)%0A self.assertFalse(self.order.isCurrent(checkDate))%0A self.order.setDiscontinued(True)%0A self.assertFalse(self.order.isDiscontinued(checkDate))%0A %0A checkDate2 = datetime(2016, 12, 25)%0A self.assertTrue(self.order.isDiscontinued(checkDate2))%0A%0A self.assertTrue(self.order.isFuture(checkDate))%0A self.assertFalse(self.order.isDrugOrder())%0A%0A obj = Order(orderId = 9112)%0A self.assertTrue(self.order.equals(obj))%0A%0A self.assertIs(self.order.serialVersionUID, 1)%0A %0Aif __name__ == %22__main__%22:%0A unittest.main()%0A
9f18d31b85067fac2fd4d41d59c3158b50bd8c87
math2
tests/domains/math2.py
tests/domains/math2.py
Python
0.999621
@@ -0,0 +1,374 @@ +#!/usr/bin/env python3%0A%0Afrom collections import defaultdict%0Afrom copy import copy%0Afrom strips import *%0A%0Aclass S(State):%0A def __init__(self, n):%0A self.n = n%0A%0A @Action%0A def incr(self):%0A if self.n %25 4 != 0: raise UnsatisfiedPreconditions()%0A self.n += 1%0A%0A @Action%0A def double(self):%0A self.n *= 2%0A%0As = S(0)%0Agoal = lambda s: s.n == 123%0A%0A
274d539e0cf08a3417315bd68bc5544dbb21d0ff
Add config test
tests/config.py
tests/config.py
Python
0.000001
@@ -0,0 +1,1364 @@ +import wakefs.config%0Aimport os%0Aimport unittest%0Aimport random%0Aimport string%0A%0Adef random_str(N):%0A ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(N))%0A%0Aclass TestConfigFileCreate(unittest.TestCase):%0A def test_file_create(self):%0A testfile = %22test.cfg%22%0A config = wakefs.config.Config(testfile)%0A config.close()%0A self.assertTrue(os.path.exists(testfile))%0A os.remove(testfile)%0A%0Aclass TestConfigAttributes(unittest.TestCase):%0A def setUp(self):%0A self.testfile = %22test.cfg%22%0A self.config = wakefs.config.Config(self.testfile)%0A %0A def test_get_attribute(self):%0A self.config.database_uri%0A%0A def test_get_wrong_attribute(self):%0A with self.assertRaises(AttributeError):%0A self.config.detabase_uri%0A%0A def test_set_attribute(self):%0A teststr = random_str(random.randint(5,20))%0A self.config.test = teststr%0A self.assertTrue(self.config.test == teststr)%0A%0A def test_del_attribute(self):%0A teststr = random_str(random.randint(5,20))%0A self.config.test = teststr%0A self.assertTrue(self.config.test == teststr)%0A del self.config.test%0A with self.assertRaises(AttributeError):%0A self.config.test%0A%0A def tearDown(self):%0A self.config.close()%0A os.remove(self.testfile)%0A