repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
rancherio/rancher
tests/integration/suite/test_system_project.py
Python
apache-2.0
3,918
0
import pytest from rancher import ApiError from kubernetes.client import CoreV1Api from .conftest import wait_for systemProjectLabel = "authz.management.cattle.io/system-project" defaultProjectLabel = "authz.management.cattle.io/default-project" initial_system_namespaces = set(["kube-node-lease", ...
it if loggingNamespace in system_namespaces_names: system_namespaces_names.remove(loggingNamespace) assert system_namespaces_names == initial_system_namespaces def test_system_project_cant_be_deleted(admin_mc, admin_cc): ""
"The system project is not allowed to be deleted, test to ensure that is true """ projects = admin_cc.management.client.list_project( clusterId=admin_cc.cluster.id) system_project = None for project in projects: if project['name'] == "System": system_project = project ...
wojtask/CormenPy
src/chapter11/exercise11_4_2.py
Python
gpl-3.0
565
0
import math Deleted = math.inf def hash_delete(T, k, h): m = T.length i = 0 while True:
j = h(k, i, m) if T[j] == k: T[j] = Deleted return i = i + 1 if T[j] is None or i == m: break def hash_insert_(T, k, h): m = T.length i = 0 while True: j = h(k, i, m) if T[j] is None or T[j] is Deleted: T[j] = ...
else: i = i + 1 if i == m: break raise RuntimeError('hash table overflow')
mtils/ems
ems/qt4/itemmodel/sqlitermodel.py
Python
mit
5,898
0.003561
from PyQt4.QtCore import Qt from filtermodels import SortFilterProxyModel from ems import qt4 from ems.qt4.util import variant_to_pyobject from sqliter.query import test, c, and_, or_, GenClause, PathNotFoundError class SqlIterFilterModel(SortFilterProxyModel): def __init__(self, parent=None): SortFilte...
ts(self._query.group_by_fieldnames()) self._whereColumns = self._getFirstSegments(self._query.where_fieldnames()) self._hasColumnFilter = self._query.has_fields() self._visibleColumnCache = None else: self._hasGroupBy = False self._hasWhere = False ...
elf._visibleColumnCache = None #self.layoutAboutToBeChanged.emit() self.modelAboutToBeReset.emit() self.invalidateFilter() #self.layoutChanged.emit() self.modelReset.emit() def _getFirstSegments(self, fields): firstSegments = set() for field in fields: ...
rockho-team/shoop-cielo
shuup_cielo/admin/views/__init__.py
Python
agpl-3.0
3,897
0.003865
# -*- coding: utf-8 -*- # This file is part of Shuup Cielo. # # Copyright (c) 2016, Rockho Team. All rights reserved. # Author: Christian Hess # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from de...
st.POST.get('amount', cielo_transaction.total_value)) try: cielo_transaction.captu
re(amount) except CieloRequestError as err: return HttpResponseBadRequest("{0}".format(err)) return render_to_response(TRANSACTION_DETAIL_TEMPLAE, {'transaction': cielo_transaction, 'CieloTransactionStatus': Ciel...
munchycool/forthelulz
plugin.video.v1d30play/playvideo.py
Python
agpl-3.0
2,398
0.012093
import urlparse import sys,urllib import xbmc, xbmcgui, xbmcaddon, xbmcplugin import urlresolver base_url = sys.argv[0] addon_handle = int(sys.argv[1]) args = urlparse.parse_qs(sys.argv[2][1:]) _addon = xbmcaddon.Addon() _icon = _addon.getAddonInfo('icon') def build_url(query): return base_url + '?' + urlli...
= xbmcgui.ListItem(path=path) vid_url = play_item.getfilename() stream_url = resolve_url(vid_url) if stream_url: play_item.setPath(stream_url) # Pass the item to the Kodi player. xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item) # addon kicks in mode = args.get('mode', Non...
= xbmcgui.ListItem('Play Video 1', iconImage='DefaultVideo.png') li.setProperty('IsPlayable' , 'true') xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li) video_play_url = "https://www.youtube.com/watch?v=J9d9UrK0Jsw" url = build_url({'mode' :'play', 'playlink' : video_play_url}) ...
ellisonbg/pyzmq
zmq/utils/garbage.py
Python
lgpl-3.0
5,396
0.005374
"""Garbage collection thread for representing zmq refcount of Python objects used in zero-copy sends. """ #----------------------------------------------------------------------------- # Copyright (c) 2013 Brian E. Granger & Min Ragan-Kelley # # This file is part of pyzmq # # Distributed under the terms of the New ...
return self._context @context.setter def context(self, ctx): if self.is_alive(): if self.refs: warnings.warn("Replacing gc context while gc is running", RuntimeWarn
ing) self.stop() self._context = ctx def _atexit(self): """atexit callback sets _stay_down flag so that gc doesn't try to start up again in other atexit handlers """ self._stay_down = True self.stop() def stop(self): """stop ...
Micronaet/micronaet-connector
prestashop-connector/agent/agent_mysql.py
Python
agpl-3.0
33,351
0.006327
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License a...
_image): ''' Update image reference in rsync folder to prestashop path ''' #root_path = '/var/www/html/2015.redesiderio.it/site/public/https' root_path = '/home/redesiderio/public_html' # TODO
path_in = os.path.join(root_path, 'img/odoo') path_out = os.path.join(root_path, 'img/p',) # Create origin image: image_in = os.path.join( path_in, '%s.%s' % ( reference.replace(' ', '_'), self.ext_in, ...
ic-labs/django-icekit
icekit/plugins/location/models.py
Python
mit
1,493
0
from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from fluent_contents.models import ContentItem from icekit.models import ICEkitFluentContentsMixin from icekit.managers import...
ager from icekit.plugins.location import abstract_models # We must combine managers here otherwise the `PublishingManager` applied via # `ICEkitFluentContentsMixin` will clobber the existing `GoogleMapManager` class PublishingManagerAndGoogl
eMapManager( PublishingManager, GoogleMapManager, ): pass class Location( ICEkitFluentContentsMixin, abstract_models.AbstractLocationWithGoogleMap, ): """ Location model with fluent contents. """ objects = PublishingManagerAndGoogleMapManager() class Meta: unique_toget...
mercycorps/TolaActivity
indicators/tests/form_tests/result_form_unittests.py
Python
apache-2.0
9,175
0.000981
"""Unit tests for result_form_functional_tests.py Systems: - indicators.views.ResultCreate - bad indicator id 404 - get with good ids gives form - initial form data is correct - correct disaggregation values - form valid returns appropriate response - form invalid ret...
rs)) new_result = form.save() self.assertIsNotNone(new_result.id) db_result = Result.objects.get(pk=new_result.id) self.assertEqual(db_result.record_name, 'new record') def test_good_data_updating_evidence_validates(self): minimal_data = { 'date_collected': '2016...
f.indicator.id, 'program': self.program.id, 'record_name': 'existing record', 'evidence_url': 'http://google.com', 'rationale': 'this is a rationale' } form = ResultForm(minimal_data, **self.form_kwargs) self.assertTrue(form.is_valid(), "errors {0}...
madeso/prettygood
dotnet/SeriesNamer/UpdateTool.Designer.py
Python
mit
4,446
0.023852
namespace SeriesNamer { partial class UpdateTool { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <p...
ms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 237); this.Controls.Add(this.dProgress); this.Controls.Add(this.dAbort); this.Controls.Add(this.dOutput); this.Name = "UpdateTool"; this.Text = "UpdateTool"; this.Res...
ate System.Windows.Forms.Button dAbort; private System.Windows.Forms.ProgressBar dProgress; private System.ComponentModel.BackgroundWorker dWork; } }
swcarpentry/amy
amy/workshops/templatetags/tags.py
Python
mit
1,090
0
from django import template # from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def
bootstrap_tag_class(name): name_low = name.lower() class_ = 'badge-secondary' if name_low.startswith('swc'): class_ = 'badge-primary' elif name_low.startswith('dc'): class_ = 'badge-success' elif name_low.startswith('online'): class_ = 'badge-info' elif name_low.startswi...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_08_01/aio/operations/_application_gateways_operations.py
Python
mit
70,561
0.005144
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
rt AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[st...
You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_08_01.models :param client: Client fo...
darkless456/Python
download.py
Python
mit
208
0.004854
# down
load.py import urllib.request print("Downloading") url = 'https://www.python.org/ftp/python/3.4.1/python-3.4.1.msi' print('File Downloading') urllib.request.urlretrieve(url, 'python-3.4.1
.msi')
undertherain/vsmlib
vsmlib/benchmarks/__init__.py
Python
apache-2.0
126
0
"""Col
lection of benchmarks and downstream tasks on embeddings .. autosummary:: :toctree: _auto
summary analogy """
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/test/test_parser.py
Python
gpl-3.0
27,212
0.000441
import parser import unittest import sys import operator import struct from test import support from test.support.script_helper import assert_python_failure # # First, we test that we can generate trees from valid source fragments, # and that these valid trees are indeed allowed by the tree-loading side # of the pa...
e, s) def
test_yield_statement(self): self.check_suite("def f(): yield 1") self.check_suite("def f(): yield") self.check_suite("def f(): x += yield") self.check_suite("def f(): x = yield 1") self.check_suite("def f(): x = y = yield 1") self.check_suite("def f(): x = yield") ...
DomBennett/pG-lt
pglt/stages/phylogeny_stage.py
Python
gpl-2.0
3,537
0.001414
#! /usr/bin/env python # D.J. Bennett # 24/03/2014 """ pglt Stage 4: Phylogeny generation """ # PACKAGES import os import re import pickle import logging from Bio import Phylo import pglt.tools.phylogeny_tools as ptools from pglt.tools.system_tools import MissingDepError # RUN def run(wd=os.getcwd(), logger=logging....
if not ptools.raxml: raise MissingDepError('raxml') # INPUT with open(os.path.join(temp_dir, "paradict.p"), "rb") as file: paradict = pickle.load(file) with open(os.path.join(temp_dir, "genedict.p"), "rb") as file: genedict = pickle.loa
d(file) with open(os.path.join(temp_dir, "allrankids.p"), "rb") as file: allrankids = pickle.load(file) # PARAMETERS nphylos = int(paradict["nphylos"]) maxtrys = int(paradict["maxtrys"]) rttstat = float(paradict["rttstat"]) constraint = int(paradict["constraint"]) ptools.logger = lo...
bigmlcom/bigmler
bigmler/tests/test_06_missing_splits.py
Python
apache-2.0
5,076
0.003152
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2015-2021 BigML # # 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 requi...
| data | test | output |predictions_file | | ../data/iris_missing.csv | ../data/test_
iris_missing.csv | ./scenario_mspl_2/predictions.csv | ./check_files/predictions_iris_missing.csv """ print(self.test_scenario2.__doc__) examples = [ ['data/iris_missing.csv', 'data/test_iris_missing.csv', 'scenario_mspl_2/predictions.csv', 'check_files/predictions_iris_missing.c...
tigeorgia/fixmystreet
apps/mainapp/migrations/0007_auto_20150202_1422.py
Python
gpl-2.0
487
0
# -*- coding: utf-8 -*- fr
om __future__ import unicode_literals from django.db import models, migrations from django.conf impor
t settings class Migration(migrations.Migration): dependencies = [ ('mainapp', '0006_auto_20141207_2112'), ] operations = [ migrations.AlterField( model_name='ward', name='councillor', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), p...
NicovincX2/Python-3.5
Analyse (mathématiques)/Analyse numérique/Équations différentielles numériques/Collocation method/orthopoly.py
Python
gpl-3.0
11,766
0.005439
# -*- coding: utf-8 -*- """ orthopoly.py - A suite of functions for generating orthogonal polynomials and quadrature rules. Copyright (c) 2014 Greg von Winckel All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated do...
derivatives of the L2-normalized polynomials """ z = np.zeros((le
n(x), 1)) if N == 0: Px = z else: Px = 0.5 * np.hstack((z, jacobi(N - 1, a + 1, b + 1, x, NOPT) * ((a + b + 2 + np.arange(N))))) return Px
snickl/buildroot-iu
support/testing/tests/package/test_dropbear.py
Python
gpl-2.0
1,055
0
import os import infra.basetest class TestDropbear(infra.basetest.BRTest): config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \ """ BR2_TARGET_GENERIC_ROOT_PASSWD="testpwd" BR2_SYSTEM_DHCP="eth0" BR2_PACKAGE_DROPBEAR=y BR2_TARGET_ROOTFS_CPIO=y # BR2_TARGET_ROOTFS_TAR...
.0.0:22" _, exit_code = self.emulator.run(c
md) self.assertEqual(exit_code, 0) # Would be useful to try to login through SSH here, through # localhost:2222, though it is not easy to pass the ssh # password on the command line.
GUR9000/Deep_MRI_brain_extraction
NNet_Core/NN_Analyzer.py
Python
mit
4,154
0.016129
""" This software is an implementation of Deep MRI brain extraction: A 3D convolutional neural network for skull stripping You can download the paper at http://dx.doi.org/10.1016/j.neuroimage.2016.01.024 If you use this software for your projects please cite: Kleesiek and Urban et al, Deep MRI brain extraction: A 3...
runonce2() outputs = self._output_function2(*input) print() print( 'Analyzing internal gradients of network',self._cnn,' (I am',self,') ... ') i = 0 j = 0 for lay in self._cnn.layers: try: j = len(lay.params) except: ...
mean(out),np.median(out) std = np.std(out) print('{:^100}: {:^30}, min/max = [{:9.5f}, {:9.5f}], mean/median = ({:9.5f}, {:9.5f}), std = {:9.5f}'.format(lay,out.shape,mi,ma,mea,med,std)) else: print( '{:^100}: no parameters'.format(lay)) i+...
CollabQ/CollabQ
vendor/django/contrib/gis/geos/collections.py
Python
apache-2.0
4,663
0.004932
""" This module houses the Geometry Collection objects: GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon """ from ctypes import c_int, c_uint, byref from django.contrib.gis.geos.error import GEOSException, GEOSIndexError from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gi...
.ptr, index) def _get_single_external(self, index): "Returns the Geometry from this Collection at the given index (0-base
d)." # Checking the index and returning the corresponding GEOS geometry. return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid) def _set_list(self, length, items): "Create a new collection, and destroy the contents of the previous pointer." prev_ptr =...
doordash/realms-wiki
realms/lib/model.py
Python
gpl-2.0
10,966
0.000821
import json from sqlalchemy import not_, and_ from datetime import datetime from realms import db class Model(db.Model): """Base SQLAlchemy Model for automatic serialization and deserialization of columns and nested relationships. Source: https://gist.github.com/alanhamlett/6604662 Usage:: ...
f val != kwargs[rel]: setattr(self, rel, kwargs[rel]) changes[rel] = {'old': val, 'new': kwargs[rel]} return changes def set_columns(self, **kwargs): self._changes = self._set_columns(**kwargs) if 'modified' in self.__table__.columns:...
'modified_at' in self.__table__.columns: self.modified_at = datetime.utcnow() if 'updated_at' in self.__table__.columns: self.updated_at = datetime.utcnow() return self._changes def __repr__(self): if 'id' in self.__table__.columns.keys(): return '%s(%s)'...
pjaehrling/finetuneAlexVGG
preprocessing/inception/resize.py
Python
apache-2.0
375
0.005333
import tensorflow as tf from preprocessing import resize def preprocess_image(image, output_height, output_width, is_training=Fal
se): image = tf.image.convert_image_dtype(image, dtype=tf.float32) image = resize.preprocess_image(image, output_height, output_width, is_train
ing) image = tf.subtract(image, 0.5) image = tf.multiply(image, 2.0) return image
zheminzhou/GrapeTree
tests/test_bsa.py
Python
gpl-3.0
1,304
0.029141
from grapetree import app import pytest import os #def test_bsa_asymetric(): #print os.getcwd() #app_test = app.test_client() #with open(os.path.join('examples','simulated_data.profile')) as f: #test_profile = f.read() #with open(os.path.join('examples','simulated_data.global.nwk')) as f: ...
app_test = app.test_client() assert app.config.get('PARAMS') is not None if __name__ == "__main__": t
est_bsa_asymetric() test_bad_profile()
t-wissmann/qutebrowser
qutebrowser/extensions/loader.py
Python
gpl-3.0
5,652
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2018-2020 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free S...
for info in walk_components(): _load_compon
ent(info, skip_hooks=skip_hooks) def walk_components() -> typing.Iterator[ExtensionInfo]: """Yield ExtensionInfo objects for all modules.""" if hasattr(sys, 'frozen'): yield from _walk_pyinstaller() else: yield from _walk_normal() def _on_walk_error(name: str) -> None: raise ImportEr...
zenefits/sentry
src/sentry/testutils/cases.py
Python
bsd-3-clause
14,473
0.000691
""" sentry.testutils.cases ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ( 'TestCase', 'TransactionTestCase', 'APITestCase', 'AuthProviderTestCase', 'RuleTest...
mport CliRunner from contextlib import contextmanager from django.conf import settings from django.contrib.auth import login from django.core.cache import cache from django.core.urlresolvers import reverse from django.http import HttpRequest from django.test import TestCase, TransactionTestCase from django.utils.import...
port iter_entry_points from rest_framework.test import APITestCase as BaseAPITestCase from six.moves.urllib.parse import urlencode from sentry import auth from sentry.auth.providers.dummy import DummyProvider from sentry.constants import MODULE_ROOT from sentry.models import GroupMeta, ProjectOption from sentry.plugin...
criteo-forks/carbon
lib/carbon/tests/test_aggregator_methods.py
Python
apache-2.0
1,107
0.000903
import unittest from carbon.aggregator.rules import AGGREGATION_METHODS PERCENTILE_METHODS = ['p999', 'p99', 'p95', 'p90', 'p80', 'p75', 'p50'] VALUES = [4, 8, 15, 16, 23, 42] def almost_equal(a, b): return abs(a - b) < 0.0000000001 class AggregationMethodTest(unittest.TestCase): def test_percentile_simpl...
for method in PERCENTILE_METHODS: self.assertTrue(almost_equal(AGGREGATION_METHODS[method]([1]), 1)) def test_percentile_order(self): for method in PERCENTILE_METHODS: a = AGGREGATION_METHODS[method]([1, 2, 3, 4, 5]) b = AGGREGATION_METHODS[method]([3, 2, 1, 4, 5]) ...
41.905, ), ('p99', 41.05, ), ('p95', 37.25, ), ('p90', 32.5, ), ('p80', 23, ), ('p75', 21.25, ), ('p50', 15.5, ), ] for (method, result) in examples: self.assertTrue(almost_equal(AGGREGATION_METHODS[method](VALUES), res...
ntymtsiv/tempest
tempest/api/compute/v3/servers/test_instance_actions.py
Python
apache-2.0
2,647
0
# Copyright 2013 NEC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://
www.apache.org/licenses/LICENSE-2.0 # # Unless required
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tem...
ccauet/scikit-optimize
skopt/tests/test_callbacks.py
Python
bsd-3-clause
832
0
import pytest from collections import namedtuple from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_less from skopt import dummy_minimize from skopt.benchmarks import bench1 from skopt.callbacks import TimerCallback from skopt.callbacks import Delta
YStopper @pytest.mark.fast_test def test_timer_callback(): callback = TimerCallback() dummy_minimize(bench1, [(-1.0, 1.0)], callback=callback, n_calls=10) assert_equal(len(callback.iter_time), 10) assert_less(0.0, sum(callback.iter_time)) @pytest.mark.fast_test def test_deltay_stopper(): deltay ...
, 0.19])) assert not deltay(Result([0, 1, 2, 3, 4, 0.1])) assert deltay(Result([0, 1])) is None
hy-2013/scrapy
scrapy/contrib/linkextractors/sgml.py
Python
bsd-3-clause
5,233
0.00344
""" SGMLParser-based Link extractors """ from six.moves.ur
llib.parse import urljoin import warnings from sgmllib import SGMLParser from w3lib.url import safe_url_string from scrapy.selector import Selector from scrapy.link import Link from scrapy.linkextractor import FilteringLinkExtractor from scrapy.utils.misc import arg_to_iter from scrapy.utils.python import unique as un...
ls.response import get_base_url from scrapy.exceptions import ScrapyDeprecationWarning class BaseSgmlLinkExtractor(SGMLParser): def __init__(self, tag="a", attr="href", unique=False, process_value=None): warnings.warn( "BaseSgmlLinkExtractor is deprecated and will be removed in future release...
mammadori/pyglet
pyglet/window/cocoa/pyglet_view.py
Python
bsd-3-clause
13,557
0.004352
from pyglet.window import key, mouse from pyglet.libs.darwin.quartzkey import keymap, charmap from pyglet.libs.darwin.cocoapy import * NSTrackingArea = ObjCClass('NSTrackingArea') # Event data helper functions. def getMouseDelta(nsevent): dx = nsevent.deltaX() dy = nsevent.deltaY() return int(dx), int(d...
sevent): symbol = getSymbol(nsevent) modifiers = getModifiers(nsevent) self._window.dispatch_event('on_key_release', symbol, modifiers) @PygletView.method('v@') def pygletFlagsChanged_(self, nsevent):
# Handles on_key_press and on_key_release events for modifier keys. # Note that capslock is handled differently than other keys; it acts # as a toggle, so on_key_release is only sent when it's turned off. # TODO: Move these constants somewhere else. # Undocumented left/right modifier m...
vinaypost/multiuploader
multiuploader/models.py
Python
mit
541
0.001848
from __future__ import unicode_literals from django.conf import settings from django.db impo
rt models from django.utils.translation import ugettext_lazy as _ class MultiuploaderFile(models.Model): file = models.FileField(upload_to=settings.MULTIUPLOADER_FILES_FOLDER, max_len
gth=255) filename = models.CharField(max_length=255, blank=False, null=False) upload_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = _('multiuploader file') verbose_name_plural = _('multiuploader files')
keenlabs/KeenClient-Python
keen/__init__.py
Python
mit
31,368
0.005324
import os from keen.client import KeenClient from keen.exceptions import InvalidEnvironmentError __author__ = 'dkador' _client = None project_id = None write_key = None read_key = None master_key = None base_url = None def _initialize_client_from_environment(): ''' Initialize a KeenClient instance using environm...
this will either result in the event being uploaded to Keen immediately or will result in saving the eve
nt to some local cache. :param events: dictionary of events """ _initialize_client_from_environment() return _client.add_events(events) def generate_image_beacon(event_collection, body, timestamp=None): """ Generates an image beacon URL. :param event_collection: the name of the collection to...
tellesnobrega/sahara
sahara/plugins/fake/edp_engine.py
Python
apache-2.0
1,219
0
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
engine from sahara.utils import edp
class FakeJobEngine(base_engine.JobEngine): def cancel_job(self, job_execution): pass def get_job_status(self, job_execution): pass def run_job(self, job_execution): return 'engine_job_id', edp.JOB_STATUS_SUCCEEDED, None def run_scheduled_job(self, job_execution): pass...
mathLab/RBniCS
rbnics/reduction_methods/base/rb_reduction.py
Python
lgpl-3.0
31,214
0.003844
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import os from math import sqrt from logging import DEBUG, getLogger from rbnics.backends import GramSchmidt from rbnics.utils.decorators import PreserveClassName, RequiredBaseDecorators, sna...
matrix") self.update_basis_matrix(snapshot) iteration += 1 print("build reduced operators") self.reduced_problem.build_reduced_operators() print("reduced order solve")
self.reduced_problem.solve() print("build operators for error estimation") self.reduced_problem.build_error_estimation_operators() (absolute_error_estimator_max, relative_error_estimator_max) = self.greedy() print("maximum absolute error est...
tristan-hunt/UVaProblems
AcceptedUVa/uva_challenging/uva_10407.py
Python
gpl-3.0
1,675
0.030448
# /* UVa problem: 10407 # * Simple Division # * Topic: Number Theory # * # * Level: challenging # * # * Brief problem description: # * Given a list of numbers, a1, a2, a3.... an compute a number m such that # * ai mod m = x for some arbitrary x for all ai. # * In other words, find a congruence class mod...
diff[0], diff[1]) for i in range(2, n-1): #sys.stdout.write("gcd({}, {}) = {}\n".format(m, diff[i], gcd(
m, diff[i]))) m = gcd(m, diff[i]) sys.stdout.write("{}\n".format(m))
Onager/plaso
plaso/parsers/dsv_parser.py
Python
apache-2.0
10,932
0.006678
# -*- coding: utf-8 -*- """Delimiter separated values (DSV) parser interface.""" import abc import csv import os from dfvfs.helpers import text_file from plaso.lib import errors from plaso.lib import specification from plaso.parsers import interface class DSVParser(interface.FileObjectParser): """Delimiter separ...
:3] == b'\xef\xbb\xbf': return 'utf-8', 3 if file_data[0:2] == b'\xfe\xff': return 'utf-16-be', 2 if file_data[0:2
] == b'\xff\xfe': return 'utf-16-le', 2 return None, 0 def ParseFileObject(self, parser_mediator, file_object): """Parses a DSV text file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. ...
architecture-building-systems/CEAforArcGIS
bin/create_trace_graphviz.py
Python
mit
1,081
0.006475
""" Read in the output from the trace-inputlocator script and create a GraphViz file. Pass as input the path to the yaml output of the trace-inputlocator script via config file. The output is written to the trace-inputlocator location. WHY? because the trace-inputlocator
only has the GraphViz output of the last call to the script. This version re-creates the trace-data from the (merged) yaml file (the yaml output is merged if pre-existing in the output file). """ import yaml import cea.config from cea.tests.trace_inputlocator import create_graphviz_output def main(config): with...
t_file, 'r') as f: yaml_data = yaml.safe_load(f) trace_data = [] for script in yaml_data.keys(): for direction in ('input', 'output'): for locator, file in yaml_data[script][direction]: trace_data.append((direction, script, locator, file)) create_graphviz_output...
treasure-data/td-client-python
tdclient/models.py
Python
apache-2.0
457
0
#!/usr/bin/env python from tdclient import ( bulk_import_model, database_model,
job_model, result_model, schedule_model, table_model, user_model, ) BulkImport = bulk_import_model.BulkImport Database = database_model.Database Schema = job_model.Schema Job = job_model.Job Result = result_model.Result ScheduledJob = schedule_model.Sch
eduledJob Schedule = schedule_model.Schedule Table = table_model.Table User = user_model.User
gersakbogdan/fsnd-conference
models.py
Python
apache-2.0
5,554
0
#!/usr/bin/env python """models.py Udacity conference server-side Python App Engine data & ProtoRPC models $Id: models.py,v 1.1 2014/05/24 22:01:10 wesc Exp $ created/forked from conferences.py by wesc on 2014 may 24 """ import httplib import endpoints from protorpc import messages from google.appengine.ext impor...
db.Model): """Session -- Session object""" name = ndb.StringProperty(required=True) highlights = ndb.StringProperty() speakerKey = ndb.KeyProperty(kind='Speaker', required=True) duration = ndb.IntegerProperty() typeOfSession = ndb.StringProperty() date = ndb.DateProperty() startTime = nd...
SessionForm(messages.Message): """SessionForm -- Session outbound form message""" name = messages.StringField(1) highlights = messages.StringField(2) websafeSpeakerKey = messages.StringField(3) duration = messages.IntegerField(4) typeOfSession = messages.StringField(5) date = messages.String...
patrikja/SyntheticPopulations
python/activity_assignment.py
Python
bsd-3-clause
11,301
0.010353
import numpy as np import pandas as pd import statsmodels.formula.api as sm import copy from common import * # The following must be identical to the corresponding values in the genertion # script (if the files produced there are to be used). survey_attributes_csv = 'survey_attributes.csv' survey_activities_csv ...
d synthetic people file and construct list of synthetic persons. They have no activities. synthetic_people_df = pd.read_csv(synthetic_people_csv) synthetic_persons = [] for index, row in synthetic_people_df.iterrows(): attributes = map(lambda a: row[a], attribute_names) synthetic_persons.append(Person(row['person_i...
nd associate synthetic persons with them synthetic_households = [] for person in synthetic_persons: hh_temp = Household(person.household_id) if not hh_temp in synthetic_households: synthetic_households.append(hh_temp) for person in synthetic_persons: synthetic_households[synthetic_households.index(Household(p...
deddokatana/PyMiningCalc
PyMiningCalc/setup.py
Python
gpl-3.0
436
0.004587
from distutils.core import setup setup( name
='PyMiningCalc', version='1.0-Alpha', packages=['PyMiningCalc'], url='https://sites.google.com/site/working4coins/calculator, h
ttps://github.com/deddokatana/PyMiningCalc', license='GPL3', author='Twitter : @deddokatana - @WorkingForCoins', author_email='[email protected]', description='Python3 Output Calculator for Bitcoin/Litecoin Based Currencies' )
xuender/test
testAdmin/itest/migrations/0012_auto__chg_field_conclusion_title__chg_field_answer_title__chg_field_qu.py
Python
apache-2.0
5,840
0.007021
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Conc
lusion.title' db.alter_column(u'itest_conclusion', 'title', self.gf('django.db.models.fields.CharField')(max_length=250, null=True)) # Changing field 'Answer.title' db.alter_column(u'itest_answer', 'title', self.gf('django.db.models.fields.CharField')(max_length=250, null=True)) # Chan...
# Changing field 'Test.title' db.alter_column(u'itest_test', 'title', self.gf('django.db.models.fields.CharField')(max_length=250, null=True)) def backwards(self, orm): # Changing field 'Conclusion.title' db.alter_column(u'itest_conclusion', 'title', self.gf('django.db.models.fields.Cha...
ebagdasa/tempest
tempest/api/network/admin/test_quotas.py
Python
apache-2.0
3,707
0
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.network import base from tempest.common.utils import data_utils from tempest import test class QuotasTest(base.BaseAdminNetworkTest): _interface = '...
a values show quotas for a specified tenant update quotas for a specified tenant reset quotas to default values for a specified tenant v2.0 of the API is assumed. It is also assumed that the per-tenant quota extension API is configured in /etc/neutron/neutron.conf as follows: ...
pypa/virtualenv
src/virtualenv/seed/embed/via_app_data/pip_install/symlink.py
Python
mit
2,362
0.001693
from __future__ import absolute_import, unicode_literals import os import subprocess from stat import S_IREAD, S_IRGRP, S_IROTH from virtualenv.util.path import safe_delete, set_tree from virtualenv.util.six import ensure_text from virtualenv.util.subprocess import Popen from .base import PipInstall class SymlinkP...
set() if root_py_cache.exists(): new_files.update(root_py_cache.iterdir()) new_files.add(root_py_cache) safe_delete(root_py_cache) core_new_files = super(SymlinkPipInstall, self)._generate_new_files() # remove files that are within the image folder deeper than...
(rel.parts) > 1: continue except ValueError: pass new_files.add(file) return new_files def _fix_records(self, new_files): new_files.update(i for i in self._image_dir.iterdir()) extra_record_data_str = self._records_text(sorted(new_...
stefanseefeld/numba
numba/lowering.py
Python
bsd-2-clause
36,946
0.000271
from __future__ import print_function, division, absolute_import from collections import namedtuple import sys from functools import partial from llvmlite.ir import Value from llvmlite.llvmpy.core import Constant, Type, Builder from . import (_dynfunc, cgutils, config, funcdesc, generators, ir, types, ...
aulterrcls): self.lower_inst(inst) def create_cpython_wrapper(self, release_gil=False):
""" Create CPython wrapper(s) around this function (or generator). """ if self.genlower: self.context.create_cpython_wrapper(self.library, self.genlower.gendesc, self.env, self.call_he...
sfowl/fowllanguage
content/migrations/0010_auto_20151019_1410.py
Python
mit
1,608
0.003731
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.utils.timezone import utc import datetime class Migration(migrations.Migration): dependencies = [ ('content', '0009_auto_20150829_1417'), ] operations = [ migrations.Crea...
le=False, verbose_name='Date Received', default=datetime.datetime(2015, 10, 19, 4, 10, 29, 712166, tzinfo=utc))), ], options={ }, b
ases=(models.Model,), ), migrations.AlterField( model_name='event', name='pub_date', field=models.DateTimeField(editable=False, verbose_name='Date Published', default=datetime.datetime(2015, 10, 19, 4, 10, 29, 711232, tzinfo=utc)), preserve_default=True, ...
dimorinny/ufed-modules
ya-maps.py
Python
apache-2.0
7,341
0.002052
# -*- coding: utf8 -*- # Extracted data: # Favorite places # Bookmarks # Search queries history from physical import * import SQLiteParser from System.Convert import IsDBNull __author__ = "Dmit
ry Merkuryev" def chromiumTimestampParse(timestamp): return TimeStamp.FromUnixTime(timestamp / 1000000 - 11644473600) def commonTimestampParse(timestamp): return TimeStamp.FromUnixTime(timestamp / 1000) class YandexMapsLabel(object): def __init__(self, databaseRecord): self.labelName =
databaseRecord['label_name'].Value self.lat = databaseRecord['lat'].Value self.lon = databaseRecord['lon'].Value self.timestamp = databaseRecord['date'].Value def toModel(self): locationModel = Location() locationModel.Position.Value = self.parsePosition() locationM...
hryamzik/ansible
lib/ansible/modules/cloud/cloudstack/cs_router.py
Python
gpl-3.0
10,470
0.000573
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2016, René Moser <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
ption: Redundant state of the router. returned: success type: string sample: UNKNOWN role: description: Role of the router. returned: success type: string sample: VIRTUAL_ROUTER zone: description: Name of zone the router is in. returned: success type: string sample: ch-gva-2 service_offering: de...
r Software Router state: description: State of the router. returned: success type: string sample: Active domain: description: Domain the router is related to. returned: success type: string sample: ROOT account: description: Account the router is related to. returned: success type: string sample...
zaneswafford/songaday_searcher
songaday_searcher/celery.py
Python
bsd-3-clause
352
0
import o
s from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'songaday_searcher.settings') app = Celery('songaday_searcher') app.config_from_object('django.conf:settings') ap
p.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
puttarajubr/commcare-hq
corehq/apps/receiverwrapper/models.py
Python
bsd-3-clause
16,267
0.002336
import base64 from collections import defaultdict, namedtuple from datetime import datetime, timedelta import logging import urllib import urlparse from dimagi.ext.couchdbkit import * from couchdbkit.exceptions import ResourceNotFound from django.core.cache import cache import socket import hashlib from casexml.apps....
ction delegates to the # appropriate sub-repeater types. pass else: # Any repeater type can be posted to the API, and the installed apps # determine whether we actually know about it. # But if we do not know about it, then may as well return nothing no...
per/repeaters', startkey=key, endkey=key + [{}], include_docs=True, reduce=False, wrap_doc=False )
mudiarto/django-mailer
mailer/__init__.py
Python
mit
3,442
0.003777
VERSION = (0, 2, 1, "f", 1) # following PEP 386 DEV_N = None def get_version(): version = "%s.%s" % (VERSION[0], VERSION[1]) if VERSION[2]: version = "%s.%s" % (version, VERSION[2]) if VERSION[3] != "f": version = "%s%s%s" % (version, VERSION[3], VERSION[4]) if DEV_N: v...
for a in settings.ADMINS]) def mail_managers(subject, message, fail_silently=False, connection=None, priority="medium"): from django.conf import settings from django.utils.encoding import force_unicode return send_mail(settings.EMAIL_SUBJECT_PREFIX + force_unicode(subject), mess...
tings.MANAGERS])
tuxology/bcc
examples/tracing/bitehist.py
Python
apache-2.0
1,181
0.00508
#!/usr/bin/python # # bitehist.py Block I/O size histogram. # For Linux, uses BCC, eBPF. Embedded C. # # Written as a basic example of using histograms to show a distribution. # # A Ctrl-C will print the gathered histogram then exit. # # Copyright (c) 2015 Brendan Gregg. # Licensed under the Apache License, Version 2....
print("~~~~~~~~~~~~~~") b["dist"].print_log2_hist("kbytes") print("\nlinear histogram") print("~~~~~~
~~~~~~~~~~") b["dist_linear"].print_linear_hist("kbytes")
bzyx/precious
precious/models/Build.py
Python
bsd-3-clause
763
0.001311
# -*- coding: utf-8 -*- from precious import db from datetime import datetime class Build(db.Model): __tablename__ = 'builds' id = db.Column(db.Integer, primary_key=True, unique=True) project_id = db.Column(db.Integer
, db.ForeignKey('projects.id')) date = db.Column(db.DateTime) revision = db.Column(db.LargeBinary)
stdout = db.Column(db.UnicodeText) success = db.Column(db.Boolean) def __init__(self, project_id, revision, stdout=u"", success=True, date=datetime.now()): self.project_id = project_id self.date = date self.revision = revision self.stdout = stdout self.success = suc...
ict-felix/stack
modules/resource/orchestrator/src/monitoring/utils.py
Python
apache-2.0
4,165
0.00048
import core logger = core.log.getLogger("monitoring-utils") class MonitoringUtils(object): def __init__(self): pass @staticmethod def check_existing_tag_in_topology(root, node, node_type, node_urns, domain=None): tag_exists = False try: ...
["destination"]) return list(e2e_link_urns) @staticmethod def find_virtual_links(topology_root): links_ids = [] for link_id in topology_root.xpath("//topology//link[@id]"): links_ids.append(link_id.attrib["id"]) return links_ids @staticmethod def find_slice_...
t): slice_name = "" try: slice_name = topology_root.xpath("//topology")[0].attrib["name"] except Exception as e: logger.warning("Unable to retrieve slice name for topology. \ Details: %s" % e) return slice_name
CamoFPV/Relay-Website-with-Raspberry-Pi
py/14on.py
Python
mit
254
0.011811
#!/usr/bin/env python # IMPORT NECESSARY LIBRARIES import RPi.GPIO as GPIO import time
# INITIALIZE THE GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(26,GPIO.OUT)
# TURN ON RELAY 1 GPIO.output(26,0) # CLEAN UP GPIO # GPIO.cleanup()
maisilex/Lets-Begin-Python
list.py
Python
mit
52
0
a =
[int(i) for i in input().split()] print(sum
(a))
jroivas/odt-html5
odt.py
Python
mit
23,990
0.002126
import zipfile import os import xml.etree.ElementTree as etree import re import copy class ODTPage: def __init__(self, name, odt=None, pagename='page', indexname='index'): self.pagename = pagename self.indexname = indexname if odt is None: self.odt = ODT(name, pagename=pagename)...
self.getFooter() return head + res + foot def getHeader(self, title, extra=""): return """<html> <head> <title>%s</title> <link rel="stylesheet" type="text/css" title="styles" href=
"odt.css"/> <meta charset="UTF-8"> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="odt.js"></script> %s </head> """ % (title, extra) def getContent(self, odt, page): res = odt.read() tmp...
sql-machine-learning/sqlflow
python/runtime/tensorflow/__init__.py
Python
apache-2.0
679
0
# Copyright 2020 The SQLFlow Authors. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of
the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dis
tributed 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 runtime.tensorflow.get_tf_model_type import is_tf_estimator # noqa: F401...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_11_01/operations/_load_balancer_backend_address_pools_operations.py
Python
mit
8,928
0.004368
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
n, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request ...
ist_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(...
pantheon-systems/etl-framework
etl_framework/utilities/DatetimeConverter.py
Python
mit
889
0.001125
"""class to convert datetime values""" import datetime class DatetimeConverter(object): """stuff""" _EPOCH_0 = datetime.datetime(1970, 1, 1) def __init__(self): """stuff""" pass @staticmethod def get_tomorrow(): """stuff""" return datetime.datetime.today() + da...
time.datetime.today() - datetime.timedelta(days=1) @classmethod def get_timestamp(cls, datetime_obj): """helper method to return timestamp fo datetime object""" return (datetime_obj - cls._EPOCH_0).total_seconds() @classmethod def get_tomorrow_timestamp(cls):
"""stuff""" return cls.get_timestamp(cls.get_tomorrow()) @classmethod def get_yesterday_timestamp(cls): return cls.get_timestamp(cls.get_yesterday())
markshao/pagrant
pagrant/provisioners/health/http.py
Python
mit
1,669
0.002996
__author__ = ['Xiaobo'] import time import httplib from pagrant.exceptions import VirtualBootstrapError from pagrant.provisioners import BaseProvisioner CHECK_TIMEOUT = 60 * 5 class HttpCheckerPrivisioner(BaseProvisioner): def __init__(self, machine, logger, provision_info, provider_info): super(HttpChe...
fo) self.port = self.provision_info.get("port", None) self.url = self.provision_info.get("url", None) def do_provision(self): self.check_health() def check_health(self): time.sleep(5) start_time = time.time() self.logger.start_progress("start to check the %s for...
while True: self.logger.info("Wait for the application to be ready on the %s ..." % self.machine.machine_info['name']) con = httplib.HTTPConnection(self.machine.host, self.port) con.request("GET", self.url) res = con.getresponse() if res.status == 200 or res....
dseuss/mpnum
tests/special_test.py
Python
bsd-3-clause
6,072
0.001318
# encoding: utf-8 from __future__ import absolute_import, division, print_function import numpy as np import pytest as pt from numpy.testing import (assert_almost_equal, assert_array_almost_equal) import mpnum.factory as factory import mpnum.mparray as mp import mpnum.special as mpsp from mpnum._testing import assert...
##################### # special.inner_prod_mps # ############################ @pt.mark.parametrize('dtype', pt.MP_TEST_DTYPES) @pt.mark.parametrize('nr_sites, local_dim, rank', pt.MP_TEST_PARAMETERS) def test_inner_prod_
mps(nr_sites, local_dim, rank, dtype, rgen): mpa1 = factory.random_mpa(nr_sites, local_dim, 1, dtype=dtype, randstate=rgen, normalized=True) mpa2 = factory.random_mpa(nr_sites, local_dim, rank, dtype=dtype, randstate=rgen, normalized=True) res_slo...
WatchPeopleCode/WatchPeopleCode
migrations/versions/44c3becf9745_.py
Python
mit
884
0.00905
"""empty message Revision ID: 44c3becf9745 Revises: 34d183116728 Create Date: 2015-02-01 17:18:35.172244 """ # revision identifiers, used by Alembic. revision = '44c3becf9745' down_revision = '34d183116728' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
ompleted', sa.Boolean(), nullable=True)) op.add_column('stream', sa.Column('is_live', sa.Boolean(), nullable=True)) op.add_column('stream', sa.Column('schelduled_start_time', sa.DateTime(), nullable=True)) ### end Alembic co
mmands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('stream', 'schelduled_start_time') op.drop_column('stream', 'is_live') op.drop_column('stream', 'is_completed') ### end Alembic commands ###
nilgoyyou/dipy
dipy/reconst/tests/test_vec_val_vect.py
Python
bsd-3-clause
1,302
0
import numpy as np from numpy.random import randn from numpy.testing import assert_almost_equal, dec from dipy.reconst.vec_val_sum import vec_val_vect def make_vecs_vals(shape): return randn(*(shape)), randn(*(shape[:-2] + shape[-1:])) try: np.einsum except AttributeError: with_einsum = dec.skipif(True...
= shape0 + s
hape1 evecs, evals = make_vecs_vals(shape) res1 = np.einsum('...ij,...j,...kj->...ik', evecs, evals, evecs) assert_almost_equal(res1, vec_val_vect(evecs, evals)) def dumb_sum(vecs, vals): N, rows, cols = vecs.shape res2 = np.zeros((N, rows, rows)) for i in range(N): ...
Forage/Gramps
gramps/gen/filters/rules/media/_hassourcecount.py
Python
gpl-2.0
1,807
0.005534
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2007 Donald N. Allingham # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2008 Jerome Rapinat # Copyright (C) 2008 Benny Malengier # # This program is free software; you can redistribute it and/or modify # it under the terms of the ...
---------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.get_translation().get
text #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- from .._hassourcecountbase import HasSourceCountBase #------------------------------------------------------------------------- # "People havi...
css-lucas/GAT
gat/core/sna/updateSNA.py
Python
mit
35,903
0.003231
import tempfile import matplotlib.pyplot as plt import networkx as nx import numpy as np import xlrd from networkx.algorithms import bipartite as bi from networkx.algorithms import centrality from itertools import product from collections import defaultdict import pandas as pd import datetime from gat.core.sna import ...
listFlag = True if type(value) is list else False
attrList.append([value[0], key] if listFlag else [value, key]) # weighted attributes take the form [value, weight] else: attrList.append(value) attrID = prevCell['header'] ...
mitenjain/nanopore
nanopore/analyses/hmm.py
Python
mit
4,792
0.01586
import os from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, samIterator import xml.etree.cElementTree as ET from jobTree.src.bioio import * class Hmm(AbstractAnalysis): """Calculates stats on indels. """ ...
s[(base, x)], bases)) + "\n") outf.close() system("Rscript nanopore/analyses/substitution_plot.R %s %s %s" % (matchEmissionsFile, os.path.join(self.outputDir, "substitution_plot.pdf"), "Per-Base Substitutions after HMM")) #Plot indel info
#Get the sequences to contrast the neutral model. refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences #Need to do plot of insert and deletion gap e...
google/starthinker
starthinker/task/cm_to_dv/cm_placement_group.py
Python
apache-2.0
2,931
0.008188
########################################################################### # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/l...
iterate=True, internal=is_superuser ).placementGroups().list( **kwargs).execute() cm_placement_group_clear(config, task) # write placement_groups to database put_rows( config, task['auth_bigquery'], { 'bigquery': { 'dataset': task['dataset'],
'table': 'CM_PlacementGroups', 'schema': Discovery_To_BigQuery( 'dfareporting', 'v3.4' ).method_schema( 'placementGroups.list', iterate=True ), 'format':'JSON' }}, load_multiple() )
kmee/pySerasa
pyserasa/crednet.py
Python
agpl-3.0
7,131
0.002664
# -*- coding: utf-8 -*- from erros import BlocoInexistenteError from blocosDados import pendenciasInternas from blocosDados import pendenciasFinanceiras from blocosDados import protestosEstados from blocosDados import chequesSemFundos class Crednet(object): def __init__(self): self.blocos = [] sel...
denciasFinanceiras()) self.blocos.append(protestosEstados()) self.blocos.append(chequesSemFundos()) def __getattr__(self, name): bloco = ([c for c in self.blocos if c.nome == name] or [None])[0] if not bloco: print BlocoInexistenteError().exibirErro(name) else: ...
in registro.campos.campos: print campos._nome, print ": ", print campos._valor print " " if bloco.nome == 'pendenciasFinanceiras': print bloco.nome_bloco + "\n" for registro in bloco....
gdbdzgd/aptly
system/t04_mirror/update.py
Python
mit
5,713
0.002626
import string import re from lib import BaseTest class UpdateMirror1Test(BaseTest): """ update mirrors: regular update """ longTest = False fixtureCmds = [ "aptly -architectures=i386,amd64 mirror create --ignore-signatures varnish http://repo.varnish-cache.org/debian/ wheezy varnish-3.0", ...
or6Test(BaseTest): """ update mirrors: wrong checksum in package, but ignore """ fixtureCmds = [ "aptly mirror create --ignore-signatures failure ${url} hardy main", ] fixtureWebServer = "test_release2" runCmd = "aptly mirror update -ignore-checksums --ignore-signatures failure" ...
""" fixtureGpg = True fixtureCmds = [ "aptly mirror create --keyring=aptlytest.gpg flat http://download.opensuse.org/repositories/Apache:/MirrorBrain/Debian_7.0/ ./", ] runCmd = "aptly mirror update --keyring=aptlytest.gpg flat" outputMatchPrepare = lambda _, s: re.sub(r'Signature made ....
tuomas2/automate-rpc
setup.py
Python
gpl-3.0
1,901
0.002104
#!/usr/bin/env python from setuptools import setup, find_packages def get_version(filename): import re with open(filename) as fh: metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read())) return metadata['version'] setupopts = dict( name="automate-rpc", version=get_version('a...
s", url="http://github.com/tuomas2/automate-rpc", entry_points={'automate.extension': [ 'rpc = automate_rpc:extension_classes' ]}, classifiers=["Development Status :: 4 - Beta", "Environment :: Console", "Environment :: Web Environment", "I...
Developers", "Intended Audience :: Information Technology", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: GNU General Public License (GPL)", "Operating System :: Microsoft :: Windows", "Operating System :: POSI...
geberl/droppy-workspace
Tasks/Image.RenameByExif/test_task.py
Python
mit
1,551
0.001289
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import py import os import shutil import task files_dir = py.path.local(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'Test', 'files')) def test_input_empty(tmpdir): input_dir = tmpdir.join('0') os.makedirs('%s...
sinstance(t, object) def test_input_f
ile(tmpdir): input_dir = tmpdir.join('0') os.makedirs('%s' % input_dir) shutil.copyfile('%s' % files_dir.join('IMG_1248.JPG'), '%s' % input_dir.join('IMG_1248.JPG')) output_dir = tmpdir.join('1') os.makedirs('%s' % output_dir) t = task.Task(input_dir='%s' % input_dir, ...
LosFuzzys/CTFd
CTFd/auth.py
Python
apache-2.0
20,121
0.001342
import base64 import requests from flask import Blueprint from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.mo...
trip() website = request.form.get("website") affiliation = request.form.get("affiliation") country = request.form.get("country") name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = ( Users.query.add_c...
.first() ) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) # Process additional user fields fields = {} for field in UserFie...
CvvT/crawler_sqlmap
crawler/util/__init__.py
Python
apache-2.0
120
0
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ =
'CwT' from .global_state import State Global = S
tate()
deKupini/erp
addons/payment/models/payment_acquirer.py
Python
agpl-3.0
25,888
0.003515
# -*- coding: utf-'8' "-*-" import logging from openerp.osv import osv, fields from openerp.tools import float_round, float_repr from openerp.tools.translate import _ _logger = logging.getLogger(__name__) def _partner_format_address(address1=False, address2=False): return ' '.join((address1 or '', address2 or ...
ider', required=True), 'company_id': fields.many2one('res.company', 'Company', required=True),
'pre_msg': fields.html('Message', translate=True, help='Message displayed to explain and help the payment process.'), 'post_msg': fields.html('Thanks Message', help='Message displayed after having done the payment process.'), 'validation': fields.selection( [('manual', 'M...
sunlightlabs/sarahs_inbox
mail_dedupe/views.py
Python
bsd-3-clause
2,307
0.01257
from settings import * from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.core.paginator import Paginator from django.http import HttpResponse, HttpResponseRedirect from urllib import unquote from mail.models impor
t * from django.core.urlresolvers import reverse from django.core.cache import cache import re import jellyfish from mail.management.commands.mail_combine_people import Command as CombineCommand def index(request): if not DEBUG: return DEFAULT_DISTANCE = 0 person_into = request.G...
if person_into is not False: victims.remove(int(person_into)) args_array = [person_into] + victims # call_command('mail_combine_people', *args_array) combcomm = CombineCommand() print person_into, victims result = combcomm.merge(person_into, victims, noprint=True) ...
drJfunk/gbmgeometry
gbmgeometry/gbm.py
Python
mit
10,575
0.00104
from collections import OrderedDict import astropy.coordinates as coord import astropy.units as u import matplotlib.pyplot as plt #import mpl_toolkits.basemap as bm import numpy as np import spherical_geometry.polygon as sp from astropy.table import Table import astropy.time as time from .gbm_detector import BGO0, BG...
* u.degree num_points = 300 ra_grid_tmp = np.linspace(0, 360, num_points) dec_range = [-90, 90] cosdec_min = np.cos(np.deg2rad(90.0 + dec_range[0])) cosdec_max = np.cos(np.deg2rad(90.0 + dec_range[1])) v = np.linspace(cosdec_min, cosdec_max, nu
m_points) v = np.arccos(v) v = np.rad2deg(v) v -= 90. dec_grid_tmp = v ra_grid = np.zeros(num_points ** 2) dec_grid = np.zeros(num_points ** 2) itr = 0 for ra in ra_grid_tmp: for
google-research/pyreach
pyreach/gyms/oracle_element.py
Python
apache-2.0
1,448
0.004144
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
defaults to an empty string. success_type: The type of success. This argument is optional and defaults to an empty string. is_synchronous: If True, the next Gym observation will synchronize all observation elements that have this flag set otherwise the next observation is asynchronous. ...
sk_code: str intent: str = "" success_type: str = "" is_synchronous: bool = False
msabramo/PyHamcrest
src/hamcrest/library/text/stringcontains.py
Python
bsd-3-clause
953
0
from hamcrest.library.text.substringmatcher import SubstringMatcher from hamcrest.core.helpers.ha
smethod import hasmethod __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class StringContains(SubstringMatcher): def __init__(self, substring): super(StringContains, self).__init__(substring) def _matches(self, item): if not hasmeth...
item.find(self.substring) >= 0 def relationship(self): return 'containing' def contains_string(substring): """Matches if object is a string containing a given string. :param string: The string to search for. This matcher first checks whether the evaluated object is a string. If so, it c...
neubot/neubot-client
neubot/utils_nt.py
Python
gpl-3.0
2,253
0.002663
# neubot/utils_nt.py # # Copyright (c) 2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN) # and Simone Basso <[email protected]> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU...
Public License for more details. # # You should have received a copy of the GNU General Public License # along with Neubot. If not, see <http://www.gnu.org/licenses/>. # """ NT utils """ import os # For python3 portability MODE_755 = int('755', 8) MODE_644 = int('644', 8) class PWEntry(object): """ Fake passwo...
functions from utils_posix.py, and I # also commented out the code that couldn't run on Windows NT. # def mkdir_idempotent(curpath, uid=None, gid=None): ''' Idempotent mkdir with 0755 permissions''' if not os.path.exists(curpath): os.mkdir(curpath, MODE_755) elif not os.path.isdir(curpath): ...
nouiz/fredericbastien-ipaddr-py-speed-up
tags/2.1.0/ipaddr.py
Python
apache-2.0
58,769
0.00051
#!/usr/bin/python # # Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. # # 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 g
overning # permissions and limitations under the License. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = 'trunk' import struct class AddressValueError(ValueError): """A Value Error related...
digling/sinotibetan
datasets/Sharma2003/prepare-byangsi.py
Python
gpl-2.0
1,355
0.002974
from lingpy import * from pystdb import load_stedt, stdb_concepts concepts = stdb_concepts() rong = csv2list('Byangsi.mapped.tsv', strip_lines=False) wl = load_stedt('SRS-TBLUP.csv') rn2k = {wl[k, 'rn']: k for k in wl} out = {0: ['language', 'concept', 'conceptid', 'concepticon_id', 'tbl_id', 'gloss_in_source', ...
'.replace('◌', '')), (':', 'ː'), ] for s, t in st: entry = entry.replace(s, t) entry = entry.split(',')[0] entry = entry.split('~')[0].strip() entry = entry.replace(' ', '_') if wl[idx, 'language'] == 'Byangsi': tokens ...
", merge_vowels=False) out[idxx] = ['Byangsi', line[1], line[0], line[2], line[3], wl[idx, 'concept'], line[4], ' '.join(tokens), wl[idx, 'reflex']] idxx += 1 wl2 = Wordlist(out) wl2.output('tsv', filename='byangsi', ignore='all', prettify=False)
raphaelamorim/fbthrift
thrift/compiler/test/fixtures/namespace/gen-py/my/namespacing/test/ttypes.py
Python
apache-2.0
5,135
0.013437
# # Autogenerated by Thrift # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # @generated # from __future__ import absolute_import import six from thrift.util.Recursive import fix_spec from thrift.Thrift import * from thrift.protocol.TProtocol import TProtocolException import pprint import warn...
(0) or sys.version_info.major >= 3 class Foo: """ Attributes: - MyInt """
thrift_spec = None thrift_field_annotations = None thrift_struct_annotations = None __init__ = None @staticmethod def isUnion(): return False def read(self, iprot): if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocol) and iprot....
danhuss/faker
faker/providers/internet/bg_BG/__init__.py
Python
mit
1,900
0.006044
from .. import Provider as InternetProvider class Provider(InternetProvider): user_name_formats = ( '{{last_name_female}}.{{first_name_female}}', '{{last_name_male}}.{{first_name_male}}', '{{last_name_male}}.{{first_name_male}}', '{{first_name_male}}.{{last_name_male}}', '...
('Й', 'i'), ('Л', 'l'), ('П', 'p'), ('Ф', 'f'), ('Ц', 'ts'), ('Ч', 'ch'), ('Ш', 'sh'), ('Щ', 'sht'), ('Ъ', 'u'), ('Ь', ''), ('Ю', 'yu'), ('Я', 'ya'), ('б', 'b'), ('в', 'v'), ('д', 'd'), ('ж', 'zh'), ('з', 'z'), ('и', 'i'), ('й', 'i'), ('к', 'k'), ('л', 'l'), ('м', 'm'), ('н', 'n'), ('п', 'p')...
s'), ('ч', 'ch'), ('ш', 'sh'), ('щ', 'sht'), ('ъ', 'u'), ('ь', ''), ('ю', 'yu'), ('я', 'ya'), ('Б', 'b'), ('Г', 'r'), ('Д', 'd'), ('Ж', 'zh'), ('З', 'z'), ('И', 'i'), ('Й', 'i'), ('Л', 'l'), ('П', 'p'), ('Ф', 'f'), ('Ц', 'ts'), ('Ч', 'ch'), ('Ш', 'sh'), ('Щ', 'sht'), ('Ъ', 'u'), ('Ь', ''...
alphacsc/alphacsc
alphacsc/other/sporco/sporco/admm/cbpdntv.py
Python
bsd-3-clause
43,694
0.002243
# -*- coding: utf-8 -*- # Copyright (C) 2016-2017 by Brendt Wohlberg <[email protected]> # All rights reserved. BSD 3-clause License. # This file is part of the SPORCO package. Details of the copyright # and user license can be found in the 'LICENSE.txt' file distributed # with the package. """Classes for ADMM algorithm...
ttr:`itstat` is a list of tuples representing statistics of each iteration. The fields of the named tuple ``Iteration
Stats`` are: ``Iter`` : Iteration number ``ObjFun`` : Objective function value ``DFid`` : Value of data fidelity term :math:`(1/2) \| \sum_m \mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \|_2^2` ``RegL1`` : Value of regularisation term :math:`\sum_m \| \mathbf{x}_m \|_1` ...
ver228/tierpsy-tracker
tierpsy/analysis/compress/processVideo.py
Python
mit
5,963
0.013584
# -*- coding: utf-8 -*- """ Created on Fri Oct 14 15:30:11 2016 @author: worm_rig """ import json import os import tables from tierpsy.analysis.compress.compressVideo import compressVideo, initMasksGroups from tierpsy.analysis.compress.selectVideoReader import selectVideoReader from tierpsy.helper.misc import TimeCo...
ArgumentParser(description='Reformat the files produced by the Gecko plugin in to the format of tierpsy.') parser.add_argument('original_file', help='path of the original file produced by the plugin') parser.add_argument('new_file', help='new file name') parser.add_argument
( '--plugin_param_file', default = fname_wenconder, help='wormencoder file used by the Gecko plugin.') parser.add_argument( '--expected_fps', default=25, help='Expected recording rate in frame per seconds.') args = parser.parse_args() ...
ibc/MediaSoup
worker/deps/gyp/test/ninja/action-rule-hash/gyptest-action-rule-hash.py
Python
isc
938
0.001066
#!/usr/bin/env python # Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style lic
ense that can be # found in the LICENSE file. """ Verify that running gyp in a different directory does not
cause actions and rules to rerun. """ import os import sys import TestGyp test = TestGyp.TestGyp(formats=['ninja']) # The xcode-ninja generator handles gypfiles which are not at the # project root incorrectly. # cf. https://code.google.com/p/gyp/issues/detail?id=460 if test.format == 'xcode-ninja': test.skip_test(...
yanjianlong/server_cluster
public/global_manager.py
Python
bsd-3-clause
1,046
0.000962
# coding:utf-8 """ Created by 捡龙眼 3/4/2016 """ from __future__ import absolute_import, unicode_literals, print_function import public.special_exception LOG_THREAD = "log_thread" TIME_THREAD = "time_thread" GLOBAL_THREAD = {} def add_thread(key, thread_object): if key in GLOBAL_THREAD: raise pub...
in GLOBAL_THREAD.values(): try: thread_object.stop_thread() except BaseException as e: print(e) HTTP_REQUEST_MANAGER = "http_request_manager" WAITE_CONNECT_MANAGER = "wait
e_client_manager" AUTH_CONNECT_MANAGER = "auth_connect_manager" GLOBAL_OBJECT = {} def add_object(key, object): if key in GLOBAL_OBJECT: raise public.special_exception.KeyExistError("%s is exist" % (key)) GLOBAL_OBJECT[key] = object def get_object(key): return GLOBAL_OBJECT.get(key)
difio/difio
grabber.py
Python
apache-2.0
1,858
0.003229
#!/usr/bin/env python ################################################################################ # # Copyright (c) 2012, Alexander Todorov <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ...
an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################ import os from urlgrabber.grabber...
t Unicode URLs, see rhbz #515797 url = url.encode('ascii', 'ignore') if not os.path.exists(dirname): os.makedirs(dirname) basename = os.path.basename(url) filename = "%s/%s" % (dirname, basename) if os.path.exists(filename): raise Exception("File %s already exists! Not downloading...
takaakiaoki/PyFoam
PyFoam/Infrastructure/RunHooks/PrintMessageHook.py
Python
gpl-2.0
443
0.018059
"""A simple hook that only prints a user-specified message""" from PyFoam.Infrastructure.RunHook import RunHook from PyFoam.ThirdParty.six import print_ class PrintMessageHook(RunHook): """Print a small message""" def __init__(self,runner,name): RunHook.__init__(self,runner,name) self.message...
Python2
emijrp/pywikibot-core
pywikibot/__init__.py
Python
mit
27,152
0.000332
# -*- coding: utf-8 -*- """The initialization file for the Pywikibot framework.""" # # (C) Pywikibot team, 2008-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __release__ = '2.0b3' __version__ = '$Id$' import datetime import math import re import sys import threadi...
ediaWiki internal timestamp to a Timestamp object.""" # If inadvertantly passed a Timestamp object, use replace() # to create a clone. if isinstance(ts, cls): return ts.clone() return cls.strptime(ts, cls.mediawikiTSFormat) def isoformat(self): """ Conver...
is included, which causes MediaWiki ~1.19 and earlier to fail. """ return self.strftime(self.ISO8601Format) toISOformat = redirect_func(isoformat, old_name='toISOformat', class_name='Timestamp') def totimestampformat(self): """Convert object to a...
beekpr/wsgiservice
docs/conf.py
Python
bsd-2-clause
6,526
0.006436
# -*- coding: utf-8 -*- # # WsgiService documentation build configuration file, created by # sphinx-quickstart on Fri May 1 16:34:26 2009. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
e_index = True # If tr
ue, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this opti...
kcsry/wurst
wurst/core/utils/schema_import.py
Python
mit
3,317
0.000603
import sys from collections import defaultdict, OrderedDict import toml from wurst.core.models import IssueType, Priority, Status, Transition def sift(iterable, predica
te): """ Sift an iterable into two lists, those which pass the predicate and those who don't. :param iterable: :param predicate: :return: (True-list, False-list) :rtype: tuple[list, list
] """ t_list = [] f_list = [] for obj in iterable: (t_list if predicate(obj) else f_list).append(obj) return (t_list, f_list) class SchemaImporter: """ An utility to import an issue type/priority/status/... schema. After the import is finished, the ``objects`` field will be po...
chipx86/reviewboard
reviewboard/diffviewer/tests/test_myersdiff.py
Python
mit
1,475
0
from __future__ import unicode_literals from reviewboard.diffviewer.myersdiff import MyersDiffer from reviewboard.testing import TestCase class MyersDifferTest(TestCase): """Unit tests for MyersDiffer.""" def test_equals(self): """Testing MyersDiffer with equal chunk""" self._test_diff(['1',...
t_diff(['1', '2', '3'], [], [('delete', 0, 3, 0, 0), ]) def test_insert_before_lines(self): """Testing MyersDiffer with insert before
existing lines""" self._test_diff('1\n2\n3\n', '0\n1\n2\n3\n', [('insert', 0, 0, 0, 2), ('equal', 0, 6, 2, 8)]) def test_replace_insert_between_lines(self): """Testing MyersDiffer with replace and insert between existing line...
pronexo-odoo/odoo-argentina
l10n_ar_account_check_duo/account.py
Python
agpl-3.0
1,557
0.003213
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 OpenERP - Team de Localización Argentina. # https://launchpad.net/~openerp-l10n-ar-localization # # This program is free software: you can redistribute it and/or modify # it under the terms of t...
########################### from openerp.osv import osv, fields class account_journal(osv.osv): _name = 'account.journal' _inherit = 'account.journal' _columns = { 'use_issued_check': fields.boolean('Use Issued Checks', help='Allow to user Issued Checks in associated vouchers.'), 'use_thir...
'Validate only Checks', help='If marked, when validating a voucher, verifies that the total amounth of the voucher is the same as the checks used.'), } account_journal()
nmercier/linux-cross-gcc
win32/bin/Lib/idlelib/idle_test/test_calltips.py
Python
bsd-3-clause
7,325
0.003549
import unittest import idlelib.CallTips as ct CTi = ct.CallTips() # needed for get_entity test in 2.7 import textwrap import types import warnings default_tip = '' # Test Class TC is used in multiple get_argspec test methods class TC(object): 'doc' tip = "(ai=None, *args)" def __init__(self,...
r(self): # test that starred first parameter is *not* removed from argspec class C: def m1(*args): pass def m2(**kwds): pass def f1(args, kwargs, *a, **k):
pass def f2(args, kwargs, args1, kwargs1, *a, **k): pass c = C() self.assertEqual(signature(C.m1), '(*args)') self.assertEqual(signature(c.m1), '(*args)') self.assertEqual(signature(C.m2), '(**kwargs)') self.assertEqual(signature(c.m2), '(**kwargs)') self....
kajgan/stbgui
lib/python/Plugins/Extensions/GraphMultiEPG/GraphMultiEpg.py
Python
gpl-2.0
57,664
0.031614
from skin import parseColor, parseFont, parseSize from Components.config import config, ConfigClock, ConfigInteger, ConfigSubsection, ConfigYesNo, ConfigSelection, ConfigSelectionNumber from Components.Pixmap import Pixmap from Components.Button import Button from Components.ActionMap import HelpableActionMap from Comp...
fig.misc.graph_mepg.extension_menu = ConfigYesNo(default = False) config.misc.graph_mepg.show_record_clocks = ConfigYesNo(default = True) config.misc.graph_mep
g.zap_blind_bouquets = ConfigYesNo(default = False) listscreen = config.misc.graph_mepg.default_mode.value class EPGList(HTMLComponent, GUIComponent): def __init__(self, selChangedCB = None, timer = None, time_epoch = 120, overjump_empty = True, epg_bouquet=None): GUIComponent.__init__(self) self.cur_event = Non...
m-kiuchi/ouimeaux
setup.py
Python
bsd-3-clause
1,705
0.002346
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys here = lambda *a: os.path.join(os.path.dirname(__file__), *a) try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.
system('python setup.py sdist upload') sys.exit() readme = open(here('README.rst')).read() history = open(here('HISTORY.rst')).read().replace('.. :changelog:', '') requirements = [x.strip() for x in open(here('requirements.txt')).readlines()] setup( name='ouimeaux', version='0.7.9', description='Open ...
.com/iancmcc/ouimeaux', packages=[ 'ouimeaux', ], package_dir={'ouimeaux': 'ouimeaux'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='ouimeaux', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Topic ::...