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
christianmemije/kolibri
kolibri/core/webpack/test/test_webpack_tags.py
Python
mit
880
0.002273
from __future__ import absolute_import, print_function, unicode_literals from django.template import Template, Context from django.test.testcases import TestCase from .base import TestHook class KolibriTagNavigationTestCase(TestCase): def setUp(self): super(KolibriTagNavigationTestCase, self).setUp
()
self.test_hook = TestHook() def test_frontend_tag(self): self.assertIn( "non_default_frontend", self.test_hook.render_to_page_load_sync_html() ) def test_frontend_tag_in_template(self): t = Template( """{% load webpack_tags %}\n{% webpack_asset 'no...
snogaraleal/adjax
adjax/tests/test_templatetags.py
Python
mit
1,451
0
from django.test import TestCase try: from django.contrib.staticfiles.templatetags.staticfiles import static except ImportError: from django.templatetags.static import static try: from django.core.urlresolvers import reverse except ImportError: from django.urls import reverse from ..templatetags.adja...
adjax_scripts) class TemplateTagsTestCase(TestCase): def test_get_script_tag(self): """ Test script tag HTML. """ source = 'https://cdn.com/source.js' expected_html =
('<script type="text/javascript" ' 'src="{}"></script>').format(source) self.assertEqual(get_script_tag(source), expected_html) def test_get_script_tags(self): """ Test script tag HTML joining. """ a_html = get_script_tag('a') b_html = get_script_ta...
Zlash65/erpnext
erpnext/accounts/general_ledger.py
Python
gpl-3.0
9,852
0.025376
# 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, erpnext from frappe.utils import flt, cstr, cint from frappe import _ from frappe.model.meta import get_field_precision from erpnext.acco...
ap[0].voucher_type=="Journal Entry": aii_accounts = [d[0] for d in frappe.db.sql("""select name from
tabAccount where account_type = 'Stock' and is_group=0""")] for entry in gl_map: if entry.account in aii_accounts: frappe.throw(_("Account: {0} can only be updated via Stock Transactions") .format(entry.account), StockAccountInvalidTransaction) def validate_cwip_accounts(gl_map): if not cint(fr...
abuibrahim/nixops
nixops/resources/azure_reserved_ip_address.py
Python
lgpl-3.0
6,605
0.007116
# -*- coding: utf-8 -*- # Automatic provisioning of Azure reserved IP addresses. import os import azure import time from nixops.util import attr_property from nixops.azure_common import ResourceDefinition, ResourceState, normalize_location from azure.mgmt.network import * class AzureReservedIPAddressDefinition(Res...
resource_group = attr_property("azure.resourceGroup", None) location = attr_property("azure.location", None) tags = attr_property("azure.tags", {}, 'json') idle_timeout = attr_property("azure.idleTimeout", None, int) domain_name_label = attr_property("azure.domainNameLabel", None) allocation_met...
one) fqdn = attr_property("azure.fqdn", None) reverse_fqdn = attr_property("azure.reverseFqdn", None) ip_address = attr_property("azure.ipAddress", None) @classmethod def get_type(cls): return "azure-reserved-ip-address" def show_type(self): s = super(AzureReservedIPAddressSta...
amwelch/a10sdk-python
a10sdk/core/configure/configure.py
Python
apache-2.0
818
0.012225
from a10sdk.common.A10BaseClass import A10BaseClass class Configure(A10BaseClass): """Class Description:: Configure sync Commands. Class configure supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param DeviceProxy: The d...
.ERROR_MSG = "" self.required=[] self.b_key = "configure" self.a10_url="/axapi/v3/configure" self.DeviceProxy = "
" self.sync = {} for keys, value in kwargs.items(): setattr(self,keys, value)
opendatagroup/hadrian
titus/titus/lib/array.py
Python
apache-2.0
49,343
0.008735
#!/usr/bin/env python # Copyright (C) 2014 Open Data ("Open Data" refers to # one or more of the following companies: Open Data Partners LLC, # Open Data Research LLC, or Open Data Capital LLC.) # # This file is part of Hadrian. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this...
son from titus.fcn import Fcn from titus.fcn import LibFcn from titus.signature import Sig from titus.signature import Sigs from
titus.datatype import * from titus.errors import * from titus.util import callfcn, negativeIndex, startEnd from titus.lib.core import INT_MIN_VALUE from titus.lib.core import INT_MAX_VALUE from titus.lib.core import LONG_MIN_VALUE from titus.lib.core import LONG_MAX_VALUE import titus.P as P provides = {} def provide(...
jim-easterbrook/pyctools-demo
src/scripts/temporal_alias/stage_2.py
Python
gpl-3.0
2,808
0.005342
#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { ...
ZonePlateGenerator', 'config': "{'kx': 0
.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " ...
yuce/pyswip
tests/test_prolog.py
Python
mit
4,048
0.001977
# -*- coding: utf-8 -*- # pyswip -- Python SWI-Prolog bridge # Copyright (c) 2007-2012 Yüce Tekol # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without ...
on for _ in p.query(somequery): pass for _ in p.query(otherquery): pass with self.assertRaises(pl.NestedQueryError): for q in p.query(somequery): for j in p.query(otherquery): # This should throw an error, because I opened ...
(a,b),h(a,b,c)])') self.assertEqual([{"L": [u"g(a, b)", u"h(a, b, c)"]}], list(p.query("f(L)"))) p.retract("f([g(a,b),h(a,b,c)])") def test_prolog_functor_in_functor(self): p = pl.Prolog() p.assertz("f([g([h(a,1), h(b,1)])])") self.assertEqual([{'G': [u"g(['h(a, 1)', 'h(b, 1...
google-research/language
language/conpono/create_pretrain_data/books_preproc_pipeline.py
Python
apache-2.0
8,949
0.00894
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
ence length.") flags.DEFINE_float("test_size", 0.1, "Size of test set by factor of total dataset.") flags.DEFINE_float("dev_size", 0.1, "Size of dev set by factor of total dataset.") flags.DEFINE_int
eger("random_seed", 12345, "A random seed") flags.DEFINE_bool( "do_lower_case", True, "Whether to lower case the input text. Should be True for uncased " "models and False for cased models.") flags.DEFINE_enum( "format", FORMAT_PARAGRAPH, [FORMAT_BINARY, FORMAT_PARAGRAPH], "Build a dataset of either...
fhdk/pacman-mirrors
pacman_mirrors/translation/i18n.py
Python
gpl-3.0
1,832
0
#!/usr/bin/env python # # This file is part of pacman-mirrors. # # pacman-mirrors is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # p...
LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo APP_NAME = "pacman_mirrors" APP_DIR = os.path.join(sys.prefix, "share") LOCALE_DIR = os.path.join(APP_DIR, "locale") CODESET = "utf-8" # Now we need to choose the language. We will provide a list, and gettext # will use the first translation available in the list LANGUA...
user_locale: LANGUAGES += user_locale except ValueError: pass LANGUAGES += os.environ.get("LANGUAGE", "").split(":") LANGUAGES += ["en_US"] # Lets tell those details to gettext # (nothing to change here for you) gettext.install(True) gettext.bindtextdomain(APP_NAME, LOCALE_DIR) gettext.bind_textdomain_cod...
megaserg/pants
tests/python/pants_test/backend/codegen/tasks/test_apache_thrift_gen.py
Python
apache-2.0
2,555
0.003914
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from textwrap import...
pacheThriftGen def setUp(self): super(ApacheThriftGenTest, self).setUp() def generat
e_single_thrift_target(self, java_thrift_library): context = self.context(target_roots=[java_thrift_library]) apache_thrift_gen = self.create_task(context) apache_thrift_gen.execute() def is_synthetic_java_library(target): return isinstance(target, JavaLibrary) and target.is_synthetic synthet...
morelab/weblabdeusto
server/src/test/unit/weblab/lab/test_status_handler.py
Python
bsd-2-clause
3,023
0.000992
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
import test.unit.weblab.lab.fake_socket as FakeSocket class AbstractLightweightIsUpAndRunningHandlerTestCase(unittest.TestCase): def test_not_implemented(self): self.assertRaises( TypeError, AbstractLightweightIsUpAndRunningHandler ) class WebcamIsUpAndRunningHandlerTest...
t() self.handler._urllib2 = FakeUrllib2 def test_run_ok(self): FakeUrllib2.expected_action = FakeUrllib2.HTTP_OK self.handler.run() def test_run_exception_bad_response(self): FakeUrllib2.expected_action = FakeUrllib2.HTTP_URL_ERROR self.assertRaises( Laborat...
benwhalley/statpipe
setup.py
Python
mit
448
0
from dis
tutils.core import setup setup( name='Statpipe', version='0.1.9', author='Ben Whalley', author_email='benwhalley@gmail.com', packages=['statpipe'], scripts=['bin/statpipe', 'bin/statpipe_image'], url='https://github.com/benwhalley/statpipe', license='LICENSE.txt', description='Pipe ...
, )
geopython/QGIS
python/plugins/processing/algs/grass7/ext/r_li_renyi_ascii.py
Python
gpl-2.0
1,538
0
# -*- coding: utf-8 -*- """ *************************************************************************** r_li_renyi_ascii.py ------------------- Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr ********************...
******************************* """ __author__ = 'Médéric Ribreux' __date__ = 'February 2016' __copyright__ = '(C
) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from .r_li import checkMovingWindow, configFile, moveOutputTxtFile def checkParameterValuesBeforeExecuting(alg, parameters, context): return checkMovingWindow(alg, parameters, context, True)...
cuauv/software
mission/missions/old/2017/aslam_buoys.py
Python
bsd-3-clause
7,476
0.0103
from mission.constants.config import PIPE_SEARCH_DEPTH from mission.framework.combinators import * from mission.framework.primitive import * from mission.framework.position import * from mission.framework.movement import * from mission.framework.task import * from mission.framework.timing import * from mission.framewor...
onfig import * from mission.missions.ozer_common import SequentialSuccess, Conditional, Retry from mission.opt_aux.aux import * from mission.missions.buoys import Scuttle import aslam import shm, time, math import numpy as n from auv_math.math_utils impor
t rotate class GoToPipe(Task): """ Move to and align with the pipe after buoys """ def on_first_run(self, *args, **kwargs): pipe_results = shm.buoys_pipe_results.get() self.task = Sequential( Log('Returning to pipe position'), GoToPosition( pipe_r...
icflix/nagios
nagios_receiver_config.py
Python
bsd-3-clause
265
0
"""Nagios Receiver config.""" SHARED_KEY = '' CFG_DIR =
'/var/lib/nagios/remoteconfigs/' RESULTS_DIR = '/var/lib/nagios/remoteresults/' COMPONENTS = { 'configs': 'config', 'results': 'result', } # Maximum Content-Length
1MB ? CONTENT_LENGTH_MAX = 1048576
MrZigler/UnderdogMilitia
landplots.py
Python
gpl-3.0
1,652
0.02724
import time import random BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) PURPLE = (255, 0, 255) BROWN = (160, 82, 45) class Landplots(): def __init__(self, owner, umtype, locationregion, jurisdiction, umvalue, inventory): self.owner = owner ...
def __init__(self, owner, umtype, locationregion, jurisdiction, umvalue, inventory): Landplots.__init__(self, owner, umtype, locationregion, jurisdiction, umvalue, inventory) def producefood(self):
self.umvalue + self.jurisdiction #orchard1 = Farm('Platinum Falcon', 5, 7, 42, 37, {})
ziggi/pawn-sublime-language
OpenWikiOnString.py
Python
mit
233
0.021459
import sublime, sublime_plugin import webbrowser class OpenW
ikiOnString(sublime_plugin.TextCommand): def run(self,
edit): query = self.view.substr(self.view.sel()[0]) webbrowser.open_new("http://wiki.sa-mp.com/wiki/" + query)
underlost/Replica
replica/contrib/blip/dashboard/views.py
Python
mit
5,663
0.007946
from __future__ import absolute_import import logging from django.shortcuts import render_to_response, render, get_object_or_404, redirect from django
.template import RequestContext from django.c
ontrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.views.generic.list import ListView from replica.contrib.blip.models import Timeline, Blip from replica.contrib.blip.forms import Timelin...
thombashi/typepy
typepy/checker/_datetime.py
Python
mit
1,159
0.000863
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from datetime import date, datetime from ._checker import CheckerFactory, TypeCheckerBase, TypeCheckerDelegator from ._common import isstring class DateTimeTypeCheckerStrictLevel0(TypeCheckerBase): def is_instance(self): return isin...
ory = CheckerFactory( checker_mapping={ 0: DateTimeTypeCheckerStrictLevel0, 1: DateTimeTypeCheckerStrictLevel1, 2: DateTimeTypeCheckerStrictLevel2, } ) class DateTimeTypeC
hecker(TypeCheckerDelegator): def __init__(self, value, strict_level): super().__init__(value=value, checker_factory=_factory, strict_level=strict_level)
synox/telewall
telewall/telewall/__init__.py
Python
gpl-3.0
290
0.003448
""" Telewall. This application connects to asterisk and provides Statis-Apps. It has a user interface using a button, display and led. It also provides a web interface. The Application should be run using python 2
.7, because ARI (Asterisk REST Interface) does not support pytho
n 3. """
unkyulee/elastic-cms
src/web/__init__.py
Python
mit
2,565
0.011306
# Initialize web application and setup routing from flask import Flask, request, session, render_template, send_from_directory app = Flask(__name__) # Define the WSGI application object # very first run will not have config.py try: app.config.from_object('config') except: pass import os import web.util.jinja # Initia...
nticated() if req_auth and not authenticated: # build payload for the navigation navigation = mod.build_payload(app.config, request, navigation) navigation['operation'] = None import web.modules.auth.control as default return default.get(navigation) ...
# build payload for the navigation navigation = mod.build_payload(app.config, request, navigation) # check for rev_proxy rev_proxy_rule = rev.is_reverse_proxy(app.config.get("HOST"), request.path) if rev_proxy_rule: return rev.rev_proxy(app.config.get("HOST"), request.path,...
Octane70/BluePad
bluepad/utils.py
Python
mit
4,859
0.00638
from __future__ import absolute_import, print_function, unicode_literals import dbus import time import sys SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapt
er1" DEVICE_INTERFACE = SERVICE_NAME + ".Device1" PROFILE_MANAGER = SERVICE_NAME + ".ProfileManager1" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object(SERVICE_NAME, "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(patt...
rn=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.items(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or...
Azure/azure-sdk-for-python
sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2-beta/sample_build_model.py
Python
mit
2,477
0.004037
# 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. # -------------------------------------------------------------------------- """ FILE: sample_build_model.py DESCRIPTION: This sample demonstrates how to build a model. ...
e structure can be found here: https://aka.ms/azsdk/formrecognizer/buildtrainingset USAGE: python sample_build_model.py Set the environment variables with your own values before running the sample: 1) AZURE_FORM_RECOGNIZER_ENDPOINT - the endpoint to your Cognitive Services resource. 2) AZURE_FORM_...
robcarver17/systematictradingexamples
plots_for_perhaps/plotcontango.py
Python
gpl-2.0
3,346
0.01853
import pandas as pd import datetime as dt import Image from random import gauss import numpy as np from matplotlib.pyplot import plot, show, xticks, xlabel, ylabel, legend, yscale, title, savefig, rcParams, figure, hist, scatter import matplotlib.pylab as plt from itertools import cycle import pickle import pandas as ...
= cycle(lines) import Quandl def get_quandl(code): QUANDLDICT=dict(GOLD="COM/WLD_GOLD", CORN="COM/PMAIZMT_USD", CRUDE_W="C
OM/WLD_CRUDE_WTI") authtoken='qWXuZcdwzwQ2GJQ88sNb' quandldef=QUANDLDICT[code] print quandldef data = Quandl.get(quandldef, authtoken=authtoken) data.columns=["value"] return data.iloc[:,0] def pd_readcsv(filename, date_index_name="DATETIME"): """ Reads a pandas data frame, with t...
alexellis/docker-arm
images/armhf/python2-envirophat.dev/pressure/pressure.py
Python
gpl-3.0
277
0.032491
#!/usr/
bin/env python import sys import time from envirophat import light, weather, motion, analog def write(): try: p = round(weather.pressure(),2) c = light.light() print('{"light": '+str(c)+', "pressure": '+str(
p)+' }') except KeyboardInterrupt: pass write()
jimmysong/bitcoin
test/functional/test_framework/mininode.py
Python
mit
55,063
0.001925
#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Bitcoin P2P ...
et_ntoa(f.read(4)) self.port = struct.unpack(">H", f.read(2))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nServices) r += self.pchReserved r +=
socket.inet_aton(self.ip) r += struct.pack(">H", self.port) return r def __repr__(self): return "CAddress(nServices=%i ip=%s port=%i)" % (self.nServices, self.ip, self.port) MSG_WITNESS_FLAG = 1<<30 class CInv(object): typemap =...
aYukiSekiguchi/ACCESS-Chromium
native_client_sdk/src/build_tools/make_nacl_tools.py
Python
bsd-3-clause
7,703
0.008049
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Build NaCl tools (e.g. sel_ldr and ncval) at a given revision.""" import build_utils import optparse import os import shutil im...
Print('ERROR: --lib must either be newlib or glibc') return 1 return Bu
ildNaClTools(options) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
odoomrp/odoomrp-wip
product_pricelist_rules/models/product.py
Python
agpl-3.0
3,039
0
# -*- coding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free
Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be
useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see htt...
odoousers2014/odoo_addons-2
clv_frame/clv_tag/clv_tag.py
Python
agpl-3.0
2,011
0.013426
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
# # 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 <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields class clv_frame(models.Model): ...
getnikola/nikola
nikola/plugins/task/posts.py
Python
mit
5,120
0.002149
# -*- coding: utf-8 -*- # Copyright © 2012-2022 Roberto Alsina and others. # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including without limitation # the rights t...
bstantial portions of # 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...
TY, 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. """Build HTML fragments from metadata and text.""" import os from copy import copy from nikola.plugin_categories import Task from nikola import utils de...
ShipleyCollege/ViPteam1
ExtractAndAnalyzeCode/ProcessBranch.py
Python
gpl-3.0
1,199
0.035029
from Node import * from Pin import * from Utilities import getQuotedString ### # FUNCTION : Handle Branch nodes ### def processBranch(lines, buildMode, nodeNumber, OUTPUT_FOLDER): node = Node("Branch", buildMode) inObject = False pinName = "" pinType = "" pinSide = "" for line in lines: line =
line.strip(" ") if inObject: if line.startswith("PinName="): print("-Name : " + line) pinName = getQuotedString(line) if line.startswith("PinType="): print("-Type : " + line) pinType = getQuotedString(line) if line.startswith("Direction=EGPD_Output"): print("-Direction : " + line) pi...
ndly name : " + line) pinName = getQuotedString(line) if line.startswith("Begin Object Name="): inObject = True pinName = "" PinType = "" pinSide = "Left" print("In Object") if line.startswith("End Object"): inObject = False if pinSide != "": pin = Pin(pinName, pinType) node.addP...
Glasgow2015/team-10
env/lib/python2.7/site-packages/djangocms_text_ckeditor/utils.py
Python
apache-2.0
3,506
0.001141
# -*- coding: utf-8 -*- import os import re from cms.models import CMSPlugin from django.core.files.storage import get_storage_class from django.template.defaultfilters import force_escape from django.utils.functional import LazyObject OBJ_ADMIN_RE_PATTERN = r'<img [^>]*\bid="plugin_obj_(\d+)"[^>]*/?>' OBJ_ADMIN_RE =...
icon_alt=force_escape(obj.get_instance_icon_alt()), )
) ) return OBJ_ADMIN_RE.sub(_replace_tag, text) def _plugin_dict(text, regex=OBJ_ADMIN_RE): try: from cms.utils.plugins import downcast_plugins except ImportError: from cms.plugins.utils import downcast_plugins plugin_ids = plugin_tags_to_id_list(text, regex) plugin_list...
trevor/calendarserver
calendarserver/tools/checkdatabaseschema.py
Python
apache-2.0
7,687
0.003512
## # Copyright (c) 2014 Apple 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 la...
import Schema, Table, Column, Sequence from twext.enterprise.dal.parseschema import addSQLToSchema, schemaFromPath from twisted.python.filepath import FilePath USERNAME = "caldav" DATABASENAME = "caldav" PGSOCKETDIR = "127.0.0.1" SCHEMADIR = "./txdav/common/datastore/sql_schema/" # Executables: PSQL = "../postgresql...
ys.argv[0]) print("usage: %s [options] username" % (name,)) print("") print(" Check calendar server postgres database and schema") print("") print("options:") print(" -d: path to server's sql_schema directory [./txdav/common/datastore/sql_schema/]") print(" -k: postgres socket path (value ...
MarcoStucchi/ModbusTCP-Client-Server
device/device.py
Python
mit
2,774
0.01478
#Standard libraries import from thread import * #Local import import tcp_server device_repository = [ {'type': 'new emax', 'dictionary' : [['Current I1', 2000, 2, 0], ['Current I2', 2002, 2, 0], ['Current I3', 2004, 2, 0], ['Current Ne', 2006, 2, 0]]}, {'type': 'emax2', ...
e', 2006, 2, 0]]} ] ##Device class. # This class loads a device object dictionary and manage the interface with the external worls class Device: name = '' ##Device name freely assigned by user type = '' ##Device type, co
mpared with the repository object_dictionary = [] ##Object Dictionary object_dictionary_columns = \ ('Name', 'ModbusAddress', 'Size') ##Dictionary columns ##Constructor method def __init__(self, name = 'Generic device', type = 'emax2', diagnostics = False): #...
kubeflow/pipelines
components/aws/sagemaker/common/generate_components.py
Python
apache-2.0
4,875
0.000821
#!/usr/bin/env python3 """A command line tool for generating component specification files.""" # 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 # #...
c_dir.parent, "component.yaml") relative_path = component_file.relative_to(root) # Remove extension relative_module = os.path.splitext(str(relative_path))[0] with ComponentCollectorContext() as component_metadatas: # Import the file using the path relative to the root __import__(relativ...
)) if len(component_metadatas) != 1: raise ValueError( f"Expected exactly 1 ComponentMetadata in {component_file}, found {len(component_metadatas)}" ) if args.check: return SageMakerComponentCompiler.check( component_metadatas[0], str(relative_path),...
bleachbit/bleachbit
bleachbit/Action.py
Python
gpl-3.0
22,786
0.001097
# vim: ts=4:sw=4:expandtab # -*- coding: UTF-8 -*- # BleachBit # Copyright (C) 2008-2021 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version...
if 'f' == object_type and not os.path.isfile(path): continue elif 'd' == object_type and not os.path.isdir(path): continue yield path def _get_paths(sel
f): """Return a filtered list of files""" def get_file(path): if os.path.lexists(path): yield path def get_walk_all(top): """D
bmazin/ARCONS-pipeline
examples/skyAnalysis/statsExplorer.py
Python
gpl-2.0
12,388
0.016306
from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4 import QtGui import matplotlib.pyplot as plt import matplotlib import matplotlib.cm as cm import numpy as np
import sys import os from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.figure import Figure from mpl_toolkits.mplot3d import Axes3D from util.ObsFile import ObsFile from util.File...
ef mad(a,axis=-1): if axis==-1: return 1.4826*np.median(np.abs(a-np.median(a))) elif axis == 0: return 1.4826*np.median(np.abs(a-np.median(a))) class AppForm(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Pixel ...
legacysurvey/rapala
bokpipe/tools/bokwcs.py
Python
bsd-3-clause
1,410
0.021986
#!/usr/bin/env/python import sys import argparse from bokpipe.bokastrom import scamp_solve parser = argparse.ArgumentParser() parser.add_argument("image",type=str, help="input FITS image") parser.add_argument("catalog",type=str, help="input FITS catalog") parser.add_argument("...
talog,refStarCatFile=args.reference, filt=args.filter,savewcs=args.write,clobber=True, check_plots=args.plots
,twopass=not args.single, verbose=args.verbose,**kwargs)
talapus/Ophidian
Academia/ListComprehensions/cubes_by_four.py
Python
bsd-3-clause
107
0.009346
#!/usr/bin/env python cub
es_by_four = [x**3 for x in range(1,11) if (x**3) % 4 == 0] print
cubes_by_four
clusterfudge/boomer
boomer/filesystem/__init__.py
Python
gpl-3.0
1,932
0
# This file is part of Boomer Core. # # Boomer Core is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Boomer Core is distributed in t...
e <http://www.gnu.org/licenses/>. # # Forked from Mycroft Core on 2017-07-29 import os from os.path import join, expanduser, isdir __author__ = 'jdorleans' class FileSystemAccess(object): """ A class for providing access to the boomer FS sandbox. Intended to be attached to skills at initialization t...
amespace. """ def __init__(self, path): self.path = self.__init_path(path) @staticmethod def __init_path(path): if not isinstance(path, str) or len(path) == 0: raise ValueError("path must be initialized as a non empty string") path = join(expanduser('~'), '.boomer', ...
PanDAWMS/panda-server
pandaserver/dataservice/AdderGen.py
Python
apache-2.0
39,116
0.005778
''' add data to dataset ''' import os import re import sys import time import datetime # import fcntl import traceback import xml.dom.minidom import uuid from pandaserver.config import panda_config from pandacommon.pandalogger.PandaLogger import PandaLogger from pandacommon.pandalogger.LogWrapper import LogWrapper f...
#
self.logger.error(errMsg) elif self.jobStatus == EventServiceUtils.esRegStatus: # instantiate concrete plugin adderPluginClass = self.getPluginClass(self.job.VO) adderPlugin = adderPluginClass(self.job, taskB...
glue-viz/glue-qt
glue/sandbox/layertree.py
Python
bsd-3-clause
471
0.002123
im
port glue from glue.qt.layertreewidget import LayerTreeWidget def main(): """ Display a layer tree """ from PyQt4.QtGui import QApplication, QMainWindow import sys hub = glue.Hub() app = QApplication(sys.argv) win = QMainWindow() ltw = LayerTreeWidget() ltw.register_to_hub(hub) lt...
)
Laurawly/tvm-1
vta/python/vta/top/bitpack.py
Python
apache-2.0
2,886
0.000347
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
urn ret return te.compute(oshape, _bitpack, name=name, tag="bitpack") @register_compute("bitpack", level=15) def compute_bitpack(attrs, inputs): lanes = attrs.lanes dtype = inputs[0].dtype assert dtype == "int8" width = 8 assert width % lanes == 0 bits = 8 // lanes return bitpack(inpu...
rn("bitpack", OpPattern.INJECTIVE)
marcoandreini/injection
commands.py
Python
gpl-2.0
5,661
0.004063
# Here you can create play commands that are specific to the module, and extend existing commands import os import os.path import shutil import time from play.utils import * MODULE = 'injection' # Commands that are specific to your module COMMANDS = ['injection:ec'] HELP = { 'injection:ec': 'Update eclipse...
cXML = "" for module in sorted(modules):
lXML += '<link><name>%s</name><type>2</type><location>%s</location></link>\n' % (os.path.basename(module), os.path.join(module, 'app').replace('\\', '/')) if os.path.exists(os.path.join(module, "conf")): lXML += '<link><name>conf/%s</name><type>2</type><location>%s/conf</locatio...
Integral-Technology-Solutions/ConfigNOW
wlst/apps.py
Python
mit
6,847
0.019863
# ============================================================================ # # Copyright (c) 2007-2011 Integral Technology Solutions Pty Ltd, # All Rights Reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL...
#======================================================================================= appsModule = '1.0.1' log.debug('Loading module [apps.py] version [' + appsModule + ']') #======================================================================================= # Deploy applications
#======================================================================================= def deployApps(componentProperties): """Deploys applications""" applications = componentProperties.getProperty('applications') if applications is None: log.info('No applications to deploy') else: apps = applications.spl...
edison7500/django-leancloud-sms
testapp/settings.py
Python
gpl-3.0
2,833
0
""" Django settings for testapp project. Generated by 'django-admin startproject' using Django 1.8.18. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build pat...
_))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ap@6rnmzb&i&-ch^)hh=f=6a5)aho^f@td16y)-1-b9(p%v*l(' # SECURITY WARNING: don't run with debug tu...
on definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sms', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', ...
huguesv/PTVS
Python/Product/Miniconda/Miniconda3-x64/Lib/site-packages/win32com/test/testDictionary.py
Python
apache-2.0
2,509
0.006377
# testDictionary.py # import sys import win32com.server.util import win32com.test.util import win32com.client import traceback import pythoncom import pywintypes import winerror import unittest error = "dictionary test error" def MakeTestDictionary(): return win32com.client.Dispatch("Python.Dictionary") def Tes...
o args worked when it shouldnt have!") except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, argErr) = xxx_todo_changeme.args if hr != winerror.DISP_E_BADPARAMCOUNT: raise error("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc)) try: dict("hi", "there") ...
xxx_todo_changeme1.args if hr != winerror.DISP_E_BADPARAMCOUNT: raise error("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc)) try: dict(0) raise error("int key worked when it shouldnt have!") except pythoncom.com_error as xxx_todo_changeme2: (hr, desc, exc,...
mikeireland/chronostar
unit_tests/test_unit_expectmax.py
Python
mit
6,240
0.007372
from __future__ import print_function, division import numpy as np import pytest import sys import chronostar.likelihood sys.path.insert(0,'..') from chronostar import expectmax as em from chronostar.synthdata import SynthData from chronostar.component import SphereComponent from chronostar import tabletool from ch...
# dummy_mean = np.array([10,10,10, 5, 5, 5,np.log(dx),np.log(dv),20]) # dummy_std = np.array([1.,1.,1.,1
.,1.,1.,0.5, 0.5, 3.]) # assert len(dummy_mean) == len(dummy_std) # npars = len(dummy_mean) # # nsteps = 10000 # nwalkers = 18 # # dummy_chain = np.array([np.random.randn(nsteps)*std + mean # for (std, mean) in zip(dummy_std, dummy_mean)]).T # np.repeat(du...
plotly/plotly.py
packages/python/plotly/plotly/validators/layout/ternary/baxis/tickformatstop/_name.py
Python
mit
453
0
import _plotly_utils.basevalidators class NameValidator(_plotly_utils.bas
evalidators.StringValidator): def __init__( self, plotly_name="name", parent_name="layout.ternary.baxis.tickformatstop", **kwargs ): super(NameValidator, self).__init__( plotly_name=plotly_name, parent_name=p
arent_name, edit_type=kwargs.pop("edit_type", "plot"), **kwargs )
activityworkshop/Murmeli
murmeli/signals.py
Python
gpl-2.0
1,289
0.000776
'''Simple signal and timer functionality to remove dependency on Qt''' import threading import time class Signal: '''A signal which can be connected to one or more listeners''' def __init__(self): self._listeners = [] def clear(self): '''Clear all the listeners''' self._listeners...
lear() def connect(self, listener): '''Connect this signal to an additional listener''' if listener: self._listeners.append(listener) def fire(self): '''Fire the signal to each of the listeners in turn''' for listener in self._listeners: l
istener() class Timer: '''Calls a given method either repeatedly or after a given period''' def __init__(self, delay, target, repeated=True): self.delay = delay self.target = target self.repeated = repeated self.running = True threading.Thread(target=self.run).start() ...
gecos-team/gecos-firstboot
firstboot/pages/linkToChef/LinkToChefConfEditorPage.py
Python
gpl-2.0
7,126
0.003369
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, ...
efaultRole.get_text()) == 0: self.ui.txtDefaultRole.set_text(__DEFAULT_ROLE__) self.update_server_conf = True self.chef_is_configured = params['ch
ef_is_configured'] self.unlink_from_chef = params['unlink_from_chef'] # if self.chef_is_configured and self.unlink_from_chef: # self.ui.chkChef.get_child().set_markup(self._bold(_('This \ #workstation is going to be unlinked from the Chef server.'))) def _bold(self, str): return ...
nugget/home-assistant
homeassistant/components/plum_lightpad/light.py
Python
apache-2.0
5,479
0
"""Support for Plum Lightpad lights.""" from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, Light) from homeassistant.components.plum_lightpad import PLUM_DATA import homeassistant.util.color as color_util DEPENDENCIES = ['plum_lightpad'] async def asyn...
the brightness of this switch between 0..255.""" return self._brightness @property def glow_intensity(self): """Brightness in float form.""" return self._brightness / 255.0 @property def is_on(self) -> bool: """Return true if light is on.""" return self._state ...
rait' @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_COLOR async def async_turn_on(self, **kwargs): """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs: await self._lightpad.set_config( ...
yegorshr/CDNetworksAPI
cdnetworks/__init__.py
Python
apache-2.0
186
0
fr
om .base import Base from .helper import select_item_by_user from .actions import Actions from .browser import Browser __all__ = ['select_
item_by_user', 'Base', 'Actions', 'Browser']
alxgu/ansible
lib/ansible/modules/messaging/rabbitmq/rabbitmq_binding.py
Python
gpl-3.0
9,638
0.002594
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2015, Manuel Sousa <manuel.sousa@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_...
anuel-sousa) version_added: "2.0"
short_description: Manage rabbitMQ bindings description: - This module uses rabbitMQ REST APIs to create / delete bindings. requirements: [ "requests >= 1.0.0" ] options: state: description: - Whether the bindings should be present or absent. choices: [ "present", "absent" ] default: prese...
kennedyshead/home-assistant
tests/components/zwave_js/test_api.py
Python
apache-2.0
58,118
0.000465
"""Test the Z-Wave JS Websocket API.""" import json from unittest.mock import patch import pytest from zwave_js_server.const import LogLevel from zwave_js_server.event import Event from zwave_js_server.exceptions import ( FailedCommand, InvalidNewValue, NotFoundError, SetValueFailed, ) from homeassist...
not msg["success"] assert msg["error"]["code"] == ERR_NOT_LOADED asy
nc def test_ping_node( hass, wallmote_central_scene, integration, client, hass_ws_client ): """Test the ping_node websocket command.""" entry = integration ws_client = await hass_ws_client(hass) node = wallmote_central_scene client.async_send_command.return_value = {"responded": True} awai...
dit/dit
tests/profiles/test_mui.py
Python
bsd-3-clause
907
0.002205
""" Tests for dit.profiles.MUIProfile. Known examples taken from http://arxiv.org/abs/1409.4708 . """ import pytest import numpy as np from dit import Distribution from dit.profiles import MUIProfile ex1 = Distribution(['000', '001', '010', '011', '100', '101', '110', '111'], [1 / 8] * 8) ex2 = Distribution(['000'...
n(['000', '001', '110', '111'], [1 / 4] * 4) ex4 = Distribution(['000', '011', '101', '110'], [1 / 4] * 4) examples = [ex1, ex2, ex3, ex4] pytest.importorskip('scipy') @pytest.mark.parametrize(('d', 'prof', 'width'), [ (ex1, {0.0: 1.0}, [3.0]), (ex2, {0.0: 3.0}, [1.0]), (ex3, {0.0: 2.0, 1.0: 1.0}, [1.0,...
sert np.allclose(mui.widths, width)
lablup/sorna-common
src/ai/backend/common/utils.py
Python
lgpl-3.0
9,171
0.00109
from __future__ import annotations import base64 from collections import OrderedDict from datetime import timedelta from itertools import chain import numbers import random import re import sys from typing import ( Any, Iterable, Iterator, Mapping, Tuple, TYPE_CHECKING, TypeVar, Union, ...
None """ pieces = key_path.split(path_delimiter) while pieces: p = pieces.pop(0) if o is None or p not in o: return def_val o = o[p] if o is None and null_as_default: return def_val return o def readable_size_to_bytes(expr: Any) -> BinarySize | Decimal:...
if isinstance(expr, numbers.Real): return BinarySize(expr) return BinarySize.from_str(expr) def str_to_timedelta(tstr: str) -> timedelta: """ Convert humanized timedelta string into a Python timedelta object. Example: >>> str_to_timedelta('30min') datetime.timedelta(seconds=1800) ...
xhorn/xchorizon
horizon/usage/tables.py
Python
apache-2.0
2,032
0
from django.utils.translation imp
ort ugettext_lazy as _ from django.template.defaultfilters import timesince, floatformat from horizon import tables from horizon.templatetags.sizeformat import mbformat class CSVSummary(tables.LinkAction): name = "csv_summary" verbose_name = _("Download CSV Summary") classes = ("btn-download",) def ...
link_url(self, usage=None): return self.table.kwargs['usage'].csv_link() class BaseUsageTable(tables.DataTable): vcpus = tables.Column('vcpus', verbose_name=_("VCPUs")) disk = tables.Column('local_gb', verbose_name=_("Disk")) memory = tables.Column('memory_mb', verbose_n...
prasanna08/oppia
scripts/linters/test_files/invalid_test_only.py
Python
apache-2.0
1,448
0
# coding: utf-8 # # Copyright 2020 The Oppia 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 requi...
odules import python_utils class FakeClass(python_utils.OBJECT): """This is a fake docstring for invalid syntax purposes.""" def __init__(self, fake_arg): self.fake_arg = fake_arg # Use of test_only is not allowed in non-test files. def test_only_method(self, name): """This doesn't ...
le(str, str). The argument passed in but twice in a tuple. """ yield (name, name)
drsmith48/fdp
fdp/lib/shot.py
Python
mit
4,629
0.00108
# -*- coding: utf-8 -*- """ Created on Wed Nov 25 12:14:03 2015 @author: ktritz """ from __future__ import print_function from builtins import str, range import inspect import types #import numpy as np from collections.abc import MutableMapping from .container import containerClassFactory class Shot(MutableMapping)...
rundate if self._logbook_entries: return self._logbook_entries[0]['rundate'] else: return def __getatt
r__(self, attr_name): if attr_name in self._modules: if self._modules[attr_name] is None: self._modules[attr_name] = containerClassFactory(attr_name, root=self._machine, ...
synergeticsedx/deployment-wipro
lms/djangoapps/oauth2_handler/handlers.py
Python
agpl-3.0
8,254
0.001696
""" Handlers for OpenID Connect provider. """ from django.conf import settings from django.core.cache import cache from courseware.access import has_access from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY from openedx.core.dj...
nymous_id_for_user(data['user'], None) return value class PermissionsHandler(object)
: """ Permissions scope handler """ def scope_permissions(self, _data): return ['administrator'] def claim_administrator(self, data): """ Return boolean indicating user's administrator status. For our purposes an administrator is any user with is_staff set to True. ...
repotvsupertuga/tvsupertuga.repository
script.module.xbmcswift2/lib/xbmcswift2/xbmcmixin.py
Python
gpl-2.0
22,104
0.000724
import os import sys import time import shelve import urllib from datetime import timedelta from functools import wraps import xbmcswift2 from xbmcswift2 import xbmc, xbmcaddon, xbmcplugin, xbmcgui from xbmcswift2.storage import TimedStorage from xbmcswift2.logger import log from xbmcswift2.constants import VIEW_MODES...
ontent(self, content): '''Sets the content type for the plugin.''' # TODO: Change to a warning instead of an assert. Otherwise will have # to keep this list in sync with # any XBMC changes. #contents = ['files', 'songs', 'artists', 'albums', 'movies', #'tvshows', 'e...
s, 'Content type "%s" is not valid' % content xbmcplugin.setContent(self.handle, content) def get_setting(self, key, converter=None, choices=None): '''Returns the settings value for the provided key. If converter is str, unicode, bool or int the settings value will be returned conve...
timothy1191xa/project-epsilon-1
code/utils/tests/test_mask.py
Python
bsd-3-clause
1,918
0.008342
"""test_mask.py Tests for the functions in the mask_functions.py Run with: nosetests test_mask.py """ from __future__ import print_function import os, sys import numpy as np from numpy.testing import assert_array_equal #Append path to functions sys.path.append(os.path.join(os.path.dirname(__file__), "../functions...
3d) arr_2d = np.arange(9).reshape((3,3)) mask_bool2d = arr_2d < 10 # make_binary_mask(arr_3d,mask_bool2d) def test_make_bool_mask(): # We make a 3D array of shape (3,3,2) slab3 = np.ones((3,)) arr_3d = np.zeros((3, 3)) a
rr_3d[0, :] = slab3 mask_bool = make_bool_mask(arr_3d) assert_array_equal(mask_bool[0, :],np.ones((3,), dtype=bool)) assert_array_equal(mask_bool[1:,: ],np.zeros((2, 3), dtype=bool))
GoogleCloudPlatform/appengine-blobstoremgmt-python
src/main.py
Python
apache-2.0
730
0
# Copyright 2018 Google Inc. All rights rese
rved. # # 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 ...
NY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Main WSGI app for blob-management tool. """ import webapp2 from app import routes APP = webapp2.WSGIApplication(routes.ROUTES)
thinkopensolutions/server-tools
auto_backup/tests/test_db_backup.py
Python
agpl-3.0
8,529
0
# -*- coding: utf-8 -*- # © 2015 Agile Business Group <http://www.agilebg.com> # © 2015 Alessio Gerace <alesiso.gerace@agilebg.com> # © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import os import mock...
'folder': self.vals['folder'], }, rec_id.name, ) def test_check_folder(self): """ It should not allow recursive backups """ rec_id = self.new_record('local') with self.assertRaises(exceptions.ValidationError): rec_id.write({ ...
.config.filestore( self.env.cr.dbname ), }) @mock.patch('%s._' % model) def test_action_sftp_test_connection_success(self, _): """ It should raise connection succeeded warning """ rec_id = self.new_record() with mock.patch.object(rec_id, '...
linucks/ample
ample/parsers/tests/test_tm_parser.py
Python
bsd-3-clause
1,471
0
"""Test functions for parsers.tm_parser""" import os import unittest from ample import constants from ample.parsers import tm_parser cl
ass TestTMscore(unittest.TestCase): @classmethod def setUpClass(cls): cls.thisd = os.path.abspath(os.path.dirname(__file__)) cls.ample_share = constants.SHARE_DIR cls.testfiles_dir = os.path.join(cls.ample_share, 'testfiles') def test_parse(self): logfile = os.path.join(self...
TM = tm_parser.TMscoreLogParser() TM.parse(logfile) self.assertEqual(173, TM.nr_residues_common) self.assertEqual(6.654, TM.rmsd) self.assertEqual(0.5512, TM.tm) self.assertEqual(0.3147, TM.maxsub) self.assertEqual(0.4292, TM.gdtts) self.assertEqual(0.2283, ...
mgabay/Variable-Size-Vector-Bin-Packing
vsvbp/__init__.py
Python
gpl-3.0
37
0
from .be
nchmark import run_benchmark
yv84/pyph
src/tests/integrate_tests/msg_log.py
Python
mit
2,730
0.003297
import sys import os PACKAGE_PARENT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from proxy.repr_to_bytes import repr_bytes_to_bytes_gen class Message(): def __init__(...
elif self.side == 'server': while log['client'] and log['server']: _pin_pong.update({log['client'].pop(0):log['s
erver'].pop(0)}) return _pin_pong def __call__(self, msg=b''): self.msg = b''.join([self.msg, msg]) if self.msg in self.pin_pong: yield self.pin_pong[self.msg] self.msg = b'' @staticmethod def game_log_from_import(log): _log = [] _side_log = ...
neurospin/localizer
entities.py
Python
lgpl-2.1
916
0.001092
# -*- coding: utf-8 -*- # copyright 2013 CEA (Saclay, FRANCE), all rights reserved. # copyright 2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://brainomics.cea.fr -- mailto:localizer94@cea.fr # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU...
n, either version 2.1 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # ...
uld have received a copy of the GNU Lesser General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. """cubicweb-localizer entity's classes"""
Blimeo/Java
out/production/matthew/Contests/TopCoder/SRM007/Dice.py
Python
apache-2.0
637
0.069074
from itertools import repeat def getScores(nu
mPlayers, dieRolls): dieRolls = list(dieRolls) scores = list(repeat(0, numPlayers)) print(scores) c = 0 last = -1 num = 0 for i in dieRolls: v = dieRolls[i] if not (v == last and num > 0): if v <= 2: scores[c] += 1 elif v <= 4: scores[c] += 2 else: scores[c] += 3 if v == last: num ...
c = c % numPlayers return scores print(getScores(5, [3,4,4,4,4,6,6,2,1,5,5]))
drmonkeysee/ecs-scheduler
ecs_scheduler/webapi/home.py
Python
mit
1,021
0
"""Root url REST resources.""" import flask import flask_restful from .jobs import Jobs from .spec import Spec class Home(flask_restful.Resource): """Home url REST resource.""" def get(self): """ Home Available endpoints for the web api. --- tags: - docs ...
esources': [ { 'link': { 'rel': 'jobs', 'title': 'Jobs', 'href': flask.url_for(Jobs.__name__.lower()), }, }, { 'link': { ...
'href': flask.url_for(Spec.__name__.lower()), }, } ], }
danhuss/faker
faker/providers/person/fr_FR/__init__.py
Python
mit
10,085
0.003793
from .. import Provider as PersonProvider class Provider(PersonProvider): formats_female = ( '{{first_name_female}} {{last_name}}', '{{first_name_female}} {{last_name}}', '{{first_name_female}} {{last_name}}', '{{first_name_female}} {{last_name}}', '{{first_name_female}} {{...
', 'Alves
', 'Etienne', 'Marchal', 'Poulain', 'Tessier', 'Lemaitre', 'Guichard', 'Besson', 'Mallet', 'Hoareau', 'Gillet', 'Weber', 'Jacob', 'Collin', 'Chevallier', 'Perrier', 'Michaud', 'Carlier', 'Delaunay', 'Chauvin', 'Alexandre', 'Marechal', 'Antoine', 'Lebon', 'Cordier', 'Lejeune', 'Bouchet', 'Pasquie...
solarpermit/solarpermit
website/migrations/0043_auto__add_field_userdetail_display_preference.py
Python
bsd-3-clause
48,128
0.007293
# -*- coding: utf-8 -*- import 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 'UserDetail.display_preference' db.add_column('website_userdetail', 'display_preference', ...
'label': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'bla
nk':
ema/conpaas
conpaas-services/src/conpaas/core/ganglia.py
Python
bsd-3-clause
5,129
0.007019
# -*- coding: utf-8 -*- """ conpaas.core.ganglia ==================== ConPaaS core: performance monitoring with Ganglia. :copyright: (C) 2010-2013 by Contrail Consortium. """ import os from shutil import copyfile, copy from Cheetah.Template import Template from conpaas.core.misc import run_cmd c...
glia.start(self) if err: return err
cmds = ( '/etc/init.d/gmetad start', '/etc/init.d/php5-fpm start', '/usr/sbin/nginx -c /var/cache/cpsagent/nginx-manager.conf' ) for cmd in cmds: _, err = run_cmd(cmd) if err: return "Error executing '%s': %s" % (cmd, err) class Agen...
cfe-lab/Kive
kive/container/tests_mock.py
Python
bsd-3-clause
39,450
0.000406
import os from argparse import Namespace import tempfile import io import zipfile import tarfile import json from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.files.base import File from django.test import TestCase from django.urls import reverse, resolve f...
_, self.empty_tar_archive = tempfile.m
kstemp() with zipfile.ZipFile(self.empty_zip_archive, mode="w"): pass with tarfile.open(self.empty_tar_archive, mode="w"): pass # Improper archives that contain no drivers. _, self.no_driver_zip = tempfile.mkstemp() _, self.no_driver_tar = tempfile.mkstem...
wixenius/Project_Euler
13.py
Python
mit
5,198
0.000192
s = """37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 2811287...
2192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674
417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 6662789198148808779794187687...
jgmize/kuma
kuma/users/templatetags/jinja_helpers.py
Python
mpl-2.0
5,220
0.000383
from allauth.account.utils import user_display from allauth.socialaccount import providers from allauth.socialaccount.templatetags.socialaccount import get_providers from allauth.utils import get_request_param from django.conf import settings from django.contrib import admin from django.utils.translation import ugettex...
return Markup(link) @library.global_function def admin_link(user): """Returns a link to admin a user""" url = reverse('admin:users_user_change', args=(user.id,),
current_app=admin.site.name) link = ('<a href="%s" class="button neutral">%s' '<i aria-hidden="true" class="icon-wrench"></i></a>' % (url, ugettext('Admin'))) return Markup(link) @library.filter def public_email(email): """Email address -> publicly displayable email...
vijos/vj4
vj4/model/user.py
Python
agpl-3.0
6,864
0.014423
import datetime from pymongo import errors from pymongo import ReturnDocument from vj4 import db from vj4 import error from vj4.model import builtin from vj4.util import argmethod from vj4.util import pwhash from vj4.util import validator PROJECTION_PUBLIC = {'_id': 1, 'uname': 1, ...
def set_mail(uid: int, mail: str): """Set mail. Returns doc or None.""" validator.check_mail(mail) return await set_by_uid(uid, mail=mail, mail_lower=mail.strip().lower()) @argmethod.wrap async def change_password(uid: int, current_password: str, password: str): """Change password. Returns doc or None.""" d...
c = await coll.find_one_and_update(filter={'_id': doc['_id'], 'salt': doc['salt'], 'hash': doc['hash']}, update={'$set': {'salt': salt, ...
EricMuller/mynotes-backend
requirements/twisted/Twisted-17.1.0/src/twisted/mail/test/test_bounce.py
Python
mit
1,029
0.002915
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Test cases for bounce message generation """ from twisted.trial import unittest from twisted.mail import bounce import cStringIO import email.message import email.parser class BounceTests(unittest.TestCase): """ testcases for bounce ...
subject'], 'Returned Mai
l: see transcript for details') def testBounceMIME(self): pass
michaelpacer/dynd-python
dynd/tests/test_range_linspace.py
Python
bsd-2-clause
5,966
0.003185
import sys import unittest from dynd import nd, ndt class TestArange(unittest.TestCase): def test_simple(self): self.assertEqual(nd.as_py(nd.range(10)), list(range(10))) self.assertEqual(nd.as_py(nd.range(5, 10)), list(range(5, 10))) self.assertEqual(nd.as_py(nd.range(5, 10, 3)), list(range...
ssertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.int64) self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint8) self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint16) self.assertRaises(RuntimeErr
or, nd.linspace, 0, 1, dtype=ndt.uint32) self.assertRaises(RuntimeError, nd.linspace, 0, 1, dtype=ndt.uint64) # Should obey the float/complex type requests self.assertEqual(nd.dtype_of(nd.linspace(0, 1, dtype=ndt.float32)), ndt.float32) self.assertEqual(nd.dtype_of(nd.linspace(0, 1, dtyp...
Eagles2F/sync-engine
inbox/auth/_outlook.py
Python
agpl-3.0
4,066
0.001968
import datetime import sqlalchemy.orm.exc from nylas.logging import get_logger log = get_logger() from inbox.auth.oauth import OAuthAuthHandler from inbox.basicauth import OAuthError from inbox.models import Namespace from inbox.config import config from inbox.models.backends.outlook import OutlookAccount from inbox...
account.link = response.get('link') account.locale = response.get('locale') # Unlike Gmail, Outlook doesn't return t
he client_id and secret here account.client_id = OAUTH_CLIENT_ID account.client_secret = OAUTH_CLIENT_SECRET # Ensure account has sync enabled. account.enable_sync() return account def validate_token(self, access_token): return self._get_user_info(access_token) ...
Huyuwei/tvm
tests/python/relay/test_pass_alter_op_layout.py
Python
apache-2.0
22,068
0.001178
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
NTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Test alter op layout pass""" import tvm from tvm import r
elay from tvm.relay.op import register_alter_op_layout from tvm.relay import transform, analysis def run_opt_pass(expr, passes): passes = passes if isinstance(passes, list) else [passes] mod = relay.Module.from_expr(expr) seq = transform.Sequential(passes) with transform.PassContext(opt_level=3): ...
zappyk-github/zappyk-python
src/src_zappyk/findNameSend/setup.py
Python
gpl-2.0
2,984
0.029155
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'zappyk' import os, sys from lib_zappyk import _setup project = 'FindNameSend' name = __import__(project).get_project() description = __import__(project).get_description() version = __import__(project).get_version() author = _setup.AUTH...
on ,license=license ,keywords=keywords ,executables=[executables] ,options=dict(build_exe=buildOptions) # ,packages=pkgs_include # ,include_package_data=True # ,scripts=[file_execute] ...
################## sys.exit(0)
luboslenco/lue
tools/io_export_arm.py
Python
lgpl-3.0
29,689
0.003166
# Armory Mesh Exporter # https://armory3d.org/ # # Based on Open Game Engine Exchange # https://opengex.org/ # Export plugin for Blender by Eric Lengyel # Copyright 2015, Terathon Software LLC # # This software is licensed under the Creative Commons # Attribution-ShareAlike 3.0 Unported License: # http://creat...
= {} self.meshArray = {} self.boneParentArray = {} self.bone_tracks = [] self.depsgraph = context.evaluated_depsgraph_get() scene_objects = self.scene.collection.all_objects for bobject in scene_objects: if not bobject.parent: self.process_bob...
self.output['objects'] = [] for bo in scene_objects: if not bo.parent: self.export_object(bo, self.scene) self.output['mesh_datas'] = [] for o in self.meshArray.items(): self.export_mesh(o, self.scene) self.write_arm(self.filepath, self.output)...
ScienceWorldCA/domelights
backend/artnet-bridge/artnet-server.py
Python
apache-2.0
234
0.012821
from artnet import * import SocketServer import time, os, random, datetime, sys import argparse import socket import struct from subprocess import Popen, PIPE, STDOUT import glob DEBUG
= False UD
P_IP = "2.0.0.61" UDP_PORT = 6454
CBien/django-alert
test_project/manage.py
Python
mit
698
0.004298
#!/usr/bin/env python try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it
your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": try: from django.core.management import execute_from_command_line
execute_from_command_line() except ImportError: from django.core.management import execute_manager execute_manager(settings)
shadowoneau/skylines
skylines/commands/tracking/stats.py
Python
agpl-3.0
4,007
0.001248
from flask_script import Command, Option from datetime import timedelta from itertools import chain from skylines.database import db from skylines.model import TrackingFix, User class Stats(Command): """ Analyse live tracks and output statistics """ option_list = ( Option('user', type=int, help='a ...
dt = (fix.time - last_fix.time) if (fix and last_fix) else None is_new_session = dt an
d dt > timedelta(hours=3) # update current session if not (is_start or is_new_session or is_end): session['num_fixes'] += 1 dt_secs = dt.total_seconds() session['min_dt'] = min(dt_secs, session.get('min_dt', 999999)) session['max_...
ThomasYeoLab/CBIG
stable_projects/fMRI_dynamics/Kong2021_pMFM/part2_pMFM_control_analysis/Individual_analysis/scripts/CBIG_pMFM_step5_validation_IndividualGrad.py
Python
mit
3,061
0.000653
# /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as np import torch import CBIG_pMFM_basic_functions as fc def CBIG_mfm_validation_desikan_main(gpu_index=0, subject=1): ''' This function is to v...
+ str(subject) + '/gradient/training/' output_path = '../output/subject' + str(subject) + '/gradient/validation/' if not os.path.isdir(output_path): os.makedirs(output_path) # Loading myelin and gradient data highest_order = 1 gradient_data = fc.csv_matrix_read( '../../../input/Des...
((n_node, highest_order + 1)) for i in range(highest_order + 1): amatrix[:, i] = gradient_data**(i) template_mat = amatrix # Setting hyper-parameters n_trial = 2 vali_dup = 20 for i in range(1, 8): random_seed_cuda = i + 100 torch.cuda.manual_seed(random_seed_cuda) ...
kahuang/jarvis
jarvis/modules/coinbase/watcher.py
Python
mit
8,706
0.004824
import cPickle import logging import numpy import os import time from collections import deque from copy import deepcopy from datetime import datetime from pytz import timezone from threading import Event, Thread from coinbase.wallet.client import Client from jarvis.utils.messaging.client import TwilioMessenger from ...
ges: self.sent_messages = deque(maxlen=3) @property def raw_btc_timeseries(self): return self.btc_timeseries.timeseries @property def raw_eth_timeseries(self): return self.eth_timeseries.timeseries @property def in_cooldown(self): self.cooldown = max(0,self...
cooldown = self.COOLDOWN_TICKS def start(self): while not self.stop.is_set(): try: spot_price = self.coinbase_client.do( 'get_spot_price',currency_pair='BTC-USD') self.btc_timeseries.append(float(spot_price['amount'])) # c...
gogobook/Spirit
spirit/comment/urls.py
Python
mit
1,185
0.003376
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url, include import spirit.comment.bookmark.urls import spirit.comment.flag.urls import spirit.comment.history.urls import spirit.comment.like.urls from . import views urlpatterns = [ url(r'^(?P<topic_id>\d+)/publish/$...
ate, name='update'), url(r'^(?P<pk>\d+)/find/$', views.find, name='find'), url(r'^(?P<topic_id>\d+)/move/$', views.move, name='move'), url(r'^(?P<pk>\d+)/delete/$', views.delete, name='delete'), url(r'^(?P<pk>\d+)/undelete/$', views.delete, kwargs={'remove': False, }, name='undelete'), url(r'^uplo...
, url(r'^flag/', include(spirit.comment.flag.urls, namespace='flag')), url(r'^history/', include(spirit.comment.history.urls, namespace='history')), url(r'^like/', include(spirit.comment.like.urls, namespace='like')), ]
XiaoMi/galaxy-fds-sdk-python
fds/model/timestamp_anti_stealing_link_config.py
Python
apache-2.0
1,037
0.019286
class TimestampAntiStealingLinkConfig(dict): def __init__(self, json): if json is not None: if 'enabled' in json.keys(): self.enabled = json['enabled'] else: self.enabled = None if 'primaryKey' in json.keys(): self.primary_key = json['primaryKey'] else: self...
secondary_key = None else: raise GalaxyFDSClientException("Json data cannot be None") @property def enabled(self): return self['enabled'] @enabled.setter def enabled(self, enabled): self['enabled'] = enabled
@property def primary_key(self): return self['primaryKey'] @primary_key.setter def primary_key(self, primary_key): self['primaryKey'] = primary_key @property def secondary_key(self): return self['secondaryKey'] @secondary_key.setter def secondary_key(self, secondary_key): self['secondar...
jonludlam/xen
tools/python/xen/util/oshelp.py
Python
gpl-2.0
961
0.014568
import fcntl import os def close_fds(pass_fds=()): try:
MAXFD =
os.sysconf('SC_OPEN_MAX') except: MAXFD = 256 for i in range(3, MAXFD): if i in pass_fds: continue try: os.close(i) except OSError: pass def fcntl_setfd_cloexec(file, bool): f = fcntl.fcntl(file, fcntl.F_GETFD) if bool: f |= f...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/PyKDE4/kio/KDirWatch.py
Python
gpl-2.0
2,320
0.011207
# encoding: utf-8 # module PyKDE4.kio # from /usr/lib/python2.7/dist-packages/PyKDE4/kio.so # by generator 1.135 # no doc # imports import PyKDE4.kdeui as __PyKDE4_kdeui import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui class KDirWatch(__PyQt4_QtCore.QObject): # no doc def addDir(self...
# real signature unk
nown pass def removeFile(self, *args, **kwargs): # real signature unknown pass def restartDirScan(self, *args, **kwargs): # real signature unknown pass def self(self, *args, **kwargs): # real signature unknown pass def setCreated(self, *args, **kwargs): # real signatu...
mishbahr/django-connected
connected_accounts/providers/google.py
Python
bsd-3-clause
1,465
0
import logging from django.utils.translation import ugettext_lazy as _ from connected_accounts.conf import settings from connected_accounts.provider_pool import providers from .base import OAuth2Provider, ProviderAccount logger = logging.getLogger('connected_accounts') class GoogleAccount(ProviderAccount): de...
Auth2Provider): id = 'google' name = _('Google+') account_class = GoogleAccount authorization_url = 'https://accounts.google.com/o/oauth2/auth' access_token_url = 'https://accounts.google.com/o/oauth2/token' profile_url = 'https://www.googleapis.com/oauth2/v1/userinfo' consumer_key = setti...
NTS_GOOGLE_CONSUMER_SECRET scope = settings.CONNECTED_ACCOUNTS_GOOGLE_SCOPE auth_params = settings.CONNECTED_ACCOUNTS_GOOGLE_AUTH_PARAMS providers.register(GoogleProvider)
qiyeboy/SpiderBook
ch11/APISpider/SpiderMan.py
Python
mit
1,040
0.007692
#coding:utf-8 from APISpider.SpiderDataOutput import SpiderDataOutput from APISpider.SpiderDownloader import SpiderDownloader from APISpider.SpiderParser import SpiderParser class SpiderMan(object): def __init__(self): self.downloader = SpiderDownloader() self.parser = SpiderParser() self...
url) for info in self.parser.get_kw_cat(content): print info cat_name = info['cat_name'] detail_url = 'http://ts.kuwo.cn/service/getlist.v31.php?act=detail&id=%s'%info['id'] content = self.downloader.download(detail_url) details = self.parser.get_kw_de...
(self.output.filepath,details) self.output.ouput_end(self.output.filepath) if __name__ =="__main__": spider = SpiderMan() spider.crawl('http://ts.kuwo.cn/service/getlist.v31.php?act=cat&id=50')
rpetersburg/fiber_properties
fiber_properties/calibrated_image.py
Python
mit
11,258
0.001244
"""calibrated_image.py was written by Ryan Petersburg for use with fiber characterization on the EXtreme PREcision Spectrograph """ import numpy as np from .base_image import BaseImage from .numpy_array_handler import filter_image, subframe_image class CalibratedImage(BaseImage): """Fiber face image analys...
mage_to_array(self.image_input) def get_image(self): """Return the corrected image This method must be called to get access to the corrected 2D numpy array being analyzed. Attempts to access a previously saved image under self.image_file or otherwise applies corrections to t...
ibration images """ if self.image_file is not None and not self.new_calibration: return self.image_from_file(self.image_file) return self.execute_error_corrections(self.get_uncorrected_image()) def get_uncorrected_filtered_image(self, kernel_size=None, **kwargs): ...
adviti/melange
thirdparty/google_appengine/lib/django_1_2/tests/modeltests/model_inheritance/tests.py
Python
apache-2.0
10,909
0.002933
from operator import attrgetter from django.conf import settings from django.core.exceptions import FieldError from django.db import connection from django.test import TestCase from models import (Chef, CommonInfo, ItalianRestaurant, ParkingLot, Place, Post, Restaurant, Student, StudentWorker, Supplier, Worker, M...
ate(name="Barney
", age=34, job="Quarry worker") s = Student.objects.create(name="Pebbles", age=5, school_class="1B") self.assertEqual(unicode(w1), "Worker Fred") self.assertEqual(unicode(s), "Student Pebbles") # The children inherit the Meta class of their parents (if they don't # specify the...
flatangle/flatlib
flatlib/tools/planetarytime.py
Python
mit
4,632
0.004751
""" This file is part of flatlib - (C) FlatAngle Author: João Ventura (flatangleweb@gmail.com) This module provides useful functions for handling planetary times. The most import element is the HourTable class which handles all queries to the planetary rulers and hour ruler...
the current hour ruler. """ return self.table[self.currIndex]
[2] def currInfo(self): """ Returns information about the current planetary time. """ return self.indexInfo(self.currIndex) def indexInfo(self, index): """ Returns information about a specific planetary time. """ entry = self....
clebergnu/autotest
client/common_lib/profiler_manager.py
Python
gpl-2.0
3,234
0.00402
import os, sys import common from autotest_lib.client.common_lib import error, utils, packages class ProfilerNotPresentError(error.JobError): def __init_
_(self, name, *args, **dargs): msg = "%s not present" % name error.JobError.__init__(self, msg, *args, **dargs) class profiler_manager(object): def __init__(self, job): self.job = job self.list = [] self.tmpdir = job.tmpdir self.profile_run_only = False self...
gs, dargs): """ Given a name and args, loads a profiler, initializes it with the required arguments, and returns an instance of it. Raises a ProfilerNotPresentError if the module isn't found. """ raise NotImplementedError("load_profiler not implemented") def add(self, profiler, *ar...