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
baylee/django
tests/postgres_tests/test_json.py
Python
bsd-3-clause
9,110
0.000768
import datetime import unittest from django.core import exceptions, serializers from django.db import connection from django.forms import CharField, Form from django.test import TestCase from django.utils.html import escape from . import PostgreSQLTestCase from .models import JSONModel try: from django.contrib.p...
e valid JSON.") class TestFormField(PostgreSQLTestCa
se): def test_valid(self): field = forms.JSONField() value = field.clean('{"a": "b"}') self.assertEqual(value, {'a': 'b'}) def test_valid_empty(self): field = forms.JSONField(required=False) value = field.clean('') self.assertEqual(value, None) def test_inv...
LockScreen/Backend
venv/bin/rst2xml.py
Python
mit
642
0.001558
#!/Users/Varun/Documents/GitHub/LockS
creen/venv/bin/python # $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing Docutils XML. """ try: import locale locale.setlocale(locale.LC_...
ne, default_description description = ('Generates Docutils-native XML from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='xml', description=description)
shawnadelic/shuup
shuup_tests/core/test_products.py
Python
agpl-3.0
3,884
0.00309
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from shuup.core.models import ( AnonymousContact, get_pe...
ct_query_with_group_visibility(regular_user): default_group = get_default_customer_group() shop_product = get_default_shop_product() shop_product.visibility_limit = 3 shop_product.save() shop = shop_product.shop product = shop_product.product shop_product.visibility_groups.add(default_group)...
ot Product.objects.listed(shop=shop, customer=regular_contact).filter(pk=product.pk).exists() regular_contact.groups.add(default_group) assert Product.objects.listed(shop=shop, customer=regular_contact).filter(pk=product.pk).count() == 1 shop_product.visibility_groups.add(regular_contact.get_default_group(...
pilou-/ansible
lib/ansible/module_utils/network/iosxr/providers/module.py
Python
gpl-3.0
2,093
0.000956
# # (c) 2019, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.iosxr.providers import providers from ansible...
network_api'] if network_api == 'cliconf': connection_type = 'network_cli' cls = providers.get(network_os, self._name, connection_type) if not cls: msg =
'unable to find suitable provider for network os %s' % network_os if self.fail_on_missing_provider: self.fail_json(msg=msg) else: self.warn(msg) obj = cls(self.params, self.connection, self.check_mode) setattr(self, '_prov...
MuckRock/muckrock
muckrock/message/utils.py
Python
agpl-3.0
793
0
"""Utility functions for sending slack messages""" # Django from django.conf import settings def format_user(user): """Format a user for inclusion in a Slack notification""" return "<%(url)s|%(name)s>" % { "url": settings.MUCKROCK_URL + user.get_absolute_url(), "name": user.profile.full_name,...
urn {"title": field_ti
tle, "value": field_value, "short": field_short}
waveform80/lars
tests/test_dns.py
Python
mit
2,559
0.001563
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Copyright (c) 2013-2017 Dave Jones <dave@waveform.org.uk> # Copyright (c) 2013 Mime Consulting Ltd. <info@mimeconsulting.co.uk> # All rights reserved. # # Permission is hereby granted, free
of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, includi
ng without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in #...
rohitwaghchaure/GenieManager-erpnext
erpnext/manufacturing/doctype/production_planning_tool/production_planning_tool.py
Python
agpl-3.0
15,108
0.026542
# 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.utils import cstr, flt, cint, nowdate, now, add_days, comma_and from frappe import msgprint, _ from frappe.model.document im...
+ self.from_date + '"' if self.to_date: so_filter += ' and so.transaction_date <= "' + self.to_date + '"' if self.customer: so_filter += ' and so.customer = "' + self.customer + '"' if self.fg_item: item_filter += ' and item.name = "' + self.fg_item + '"' open_so = frappe.db.sql(""" select distin...
so.customer, so.base_grand_total from `tabSales Order` so, `tabSales Order Item` so_item where so_item.parent = so.name and so.docstatus = 1 and so.status != "Stopped" and so.company = %s and ifnull(so_item.qty, 0) > ifnull(so_item.delivered_qty, 0) %s and (exists (select name from `tabItem` item ...
ChinaMassClouds/copenstack-server
openstack/src/horizon-2014.2/openstack_dashboard/dashboards/admin/checkhost/panel.py
Python
gpl-2.0
495
0
from django.utils.translat
ion import ugettext_lazy as _ import horizon from openstack_dashboard.dashboards.admin import dashboard from openstack_dashboard.openstack.common.log import policy_is class CheckHost(horizon.Panel): name = _("Instance") slug = 'checkhost' img = '/static/dashboard/img/nav/checkhost1.png' def nav(self,...
st)
jiriprochazka/lnst
lnst/Common/Config.py
Python
gpl-2.0
16,286
0.008105
""" Module containing class used for loading config files. Copyright 2012 Red Hat, Inc. Licensed under the GNU General Public License, version 2 as published by the Free Software Foundation; see COPYING for details. """ __autor__ = """ olichtne@redhat.com (Ondrej Lichtner) """ import os import sys import re import s...
additive" : False, "action" : self.optionPath, "name" : "ctl_pubkeys"} self.colours_scheme() def colours_scheme(self): self._options['colours'] = dict() self._options['colours']["disable_colours"] = {\ "value": False, "additive": False, ...
n": self.optionBool, "name": "disable_colours"} for preset in ["faded", "alert", "highlight", "pass", "fail", "error", "info", "debug", "warning", "log_header"]: self._options['colours'][preset] = {\ "value": get_preset_conf(preset), "additive": False, ...
brhoades/holdem-bot
holdem-ea/poker.py
Python
mit
811
0.006165
import random from solution import Solution from awesome_print import ap def copulate(gen, p
arent1, parent2): """ Randomly averages values or chooses one of parents (50/50). Returns a new solution. """ child = Solution(parent1.data, gen) if parent1 is not parent2: copulate_recursive(child.data, parent2.data) child.update_hash()
return child def copulate_recursive(childd, parent2d): """ Recursively combines/shares data dict values """ for k in childd: if isinstance(childd[k], int) or isinstance(childd[k], float): if random.randint(0,1) == 1: # if 1, we change to parent 2... keep otherwise ...
valhallasw/pywikibot-core
tests/cache_tests.py
Python
mit
1,258
0
# -*- coding:
utf-8 -*- """API Request cache tests.""" # # (C) Pywikibot team, 2012-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __version__ = '$Id$' # from pywikibot.site import BaseSite import scripts.maintenance.cache as cache from tests import _cache_dir from tests.aspect...
def _check_cache_entry(self, entry): """Assert validity of the cache entry.""" self.assertIsInstance(entry.site, BaseSite) self.assertIsInstance(entry.site._loginstatus, int) self.assertIsInstance(entry.site._username, list) if entry.site._loginstatus >= 1: self....
JakubBrachTieto/openthread
tests/scripts/thread-cert/Cert_5_3_04_AddressMapCache.py
Python
bsd-3-clause
5,192
0.000578
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
self.nodes[ED5].enable_whitelist() def tearDown(self): for node in list(self.nodes.values()): node.stop() del self.nodes def test(self): self.nodes[LEADER].start() self.nodes[LEADER].set_state('leader') self.assertEqual(self.nodes[LEADER].get_state(), '...
ROUTER1].get_state(), 'router') self.nodes[SED1].start() time.sleep(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') self.nodes[ED2].start() time.sleep(5) self.assertEqual(self.nodes[ED2].get_state(), 'child') self.nodes[ED3].start() time.slee...
benfinke/ns_python
nssrc/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_binding.py
Python
apache-2.0
3,621
0.033969
# # Copyright (c) 2008-2015 Citrix Systems, 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 l...
raise e @classmethod def get(self, service, clid) : ur""" Use this API to fetch clusterinstance_binding resource. """ try : if type(clid) is not list : obj = clusterinstance_binding() obj.clid = clid response = obj.get_resource(service) else : if clid and len(clid) > 0 : obj = ...
j[i].get_resource(service) return response except Exception as e: raise e class clusterinstance_binding_response(base_response) : def __init__(self, length=1) : self.clusterinstance_binding = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.clusterinstance_bindin...
spiffcode/hostile-takeover
stats/drain.py
Python
bsd-2-clause
1,517
0.003296
import os import command import serverinfo import accounts from google.appengine.ext.webapp import template class Drain(command.Command): def have_access(self): account = accounts.account() if not account or not account.DRAIN_ACCESS_RIGHT: return False return True def fini...
erinfo.ServerInfo.send_command(info, '{"command": "%s"}' % drain_command) errors.append('Server %s sent %s command.' % (info['name'], drain_command)) template_values['errors'] = errors self.response.headers['Content-Type'] = 'application/xhtml+xml' path = os.path.join(os.path.d...
self.response.out.write(template.render(path, template_values))
benbovy/xarray-simlab
doc/scripts/advection_model.py
Python
bsd-3-clause
5,038
0.000198
import numpy as np import xsimlab as xs @xs.process class AdvectionLax1D: """Wrap 1-dimensional advection in a single Process.""" spacing = xs.variable(description="grid spacing", static=True) length = xs.variable(description="grid total length", static=True) x = xs.variable(dims="x", intent="out") ...
): self.u += self._delta_u @xs.process class AdvectionLax: """Advection using finite difference (Lax method) on a fixed grid with periodic boundary conditions. """ v = xs.variable(dims=[(), "x"], description="velocity") grid_spacing = xs.foreign(UniformGrid1D, "spacing") u = xs.forei...
ileU, "u") u_advected = xs.variable(dims="x", intent="out", groups="u_vars") @xs.runtime(args="step_delta") def run_step(self, dt): factor = self.v / (2 * self.grid_spacing) u_left = np.roll(self.u, 1) u_right = np.roll(self.u, -1) u_1 = 0.5 * (u_right + u_left) - factor * ...
buguroo/pyknow
tests/unit/matchers/rete/test_rete_abstract.py
Python
lgpl-3.0
783
0
import pytest def test_node_exists(): try: from pyknow.
matchers.rete.abstract import Node from pyknow.matchers.rete.abstract import OneInputNode from pyknow.matchers.rete.abstract import TwoInputNode except ImportError as exc: assert False, exc def test_node_interface(): from pyknow.matchers.rete.abstract import Node assert {'_reset',...
face(): from pyknow.matchers.rete.abstract import OneInputNode assert {'_activate'} <= OneInputNode.__abstractmethods__ def test_twoinputnode_interface(): from pyknow.matchers.rete.abstract import TwoInputNode assert {'_activate_left', '_activate_right'} <= TwoInputNode.__abstractmethods...
gensmusic/test
third_party/python/flask/third-party/pagedown/usage.py
Python
gpl-2.0
230
0.017391
#coding:utf-8 from flask import Flask,request, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('demo.html')
if __name__ ==
'__main__': app.run(host='0.0.0.0', debug=True)
googlearchive/simian
src/tests/simian/mac/common/ipcalc_test.py
Python
apache-2.0
3,975
0.004025
#!/usr/bin/env python # # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
""Convert an IP string to int with code other than ours. Args: ip_str: str Returns: int in network byte order """ i = struct.unpack('I', socket.inet_aton(ip_str))[0] i = socket.htonl(i
) # on python 2.5 socket.htonl() returns a signed int, on later versions # python returns a python long type to return the number without sign. if i < 0: i = 4294967296L - (long(i) * -1) return i def testIpToIntWhenIpv6(self): """Test IpToInt() when passed ipv6.""" ip_str = '2620::1003:...
ging/python-keystoneclient
keystoneclient/v3/contrib/activation.py
Python
apache-2.0
1,528
0.002618
# Copyright (C) 2014 Universidad Politecnica de Madrid # 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...
ributed 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 keystoneclient import base from keystoneclient import exceptions from ke...
stoneclient.v3.contrib.user_registration.utils import REGISTRATION_PATH class Activation(base.Resource): pass class ActivationManager(base.CrudManager): """Manager class for activating user in the USER REGISTRATION extension for Keystone. For more information about the extension: https://www.github.c...
ctiller/grpc
src/python/grpcio_tests/tests_aio/interop/server.py
Python
apache-2.0
1,611
0
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
g.DEBUG) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.DEBUG) async def serve(): args = interop_server_lib.parse_interop_server_arguments() if args.use_tls or args.use_alts: credentials = interop_server_lib.get_server_credentials(args.use_tls) address, server = await _test_se...
ials=credentials) else: address, server = await _test_server.start_test_server( port=args.port, secure=False, ) _LOGGER.info('Server serving at %s', address) await server.wait_for_termination() _LOGGER.info('Server stopped; exiting.') if __name__ == '__main__':...
TshepangRas/tshilo-dikotla
td_maternal/models/base_maternal_clinical_measurements.py
Python
gpl-2.0
1,343
0.000745
from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models # from edc_base.audit_trail import AuditTrail from ..managers import MaternalClinicalMeasurementsManager from .maternal_crf_model import MaternalCrfModel class BaseMaternalClinicalMeasurements(MaternalCrfModel): ...
systolic_bp = models.IntegerField( max_length=3, verbose_name="Mother's systolic blood pressure?", validators=[MinValueValidator(75), MaxValueValidator(220), ], help_text="in mm e.g. 120, should b
e between 75 and 220." ) diastolic_bp = models.IntegerField( max_length=3, verbose_name="Mother's diastolic blood pressure?", validators=[MinValueValidator(35), MaxValueValidator(130), ], help_text="in hg e.g. 80, should be between 35 and 130.") objects = MaternalClinicalMe...
egenerat/gae-django
app/airport/staff_buyer.py
Python
mit
478
0.002092
# -*- coding: utf-8 -*- from app.common.http_methods import post_request from app.common.target_urls import HIRE_FLIGHT_ATTENDANTS_URL, HIRE_PILOTS_URL, HIRE_MECHANICS_URL def hire_pilots(pilots
_nb): post_request(HIRE_PILOTS_URL, {'cq': pilots_nb}) def hire_flight_attendants(flight_attendants_nb): post_request(HIRE_FLIGHT_ATTENDANTS_URL, {'cq': flight_attendants_nb}) d
ef hire_mechanics(mechanics_nb): post_request(HIRE_MECHANICS_URL, {'cq': mechanics_nb})
iandd0824/ri-app
web/django_mongoengine/forms/document_options.py
Python
apache-2.0
7,439
0.000403
import sys import warnings from django.db.models.fields import FieldDoesNotExist from django.utils.text import capfirst from django.utils.encoding import smart_text try: from django.db.models.options import get_verbose_name except ImportError: from django.utils.text import camel_case_to_spaces as get_verbose_...
ent._meta.module_name] = (f, document, False, False) else: self._field_cache[f.name] = (f, None, True, False) return self._field_cache def get_field(self, name, many_to_many=True): """ Returns the requested field by name. Raises FieldDoesNotExist on error. ...
KeyError as e: raise AttributeError(*e.args) def __setattr__(self, name, value): if not hasattr(self, name): self._meta[name] = value else: super(DocumentMetaWrapper, self).__setattr__(name, value) def __getitem__(self, key): return self._meta[key] ...
claudio-walser/gitcd
gitcd/interface/cli/clean.py
Python
apache-2.0
1,028
0
from gitcd.in
terface.cli.abstract import BaseCommand from gitcd.git.branch import Branch from gitcd.app.clean import Clean as CleanHelper class Clean(BaseCommand): updateRemote = True def run(self, branch: Branch): helper = CleanHelper() branchesToDelete = helper.getBranchesToDelete() self.in...
self.interface.red(" - %s" % branchToDelete.getName()) self.interface.writeOut('') if len(branchesToDelete) == 0: self.interface.ok('Nice, your local repository is clean already.') return True delete = self.interface.askFor( 'Do you want me to dele...
moio/spacewalk
rel-eng/koji-missing-builds.py
Python
gpl-2.0
2,946
0.004073
#!/usr/bin/python try: import koji except: import brew as koji import os import string import sys from optparse import OptionParser import ConfigParser config = ConfigParser.RawConfigParser() config.read(["tito.props", "rel-eng/tito.props"]) usage = "usage: %prog [options] <tag to check>" parser = OptionPars...
extra builds listing") (opts, args) = parser.parse_args() if len(args)
< 1: print "ERROR: need to specify tag to check\n" parser.print_help() sys.exit(1) if len(args) > 1: print "ERROR: Only one tag at a time.\n" parser.print_help() sys.exit(1) distsuffix = '' tag = args[0] pkgstoignore = [] if config.has_section(tag) and config.has_option(tag, 'blacklist'): ...
davy39/eric
DebugClients/Python/coverage/config.py
Python
gpl-3.0
7,122
0.000281
"""Config file for coverage.py""" import os, re, sys from .backward import string_class, iitems # In py3, # ConfigParser was renamed to the more-standard configparser try: import configparser # pylint: disable=F0401 except ImportError: import ConfigParser as
configparser class HandyConfigParser(configparser.RawConfigParser): """Our specialization of ConfigParser.""" def read(self, filename): """Read a filename as UTF-8 configuration data.""" kwargs = {} if sys.version_info >= (3, 2): kwargs['encoding'] = "utf-8" retur...
**kwargs) def dollar_replace(m): """Called for each $replacement.""" # Only one of the groups will have matched, just get its text. word = [w for w in m.groups() if w is not None][0] if word == "$": return "$" else: ret...
lwalstad-pivotal/unified-demonstration-sentiment_01
gen-tweet-stats/helper_functions.py
Python
mit
1,012
0.013834
import json import os import time import redis # initialize redis connection for local and CF deployment def connect_redis_db(redis_service_name = 'p-redis'): if os.environ.get('VCAP_SERVICES') is None: # running locally DB_HOST = 'localhost' DB_PORT = 6379 DB_PW = '' REDIS_DB = 1 ...
edis(host=DB_HOST, port=DB_PORT, password=DB_PW,
db=REDIS_DB) def been_n_second(n,time_now,time_start,wait_time = 0.01): time_delta = time_now - time_start if time_delta >= n: return True time.sleep(wait_time) return False
cdglabs/tableVision
ddp/pipeline/hv_lines.py
Python
mit
831
0.012034
import numpy as np import infrastructure.intake as intake import infrastructure.log as log import core.topology as topology import core.satisfaction as satisfaction def run(graph, img): graph = topology.simplify_junctures(graph) log.hsvOrGreyImage(img, points=(node for node in graph.nodes() if graph...
ts=graph.nodes(), lines=graph.edges() ) graph = topology.hv_lines(graph) log.hsvOrGreyImage(img, points=graph.nodes(), lines=graph.edges() ) graph = satisfaction.align(graph) log.hsvOrGreyImage(
img, points=graph.nodes(), lines=graph.edges() ) return graph def sample(): return intake.gpickle("input/grid_graph.gpickle")
stuartlangridge/webutils-calculator
update-cache-manifest.py
Python
mit
292
0.003425
#!/usr/bin/env python import time fp = open("calculator.appcache") out = [] for line in fp.readlines(): if line.startswith("# date: "): line = "# date: %s\n" %
time.asctime() out.append(line) fp.close() fp = open("cal
culator.appcache", "w") fp.write("".join(out)) fp.close()
marineam/nagcat
python/nagcat/plugins/query_subprocess.py
Python
apache-2.0
8,466
0.000945
# Copyright 2008-2010 ITA Software, 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 ...
ef outReceived(self, data): self.result += data def errReceived(self, data): key = "Process stderr" self.factory.saved[key] = self.factory.saved.get(key, "") + data def timeout(self): self.timedout = True
self.transport.loseConnection() # Kill all processes in the child's process group if self.transport.pid: try: os.kill(-int(self.transport.pid), signal.SIGTERM) except OSError, ex: log.warn("Failed to send TERM to a subprocess: %s", ex) d...
petrutlucian94/nova_dev
nova/virt/hyperv/vmops.py
Python
apache-2.0
17,820
0.000056
# Copyright (c) 2010 Cloud.com, Inc # Copyright 2012 Cloudbase Solutions Srl # 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/...
See the # License for the specific language governing permissions and limitations # under the License. """ Management class for basic VM operations. """ import functools import os from oslo.config import cfg from nova.api.metadata import base as instance_metadata fro
m nova import exception from nova.openstack.common import excutils from nova.openstack.common.gettextutils import _ from nova.openstack.common import importutils from nova.openstack.common import log as logging from nova.openstack.common import processutils from nova.openstack.common import units from nova import utils...
3cky/google-play-review-notify
reviewnotify/notifiers.py
Python
gpl-3.0
1,388
0.002161
# -*- coding: utf-8 -*- ''' Created on 10-Jul-2015 @author: 3cky ''' from twisted.python import log from wokkel.muc import MUCClient from fnmatch import fnmatch class MUCNotifier(MUCClient): """ Multi-user chat notifier. """ def __init__(self, chatJID, nick, appIdPatterns): MUCClient.__init_...
appIdP
attern): return True return False def notify(self, message): """ Send message to chat. """ self.groupChat(self.chatJID, message)
quartzmo/google-cloud-ruby
google-cloud-datastore/synth.py
Python
apache-2.0
3,270
0.003976
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/license
s/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li
cense 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. """This script is used to synthesize generated parts of this library.""" import synthtool as s imp...
jsj2008/kdegames
kajongg/src/config.py
Python
gpl-2.0
5,516
0.002538
# -*- coding: utf-8 -*- """ Copyright (C) 2008-2012 Wolfgang Rohdewald <wolfgang@rohdewald.de> partially based on C++ code from: Copyright (C) 2006 Mauricio Piacentini <mauricio@tabuleiro.com> kajongg is free software you can redistribute it and/or modify it under the terms of the GNU General Public License as p...
group self.name = name self.default = default self.item = None def itemValue(self): """returns the value of this item""" return self.item.value() class StringParameter(Parameter): """helper class for defining string parameters""" def __init__(self, group, name, defa...
ult = '' Parameter.__init__(self, group, name, default) self.value = QString() def add(self, skeleton): """add tis parameter to the skeleton""" self.item = skeleton.addItemString(self.name, self.value, QString(self.default or '')) def itemValue(self): """returns the val...
ilikecola/Shadowsocks-combine-manyuser
shadowsocks/eventloop.py
Python
apache-2.0
7,495
0
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013-2015 clowwindy # # 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...
L', POLL_IN: 'POLL_IN', POLL_OUT: 'POLL_OUT', POLL_ERR: 'POLL_ERR', POLL_HUP: 'POLL_HUP', POLL_NVAL: 'POLL_NVAL', } class EpollLoop(object): def __init__(self): self._epoll = select.epoll() def poll(self, timeout): return self._epoll.poll(timeout) def add_fd(sel
f, fd, mode): self._epoll.register(fd, mode) def remove_fd(self, fd): self._epoll.unregister(fd) def modify_fd(self, fd, mode): self._epoll.modify(fd, mode) class KqueueLoop(object): MAX_EVENTS = 1024 def __init__(self): self._kqueue = select.kqueue() self._...
hoytak/lazyrunner
test/test_environment/data/data.py
Python
bsd-3-clause
2,204
0.009528
from lazyrunner import pmodule, PModule, preset, presetTree, defaults from treedict import TreeDict p = defaults() p.data_defaults.a = 1 p.data_defaults.b = 2 @preset def chang
e_default_a(p): p.data_defaults.a = 10 @pmodule class Data(PModule): # Use this to set up the local branch of the preset tree. Calling # defaults() requests the local branch of the p = defaults() p.x = 1 @preset def set_X_2(p): p.x = 2 @preset def set_X(p, x =...
ies # assume results are different between different versions. version = 0.01 # Include dependencies here; alternatively, these may be given as # class methods, optionally accepting the parameter tree, to # provide parameter-dependent dependency checking. See # documentation for more info. ...
johansten/stellar-py
stellar/serialize.py
Python
bsd-3-clause
4,565
0.035268
from decimal import Decimal from address import account_from_human from utils import * #------------------------------------------------------------------------------- FIELD_MAP = { 'Account': (8, 1), 'Amount': (6, 1), 'ClearFlag': (2, 34), 'Destination': (8, 3), 'DestinationTag': (2, 14), 'Fee': (6, ...
---------------------------------------------------- de
f parse_non_native_amount(string): amount = Decimal(string).normalize() parts = amount.as_tuple() exponent = parts.exponent value = ''.join(map(str, parts.digits)) exponent += len(value) value = value.ljust(16, '0') exponent -= 16 value = int(value) if value == 0: exponent = -99 return parts.sign, va...
zyzyis/monetdb
sql/test/BugTracker/Tests/mdb_starts_with_sql_debug_64.SF-1999354.py
Python
mpl-2.0
983
0.020346
import os, sys try: from MonetDBtesting import process except ImportError: import process def server_start(args): sys.stderr.write('#mserver: "%s"\n' % ' '.join(args)) sys.stderr.flush() srv = process.server(args = args, stdin = process.PIPE,
stdout = process.PIPE, stderr = process.PIPE) return srv def client(lang, file): sys.stderr.write('#client: "%s"\n' % file) sys.stderr.flush() clt = process.client(lang.lower(), stdin = open(file), stdout = process.PIPE, stderr = process.PIPE) return clt.communicate() d...
'mdb_starts_with_sql_debug_64.SF-1999354.sql')) sys.stdout.write(out) sys.stderr.write(err) out, err = srv.communicate() sys.stdout.write(out) sys.stderr.write(err) main()
er432/TASSELpy
TASSELpy/java/util/Deque.py
Python
bsd-3-clause
11,930
0.01031
from TASSELpy.utils.helper import make_sig from TASSELpy.utils.Overloading import javaOverload, javaConstructorOverload, javaGenericOverload from TASSELpy.java.util.Queue import Queue from TASSELpy.java.lang.Object import Object from TASSELpy.java.util.Iterator import Iterator java_imports = {'Deque':'java/lang/Deque'...
(make_sig([],java_imports['Iterator']),(), dict(type=Iterator, generic=('/@1/',)))) def descendingI
terator(self, *args): """ Returns an iterator over the elements in this deque in reverse sequential order. The elements will be returned in order from last (tail) to first (head) Signatures: Iterator<E> descendingIterator() Returns: An iterator over the elements in th...
eduNEXT/edx-platform
lms/djangoapps/instructor/tests/test_spoc_gradebook.py
Python
agpl-3.0
6,317
0.0019
""" Tests of the instructor dashboard spoc gradebook """ from django.urls import reverse from capa.tests.response_xml_factory import StringResponseXMLFactory from common.djangoapps.student.tests.factories import AdminFactory, CourseEnrollmentFactory, UserFactory from lms.djangoapps.courseware.tests.factories import St...
ssigned_grades(self): # Users 9-10 have >= 90% on Homeworks [2] # Users 9-10 have >= 90% on the class [2] # One use at the top of the page [1] assert 5 == self.response.content.count(b'grade_A') # User 8 has 80 <= Homeworks < 90 [1] # User 8 has 80 <= class < 90 [1] ...
content.count(b'grade_B') # User 7 has 70 <= Homeworks < 80 [1] # User 7 has 70 <= class < 80 [1] # One use at the top of the page [1] assert 3 == self.response.content.count(b'grade_C') # User 6 has 60 <= Homeworks < 70 [1] # User 6 has 60 <= class < 70 [1] # O...
Xarthisius/girder
girder/__init__.py
Python
apache-2.0
12,075
0.000994
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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 ...
e for a file-like object to have name appear in dir(stream) but not # a
ctually be an attribute, thus using a default with getattr is required. # See https://github.com/GrahamDumpleton/mod_wsgi/issues/184 for more. if (key != 'write' and not key.startswith('_') and ( callable(getattr(stream, key, None)) or isinstance(getattr(s...
yakinaround/myadventure-front
app/mod_facebook/__init__.py
Python
apache-2.0
36
0
""
" Initialize facebook module """
dcramer/gitboard
gitboard/__init__.py
Python
apache-2.0
126
0
try: VERSION = __impo
rt__("pkg_resources").get_distribution("gitboard").version except Exception: VERSION = "unkno
wn"
acbecker/BART
steps.py
Python
mit
11,512
0.005386
""" This file contains the class definitions and functions that form the base of an MCMC sampler. These classes are the base Parameter class, various MCMC step classes (e.g., Gibbs update, Metropolis-Hastings update), and various proposal distributions for the Metropolis-like algorithms. """ #TODO: ADD IN ASSERTIONS T...
self._alpha = np.exp(min(0.0, alpha)) unif = np.random.uniform() if not np.isfinite(alpha): # Make sure alpha is finite, otherwise reject the proposal self
._alpha = alpha return False return unif < self._alpha def do_step(self): proposed_value = self._proposal.draw(self._parameter.value) if self.accept(proposed_value, self._parameter.value): self._parameter.value = proposed_value self._parameter._log_post...
SanketDG/networkx
examples/graph/knuth_miles.py
Python
bsd-3-clause
2,993
0.016372
#!/usr/bin/env python """ An example using networkx.Graph(). miles_graph() returns an undirected graph over the 128 US cities from the datafile miles_dat.txt. The cities each have location and population data. The edges are labeled with the distance betwen the two cities. This example is described in Section 1.1 in ...
G.add_edge(city,cities[i],weight=int(d)) i=i+1 else: # this line is a city, position, population i=1 (city,coordpop)=line.split("[") cities.insert(0,city) (coord,pop)=coordpop.split("]") (y,x)=coord.split(",") ...
nt(y)-3000) G.population[city]=float(pop)/1000.0 return G if __name__ == '__main__': import networkx as nx import re import sys G=miles_graph() print("Loaded miles_dat.txt containing 128 cities.") print("digraph has %d nodes with %d edges"\ %(nx.number_of...
plotly/python-api
packages/python/plotly/plotly/validators/layout/yaxis/_showtickprefix.py
Python
mit
562
0.003559
impor
t _plotly_utils.basevalidators class ShowtickprefixValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="showtickprefix", parent_name="layout.yaxis", **kwargs ): super(ShowtickprefixValidator, self).__init__( plotly_name=plotly_name, ...
ll", "first", "last", "none"]), **kwargs )
alexandrul-ci/robotframework
src/robot/parsing/tablepopulators.py
Python
apache-2.0
9,810
0.000102
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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 ...
nt_row) def _get_populator(self, row): if row.starts_test_or_user_keyword_setting(): setter = self._setting_setter(row) if not setter: return NullPopulator() if isinstance(setter.__self__, Documentation): return DocumentationPopulator(sett...
return ForLoopPopulator(self._test_or_uk.add_for_loop) return StepPopulator(self._test_or_uk.add_step) def _continues(self, row): return row.is_continuing() and self._populator or \ (isinstance(self._populator, ForLoopPopulator) and row.is_indented()) def _setting_sett...
junhuac/MQUIC
src/tools/android/loading/sandwich_runner.py
Python
mit
9,553
0.007537
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import logging import os import shutil import sys import tempfile _SRC_DIR = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', ...
trace = loading_trace.LoadingTrace.RecordUrlNavigation( url=url, connection=connection, chrome_metadata=self._chrome_ctl.ChromeMetadata(), categories
=sandwich_metrics.CATEGORIES, timeout_seconds=_DEVTOOLS_TIMEOUT) else: trace = loading_trace.LoadingTrace.RecordUrlNavigation( url=url, connection=connection, chrome_metadata=self._chrome_ctl.ChromeMetadata(), categories=sandwich_metrics.CATEGO...
sgubianpm/RPackUtils
tests/test_graph.py
Python
gpl-2.0
766
0
####################################### # Copyright 2019 PMP SA. # # SPDX-License-Identifier: Apache-2.0 # ####################################### from rpackutils.graph import Graph from rpackutils.graph import Node def create_graph(): g = Graph() for i in range(10): n = Node(str(i)) ...
', 1) g.connect('4', '7', 1) g.connect('3', '6', 1) g.connect('3', '9', 1)
return g def test_create_graph(): g = create_graph() for i in range(10): print(g.node(str(i))) assert(g)
WillsB3/Sim-Checklist
simchecklist/core/migrations/0008_auto__add_field_aircraft_slug__chg_field_checklistphase_slug.py
Python
mit
2,870
0.007317
# -*- 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): # Adding field 'Aircraft.slug' db.add_column(u'core_aircraft', 'slug', ...
': '50', 'populate_from': "'name'"}) }, u'core.checkliststep': { 'Meta': {'ordering': "('order',)", 'object_name': 'ChecklistStep'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'checklist_phase': ('django.db.models.fields.r
elated.ForeignKey', [], {'related_name': "'steps'", 'to': u"orm['core.ChecklistPhase']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'item': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'order': ('django.db.models.fields.PositiveI...
tadhg-ohiggins/regulations-parser
tests/tree_depth_derive_tests.py
Python
cc0-1.0
11,439
0
from unittest import TestCase import six from regparser.tree.depth import markers, optional_rules, rules from regparser.tree.depth.derive import debug_idx, derive_depths from regparser.tree.depth.markers import INLINE_STARS, MARKERLESS, STARS_TAG class DeriveTests(TestCase): def assert_depth_match(self, markers...
hat the set of markers resolves to the provided set of depths (in any order). Allows extra constraints.""" solutions = derive_depths(markers, extra) results = {tuple(a.depth for a in s) for s in solutions} six.assertCountEqual(self, results, {tuple(s) for s in depths_set}) def test_...
[0, 0, 0, 0]) def test_alpha_ints(self): self.assert_depth_match(['A', '1', '2', '3'], [0, 1, 1, 1]) def test_alpha_ints_jump_back(self): self.assert_depth_match(['A', '1', '2', '3', 'B', '1', '2', '3', 'C'], [0, 1, 1, 1, 0, 1, 1,...
plotly/plotly.py
packages/python/plotly/plotly/validators/histogram2dcontour/hoverlabel/_namelengthsrc.py
Python
mit
471
0
import _plotly_utils
.basevalidators class NamelengthsrcValidator(_plotly_utils.basevalidato
rs.SrcValidator): def __init__( self, plotly_name="namelengthsrc", parent_name="histogram2dcontour.hoverlabel", **kwargs ): super(NamelengthsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs...
msincenselee/vnpy
prod/jobs/refill_tdx_cb_stock_bars.py
Python
mit
3,556
0.00403
# flake8: noqa """ 下载通达信可转债1分钟bar => vnpy项目目录/bar_data/ 上海股票 => SSE子目录 深圳股票 => SZSE子目录 """ import os import sys import csv import json from collections import OrderedDict import pandas as pd vnpy_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) if vnpy_root not in sys.path: sys.path.appe...
ata_df.tail()) data_df.to_csv(bar_file_path, index=True) print(f'首次更新{stock_co
de} {stock_name}数据 => 文件{bar_file_path}') continue # 获取标题 headers = [] with open(bar_file_path, "r", encoding='utf8') as f: reader = csv.reader(f) for header in reader: headers = header break bar_count = 0 # 写入所有大于最后bar时间的数据 with open(bar_file_pa...
gkc1000/pyscf
pyscf/nao/m_ao_eval_libnao.py
Python
apache-2.0
3,652
0.016977
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
res, dtype=c_double, requirements='CW') mu2j = np.require(ao.sp_mu2j[isp], dtype=c_int64, requirements='C') mu2s = np.require(ao.sp_mu2s[isp], dtype=c_int64, requirements='C') mu2rcut = np.require(ao.sp
_mu2rcut[isp], dtype=c_double, requirements='C') ff = np.require(ao.psi_log_rl[isp], dtype=c_double, requirements='C') libnao.ao_eval( c_int64(ao.sp2nmult[isp]), ff.ctypes.data_as(POINTER(c_double)), c_int64(ao.nr), c_double(ao.interp_rr.gammin_jt), c_double(ao.interp_rr.dg_jt), mu2j.ctype...
The-Compiler/qutebrowser
qutebrowser/browser/navigate.py
Python
gpl-3.0
8,364
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # 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...
eroes: if len(number) < len(str(val)): zeroes = zeroes[1:] elif len(number) > len(str(val)): zeroes += '0' return ''.join([pre, zeroes, str(val), post]) def incdec(url, count, inc_or_dec): """Helper method for :navi
gate when `where' is increment/decrement. Args: url: The current url. count: How much to increment or decrement by. inc_or_dec: Either 'increment' or 'decrement'. tab: Whether to open the link in a new tab. background: Open the link in a new background tab. window: O...
nvoron23/hadoop-fundamentals
spark/sales.py
Python
mit
1,793
0.006693
## Count the number of sales per month in our order history. ## Imports import csv from operator import add from datetime import datetime from StringIO import StringIO from collections import namedtuple from pyspark import SparkConf, SparkContext ## Helper constants DATE_FMT = "%Y-%m-%d %H:%M:%S" # 2013-09-16 12:23:...
nt(row[2]) # Parse Customer ID to an integer row[3] = datetime.strptime(row[3], DATE_FMT) return Order(*row) def split(line): """ Operator function for splitting a line on a delimiter. """ reader = csv.reader(StringIO(line)) return reader.next() if __name__ == '__main__': conf = SparkC...
sc = SparkContext(conf=conf) # Base RDD orders = sc.textFile("shopping/orders.csv") # Transform all rows into a parsed Orders object orders = orders.map(split).map(parse) # Transform orders to ensure just 2013 orders are tracked orders = orders.filter(lambda order: order.date.year == 2013...
openstack/heat
heat/engine/resources/template_resource.py
Python
apache-2.0
14,723
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
if not self._parsed_nested: self._parsed_nested = template_format.parse(self.template_data(), self.template_url) return self._parsed_nested def regenerate_info_schema(self, definition):
self._get_resource_info(definition) self._generate_schema() @property def template_url(self): return self._template_name def template_data(self): # we want to have the latest possible template. # 1. look in files # 2. try download # 3. look in the d...
junhuac/MQUIC
depot_tools/win_toolchain/get_toolchain_if_necessary.py
Python
mit
17,887
0.010846
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Downloads and unpacks a toolchain for building on Windows. The contents are matched by sha1 which will be updated when the toolchain...
turn digest.hexdigest() def CalculateToolchainHashes(root): """Calculate the hash of the different toolchains installed in the |root| directory.""" hashes = [] dir_list = [ d for d in os.li
stdir(root) if os.path.isdir(os.path.join(root, d))] for d in dir_list: hashes.append(CalculateHash(root, d)) return hashes def SaveTimestampsAndHash(root, sha1): """Saves timestamps and the final hash to be able to early-out more quickly next time.""" file_list = GetFileList(os.path.join(root, sha1)) ...
leonanu/scripts
file_md5.py
Python
mit
732
0.001366
#!/usr/local/python2.7/bin/python # -*- coding:utf-8 -*- import os import hashlib def dir_walk(base_dir): for parent_dir, dirnames, filenames in os.walk(base_dir): for filename in filenames: yield os.pat
h.join(parent_dir, filename) def file_md5(filename): hash_md5 = hashlib.md5() with open(filename
, 'rb') as f: for chunk in iter(lambda: f.read(4096), b''): hash_md5.update(chunk) return hash_md5.hexdigest() def main(): root_dir = '/usr/local/python2.7' files = dir_walk(root_dir) md5_list = [] for fname in iter(files): md5 = file_md5(fname) md5_list.appen...
tomcounsell/Cobra
apps/public/migrations/0025_commission_customer_confirmed_at.py
Python
gpl-2.0
465
0
#
-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('public', '0024_auto_20141230_2008'), ] operations = [ migrations.AddField( model_name='commission', n...
rue, ), ]
rsalmaso/wagtail
wagtail/tests/testapp/migrations/0039_customdocument_description.py
Python
bsd-3-clause
398
0
# Generated by Django 2.1.2 on 2018-10-24 09:54 from django.db import m
igrations, models class Migration(migrations.Migration): dependencies = [ ("tests", "0038_singletonpageviamaxcount"), ] operations = [ migrations.AddField( model
_name="customdocument", name="description", field=models.TextField(blank=True), ), ]
freedesktop-unofficial-mirror/telepathy__telepathy-salut
tests/twisted/avahi/file-transfer/receive-file-and-sender-disconnect-while-pending.py
Python
lgpl-2.1
979
0.003064
import dbus from saluttest import exec_test from file_transfer_helper import ReceiveFileTest import constants as cs class ReceiveFileAndSenderDisconnectWhilePendingTest(ReceiveFileTest): def accept_file(self): # The sender of the file disconnects self.outbound.transport.loseConnection() s...
signal='FileTransferStateChanged') # We can't accept the transfer now try: self.ft_channel.AcceptFile(cs.SOCKET_ADDRESS_TYPE_UNIX, cs.SOCKET_ACCESS_CONTROL_LOCALHOST, "", 0, byte_arrays=True) except dbus.DBusException, e: assert e.get_dbus_name() == cs.NO...
return True if __name__ == '__main__': test = ReceiveFileAndSenderDisconnectWhilePendingTest() exec_test(test.test)
amplifylitco/asiaq
tests/unit/test_disco_metanetwork.py
Python
bsd-2-clause
12,881
0.003494
"""Tests of disco_metanetwork""" from unittest import TestCase from mock import MagicMock, call, patch from disco_aws_automation.disco_metanetwork import DiscoMetaNetwork from disco_aws_automation.exceptions import EIPConfigError from tests.helpers.patch_disco_aws import TEST_ENV_NAME MOCK_ROUTE_FILTER = {"vpc-id"...
_aws_automation.disco_subnet.DiscoSubnet.__init__', return_value=None) @patch('disco_aws_automation.disco_subnet.DiscoSubnet.add_route_to_gateway', return_value=True) def test_add_route__multi_rt_tbls(self,
mock_add_route, mock_subnet_init): """ Verify a route is added to all subnets' route tables """ self.mock_vpc_conn.get_all_route_tables.return_value = [] self.meta_network.create() mock_gateway_id = 'mock_gateway_id' mock_cidr = '10.101.0.0...
sreecha/grpc
tools/interop_matrix/client_matrix.py
Python
apache-2.0
14,790
0.001487
#!/usr/bin/env python2.7 # Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
0.5')), ('v1.20.0', ReleaseInfo(runtimes=['go1.11'])), ('v1.21.0', ReleaseInfo(runtimes=['go1.11'])), ]), 'java': OrderedDict([ ('v1.0.3', ReleaseInfo(runtimes=
['java_oracle8'], testcases_file='java__v1.0.3')), ('v1.1.2', ReleaseInfo(runtimes=['java_oracle8'], testcases_file='java__v1.0.3')), ('v1.2.0', ReleaseInfo(runtimes=['java_oracle8'], testcases_file='java__v1.0.3')), ('v1.3.1', ReleaseInfo(runtimes=['java_oracle8'], te...
zix99/sshsysmon
sshsysmon/inspectors/system.py
Python
mit
594
0.02862
from lib.plugins import Inspector from lib.
util import TimeSpan """ Description: Gets core system metrics Metrics: uptime - TimeSpan of time the system has been up idle - TimeSpan of the amount of CPU time idle (will be multipled by CPU) """ class System(Inspector): def __init__(self, driver): self._driver = driver def getMetrics(self): uptime = self...
, 'idle' : TimeSpan(float(uptime[1])) } def getName(self): return "System" def create(driver, args): return System(driver, **args)
juanantoniofm/accesible-moodle
fabtools/oracle_jdk.py
Python
gpl-2.0
3,596
0.000556
""" Oracle JDK =========== This module provides tools for installing `Oracle JDK`_ .. _Oracle JDK: http://www.oracle.com/technetwork/java/javase/ """ from __future__ import with_statement import re from fabric.api import run, cd, settings, hide from fabtools.files import is_link from fabtools.system import get_ar...
split('-') release = version.split('_')[0].split('.')[1] update = str(int(version.split('_')[1])) return '%(release)su%(u
pdate)s-%(build)s' % locals()
igor-toga/knob2
knob/tests/fixtures.py
Python
apache-2.0
3,493
0
# Copyright 2016 IBM Corp. # # 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. ...
" # NOTE(mriedem): This is needed for importing from fixtures. from __future__ import absolute_import import logging as std_logging import os import fixtures _TRUE_VALUES = ('True', 'true', '1', 'yes') class NullHandler(std_logging.Handler): """custom default NullHandler to attempt to format the record. U...
nathaliaspatricio/febracev
articles/models.py
Python
gpl-2.0
1,018
0.005917
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from datetime import datetime from tagging.fields import TagField class Article(models.Model): title = models.CharField(max_length=250, verbose_name='Título') slug = models.SlugField(unique_for_date='pub_date', ve...
models.TextField(blank=True, verbose_name='Resumo') body = models.TextField(verbose_name='Texto') pub_date = models.DateTimeField(default=datetime.now, verbose_name='Data de Publicação') enable_comments = models.BooleanField(default=True, verbose_name='Permitir comentários?') tags = TagField(verbose_n
ame='Palavras-chave') class Meta: ordering = ['-pub_date'] verbose_name='Artigo' def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('articles_article_detail', (), { 'object_id': self.id })
vmlaker/wabbit
src/py/record.py
Python
mit
3,650
0.003836
"""Record video frames to disk, and mark the timestamps in database. Parameters: <duration_sec> [<config_file>] """ # Import standard modules. from multiprocessing import Process import datetime as dt import os import sys import time import logging # Import 3rd party modules. import cv2 import mpipe import coils #...
ON < 0: # Insert delay to observe maximum framerate limit. elapsed = (dt.datetime.now() - prev).total_seconds() sleep_time = min_interval - elapsed sleep_time = max(0, sleep_time) time.sleep(sleep_time) prev = dt.datetime.now()
# Take a snapshot, and bail out of loop if the snapshot failed. # The only way I could detect camera disconnect was by # thresholding the length of time to call read() method; # for some reason return value of read() is always True, # even after disconnecting the camera. timer = coils.Timer() ...
raybuhr/python-docs-samples
appengine/ndb/modeling/tests/test_relation_model_models.py
Python
apache-2.0
2,319
0
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
D, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test classes for code snippet for modeling article.""" from appengine.ndb.modeling import relation_model_models as models from google.appengine.ext import ndb from tests import AppEn...
self): """Creates 1 contact and 1 company. Assuming the contact belongs to tmatsuo's addressbook. """ super(ContactTestCase, self).setUp() self.myaddressbook_key = ndb.Key('AddressBook', 'tmatsuo') mary = models.Contact(parent=self.myaddressbook_key, name='Mary') ...
daniel2101/fleosa
sale/__openerp__.py
Python
gpl-3.0
3,479
0.001437
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# License, or (at your option) any later version. # # This program is distributed in the hope that it will be usef
ul, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <...
bootcamptropa/django
categories/models.py
Python
mit
362
0.002762
from django.db import models class Category(models.Model): name = models.CharField(max_length=30) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __u
nicode__(self): return self.name def __str__(self): return self
.name
icelic/eks
py/eks/core/assets.py
Python
gpl-3.0
282
0
from django_assets import register from django_eks.assets import actualis_css, actualis_js, actualis_js_min from django.conf import settings register('core_css', actualis_css) if settings.DEBUG: register('core_js', actualis_js) else: register('core_js', actualis_js_min)
TNT-Samuel/Coding-Projects
Python Tests/List Assigner/inefficient_assigner.py
Python
gpl-3.0
1,023
0.055718
import random, time, os def Validate(lista,listb): Valid = True if len(lista) == len(listb): for listindex in range(len(lista)): if lista[listindex] == listb[listindex]:
Valid = False else: Valid = False re
turn(Valid) os.system("color c") namelist = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] assignvalid = False while not assignvalid or True: symbollist = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y",...
M4rtinK/modrana
core/signal.py
Python
gpl-3.0
1,757
0.010814
# -*- coding: utf-8 -*- # modRana - signal object ## based on: http://code.activestate.com/recipes/576477/ #Author: Thiago Marcos P. Santos from weakref import WeakValueDictionary class Signal(object): def __init__(self): self.__slots = WeakValueDictionary() def __call__(self, *args, **kargs): ...
self.__value # # #class View(object): # def __init__(self, model): # self.model = model # model.changed.connect(self.model_changed) # # def model_changed(self): # print "New value:", self.model.get_value() #
# #model = Model(10) #view1 = View(model) #view2 = View(model) #view3 = View(model) # #model.set_value(20) # #del view1 #model.set_value(30) # #model.changed.clear() #model.set_value(40) ### end of http://code.activ...
gjcoombes/banks
banks/gis/tie.py
Python
mit
5,232
0.011277
# -*- coding: utf-8 -*- """ Module: tie.py Created on Mon Jan 27 17:12:19 2014 @author: gav Description: Utilities for converting to and from ASA's tie polygon format The central common format will be geojson records suitable for the shapely/fiona gis stack. """ ### Imports from __future__ import print_function from ...
with open(fp) as f: lines = f.readlines() while lines: header = lines[:HEADER_LINES] del lines[:HEADER_LINES] record = (header) vs = lines[:record['n_verts']] del lines[:record['n_verts']] record['verts'] = tie_verts(vs) records.append(record) ...
s def verts(lines): verts_ls = [] for line in lines: verts_ls.append([float(i) for i in line.split()]) return verts_ls def tie_record(tie_dict): """Return a complete tie record""" d = tie_dict color_width_height = "{} {} {}".format(*[int(i) for i in d['color_width_height']]) verts ...
TeamLab/Gachon_CS50_OR_KMOOC
gurobi_quiz/product_mix/submit.py
Python
mit
8,554
0.013208
# Author: Sungchul Choi, sc82.choi at gachon.ac.kr # Version: 0.1 # Description # 가천대학교 프로그래밍 입문 시간에 활용되는 "숙제 자동 채점 프로그램"의 Client 프로그램입니다. # # HUMAN KNOWLEDGE BELONGS TO THE WORLD. -- From the movie "Antitrust" # Copyright (C) 2015 TeamLab@Gachon University import argparse import pickle import os import types import r...
# Check Argument # To download an assignment template file : -get <ASSIGNMENT_NAME> # To submit an assignment template file : -submit <ASSIGNMENT_NAME> # [actionType, assignment_name] = checkArguements(argumentValue) actionType = "submit" assignment_name = ASSIGNMENT_NAME # Check User Logi...
_name) # Check Your Access Token [access_token, username] = getToken() # Get New Access Token if access_token == None: while (access_token == None): [username, login_password] = getLoginInformation() access_token = getAccessTokenFromServer(username, login_password) ...
Mezgrman/mezgrmanDE
staticpages/middleware.py
Python
agpl-3.0
4,812
0.014547
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from mezgrman.utils.classes import ExtendedTemplateResponse from django.template import RequestContext, Template from .models import StaticPage, StaticPageGroup from django.conf import settings from django.db.models import Q impo...
ponse # We have at least one potential page, now filter by language lang_matching_pages = [page for page in potential_pages if page.lang == request.LANGUAGE_CODE] if not lang_matching_pages: # No page found in the desired language, fall back to the default language ...
use what's available lang_matching_pages = potential_pages # Now just take the highest ranked page out of the remaining candidates page = sorted(lang_matching_pages, key = lambda p: p.rank, reverse = True)[0] # Okay, we have our page. Now serve it ...
crcro/librenms
poller-wrapper.py
Python
gpl-3.0
14,267
0.003715
#! /usr/bin/env python3 """ poller-wrapper A small tool which wraps around the poller and tries to guide the polling process with a more modern approach with a Queue and workers Authors: Job Snijders <job.snijders@atrato.com> Orsiris de Jong <contact@netpower.fr>...
er.device.%s.%s' % (device_id, time_tag)) is None: if distpoll: result = memc.add('poller.device.%s.%s' % (device_id, time_tag), config['distributed_poller_name'], step) if not result: print("This device (%s) appears to be...
done() continue if not memc_alive() and IsNode: print("Lost Memcached, Not polling Device %s as Node. Master will poll it." % device_id) poll_queue.task_done() continue # EOC5 try: sta...
raryosu/djangoblog
raryosublog/blog/admin.py
Python
mit
263
0.015209
from django.contrib import admin from blog.models import blogdata # Register your models here. class blogdataAdmin(admin.ModelAdmi
n): list_display = ('id', 'title', 'date',) list_displ
ay_links = ('id', 'title',) admin.site.register(blogdata, blogdataAdmin)
itplanes/uproxy
removekey.py
Python
apache-2.0
479
0.004175
# Remove key from Chrome manifest # # Run with: # python removekey.py import json manifest_files = [ 'build/dist/chrome/app/manifest.json', 'build/dist/chrome/extension/manifest.json' ] for filename in manifest_files: with
open(filename) as manifest: manifest_data = js
on.load(manifest) del manifest_data['key'] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2)
fbradyirl/home-assistant
homeassistant/components/foscam/camera.py
Python
apache-2.0
3,754
0.000799
"""This component provides basic support for Foscam IP cameras.""" import logging import voluptuous as vol from homeassistant.components.camera import Camera, PLATFORM_SCHEMA, SUPPORT_STREAM from homeassistant.const import CONF_NAME, CONF_USERNAME, CONF_PASSWORD, CONF_PORT from homeassistant.helpers import config_val...
atus = ret == FOSCAM_COMM_ERROR except TypeError: _LOGGER.debug("Communication problem") self._motion_status = False def disable_motion_detection(self): """Disable motion detection.""" try: ret = self._foscam_session.disable_motion_detection() ...
_motion_status = False @property def name(self): """Return the name of this camera.""" return self._name
ESSolutions/ESSArch_Core
ESSArch_Core/tags/migrations/0021_tagversiontype_archive_type.py
Python
gpl-3.0
452
0.002212
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-03-27 10:04 from django.db import migrations, models class Migration(migra
tions.Migration): dependencies = [ ('tags', '0020_auto_20190326_1547'), ] operations = [ migrations.AddField( model_name='tagversiontype', name='archive_type', field=models.
BooleanField(default=False, verbose_name='archive type'), ), ]
cryptapus/electrum
electrum/gui/kivy/uix/dialogs/settings.py
Python
mit
9,722
0.003086
from kivy.app import App from kivy.factory import Factory from kivy.properties import ObjectProperty from kivy.lang import Builder from electrum.util import base_units_list from electrum.i18n import languages from electrum.gui.kivy.i18n import _ from electrum.plugin import run_hook from electrum import coinchooser fr...
assword, self) CardSeparator SettingsItem: bu: app.base_unit title: _('Denomination') + ': ' + self.bu description: _("Base unit for Bitcoin amounts.") action: partial(root.unit_dialog, self) ...
status: root.fx_status() title: _('Fiat Currency') + ': ' + self.status description: _("Display amounts in fiat currency.") action: partial(root.fx_dialog, self) CardSeparator SettingsItem: s...
ProjectSWGCore/NGECore2
scripts/object/tangible/painting/painting_trandoshan_m.py
Python
lgpl-3.0
63
0.111111
import sys def setup(core, ob
ject): r
eturn #Warriors Honor
Mandrathax/Entropy
Scripts/french_texts_dl.py
Python
mit
2,276
0.010984
# Retrieves all text files from CNAM ABU (see license here : http://abu.cnam.fr/cgi-bin/donner_licence) for further treatment import urllib.request import os from bs4 import BeautifulSoup, SoupStrainer # Proxy handling proxies = {'http':''} opnr = urllib.request.build_opener(urllib.request.ProxyHandler(proxies)) u...
HIER", regroups lines in packets of ~15000 chars and stores in text file for i in range(len(lines)): if "DEBUT DU FICHIER" in lines[i] or "FIN DU FICHIER" in lines[i]:
read = not(read) l = len(buffstring) if read: if l>15000: f=open(dir+'/'+str(cnt)+'.txt','w',encoding='utf8') f.write(buffstring) ...
alxgu/ansible
lib/ansible/plugins/httpapi/fortimanager.py
Python
gpl-3.0
13,169
0.003113
# Copyright (c) 2018 Fortinet and/or its affiliates. # # 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 License, or # (at your option) any late...
# If Login worked, then inspect the FortiManager for Workspace Mode, and it's system information. self.inspect_fmgr() return else: raise FMGBaseException(msg="Unknown error while logging in...connection was lost during l
ogin operation...." " Exiting") def inspect_fmgr(self): # CHECK FOR WORKSPACE MODE TO SEE IF WE HAVE TO ENABLE ADOM LOCKS self.check_mode() # CHECK FOR SYSTEM STATUS -- SHOULD RETURN 0 status = self.get_system_status() if status[0] == ...
ActiveState/code
recipes/Python/578618_Droids__a_text_adventure_/recipe-578618.py
Python
mit
13,762
0.036041
#droids.py import time import random from random import randint print('\n' * 100) print('\n\n[-Droids : by jay : type help-]') print('\n\n\n------------------------') print(' DROIDS') print('------------------------') print('\n10.03.2245 : cytek inc.') time.sleep(1) print('\nCTRL866 Re-Boot Sequence....') time....
ventory) elif cmd == '4': if 'laser' in inventory: print('\n- DECK 4 - DROID HANGAR LOCKED -') time.sleep(2) start(inventory) else: droid_hangar(inventory) elif cmd == '5': shuttle_control(inventory) elif cmd == '6': if 'motion tracker' in inventory:
print('\n- DECK 6 - OBSERVATION LOCKED -') time.sleep(2) start(inventory) else: observation(inventory) def maintenance(inventory): print('\n----------') print('\nDroid mobile..') time.sleep(1) print('....') time.sleep(1) print('''\nThis is the maintenance deck and it appears deserted. You can see a...
kidaa/pySDC
examples/advection_2d_explicit/HookClass.py
Python
bsd-2-clause
1,879
0.025546
from __future__ import division from pySDC.Hooks import hooks from pySDC.Stats import stats import matplotlib.pyplot as plt import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter class p...
er = 0 def dump_step(self,status): """ Overwrite standard dump per step Args: status: status object per step """ super(plot_solution,self).dump_step(status) if False: yplot = self.level.uend.values xx = self.level.prob.xc
yy = self.level.prob.yc self.fig.clear() plt.plot( xx[:,0], yplot[0,:,0]) plt.ylim([-1.0, 1.0]) plt.show(block=False) plt.pause(0.00001) if True: yplot = self.level.uend.values xx = self.level.prob.xc ...
vivhou/Python-coursework-files
final project data analysis/webscraping scripts/private_school_tuition_data.py
Python
artistic-2.0
2,969
0.023914
import requests import math import re from bs4 import BeautifulSoup ROOT_URL = "http://nces.ed.gov/collegenavigator" INDEX_URL = ROOT_URL + "?s=all&l=93&ct=2&ic=1&an=5&ax=50" PAGINATION_DIV_ID = "ctl00_cphCollegeNavBody_ucResultsMain_divMsg" def get_num_pages(pagination): """Returns the total number of pages given p...
print("Parsing colleges page: " + str(i)) response = requests.get(INDEX_URL + "&pg
=" + str(i)) soup = BeautifulSoup(response.text, "html.parser") # There is only one "resultsTable" in the HTML that # contains the list of college links and information table = soup.find("table", attrs={"class": "resultsTable"}) for link in table.findChildren(href=is_college_link): college['name'...
windelbouwman/ppci-mirror
ppci/lang/c/parser.py
Python
bsd-2-clause
44,157
0
""" C parsing logic. The C parsing is implemented in a recursive descent parser. The following parts can be distinguished: - Declaration parsing: parsing types and declarations - Statement parsing: dealing with the C statements, like for, if, etc.. - Expression parsing: parsing the C expressions. Sources of inspirat...
self.parse_declarations() return self.semantics.finish_compilation_unit() # Declarations part: def parse_declarations(self): """ Parse normal declarations """ decl_spec = self.parse_decl_specifiers() # TODO: perhaps not parse function
s here? if not self.has_consumed(";"): self.parse_decl_group(decl_spec) def parse_decl_specifiers(self, allow_storage_class=True): """ Parse declaration specifiers. At the end we know type, storage class and qualifiers. Gathers storage classes: - typedef ...
hankjin/monitor
fetion.py
Python
gpl-2.0
1,221
0.023458
#coding:utf-8 #调用飞信 import urllib2 import urllib class Fetion: msisdn = '' passwd = '' baseurl = 'http://quanapi.sinaapp.com/fetion.php' #设置登陆用户 def setuser(self,msisdn,passwd): self.msisdn = msisdn self.passwd = passwd #发送短信 def s
endsms(self,recmsisdn,content): cod = 1 if self.msisdn == '' : cod = 0 return 'msisdn is null' if self.passwd == '' : cod = 0 return 'passwd is null' if recmsisdn == '' : cod = 0 return '
recmsisdn is null' if content == '': cod = 0 return 'content is null' if cod == 1 : smsurl = self.baseurl + '?u=' + self.msisdn + '&p=' + self.passwd + '&to='+recmsisdn +'&m=' + content print smsurl res = urllib2.urlopen(smsurl).read() ...
kiwicampus/kiwix
server.py
Python
mit
2,463
0.002842
import socket from PIL import Image import io import os def string_to_byte(hex_input): return bytearray.fromhex(hex_input) def serve(): host = "" port = 5001 my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_socket.bind((host, port)) my_socket.listen(1) conn, address = ...
# Read until a colon is found. This signals the image size segment while not ":" in decoded_data: data = conn.recv(1)
decoded_data = data.decode() decoded_data_buffer += decoded_data print("Config received: ") print(decoded_data_buffer) expected_size_str = decoded_data_buffer.replace("config", "").replace(",", "").replace(":", "") expected_size = int(expected_size_str) print("Exp...
CalthorpeAnalytics/urbanfootprint
footprint/main/models/presentation/style_attribute.py
Python
gpl-3.0
3,695
0.002165
# coding=utf-8 # UrbanFootprint v1.5 # Copyright (C) 2017 Calthorpe Analytics # # This file is part of UrbanFootprint version 1.5 # # UrbanFootprint is distributed under the terms of the GNU General # Public License version 3, as published by the Free Software Foundation. This # code is distributed WITHOUT ANY WARRANT...
marker_line_width=None, **kwargs): self['polygon-fill'] = polygon_fill self['polygon-opacity'] = polygon_opacity self['line-color'] = line_color self['line-width'] = line_width self['line-opacity'] = line_opacity self['marker-fill'] = marker_fill ...
r'] = marker_line_color self['marker-line-width'] = marker_line_width # Support arbitrary other styles for key, value in kwargs.items(): self[key] = value def __getattr__(self, attr): return self[attr] if attr in self else super(Style, self).__getattr__(self, attr) cla...
krattai/ss-middleware
connector/connector/tests/test_mapper.py
Python
bsd-2-clause
25,592
0.000039
# -*- coding: utf-8 -*- import unittest import mock import openerp.tests.common as common from openerp.addons.connector.unit.mapper import ( Mapper, ImportMapper, ExportMapper, ImportMapChild, MappingDefinition, changed_by, only_create, convert, follow_m2o_relations, m2o_to_bac...
gDefinition(changed_by=set([]), only_create=True) city_def = MappingDefinition(changed_by=set(('street',)), only_create=False) email_def = MappingDefinition(changed_by=set([]), only_create=F...
_def = MappingDefinition(changed_by=set([]), only_create=True) self.assertEqual(ThirdMapper._map_methods['name'], name_def) self.assertEqual(ThirdMapper._map_methods['street'], street_def) self.assertEqual(ThirdMapper._map_methods['city'], city_def) se...
ff94315/hiwifi-openwrt-HC5661-HC5761
staging_dir/host/lib64/scons-2.1.0/SCons/Platform/hpux.py
Python
gpl-2.0
1,777
0.002814
"""engine.SCons.Platform.hpux Platform-specific initialization for HP-UX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 200...
f the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/hpux.py 5357 2011/09/09 21:31:03 bdeegan" ...
aricchen/openHR
openerp/addons/base/res/res_currency.py
Python
agpl-3.0
12,118
0.006024
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
currency's precision.. An amount is considered lower/greater than another amount if their rounded value is different. This is not the same as having a non-zero difference! For example 1.432 and 1.431 are equal at 2 digits precision, so this method would return 0. ...
ld be considered zero at 2 digits precision. :param browse_record currency: currency for which we are rounding :param float amount1: first amount to compare :param float amount2: second amount to compare :return: (resp.) -1, 0 or 1, if ``amount1`` is (resp.) lower than, ...
webcomics/dosage
tests/test_helpers.py
Python
mit
894
0.003356
# SPDX-License-Identifier: MIT # Copyright (C) 2019 Tobias Gruetzmacher from dosagelib.helpers import joinPathPartsNamer, queryNamer class TestNamer(object): """ Tests for comic namer. """ def test_queryNamer(self): testurl = 'http://FOO?page=result&page2=result2' assert queryNamer('p...
'result' assert queryNamer('page2', True)(self, "", testurl) == 'result2' def test_joinPathPartsNamer(self):
imgurl = 'https://HOST/wp-content/uploads/2019/02/tennis5wp-1.png' pageurl = 'https://HOST/2019/03/11/12450/' assert joinPathPartsNamer((0, 1, 2))(self, imgurl, pageurl) == '2019_03_11_tennis5wp-1.png' assert joinPathPartsNamer((0, 1, 2), (-1,), '-')(self, imgurl, pageurl) == '2019-03-11-tennis5...
aronsky/home-assistant
homeassistant/components/folder/__init__.py
Python
apache-2.0
28
0
""
"The folder component."""
lsj1292/Abacus
tests/core/plugins/expected/apps.py
Python
mit
169
0
from biohub.core.plugins import PluginConfig class TestC
onfig(PluginConfig): name = 'tests.c
ore.plugins.test' title = '' author = '' description = ''