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
ITOO-UrFU/open-programs
open_programs/apps/competences/apps.py
Python
unlicense
141
0
from django.apps import AppConfi
g class CompetencesConfig(AppConfig): name = 'competenc
es' verbose_name = "Компетенции"
facebook/buck
test/com/facebook/buck/cxx/testdata/cxx_toolchain/tools/linker.py
Python
apache-2.0
531
0
#!/usr/bin/env python3 import os import sys from tools import impl parser = impl.argparser() parser.add_argument("-o", d
est="output", action=impl.StripQuotesAction) (options, args) = parser.parse_known_args() # ranlib may have hid the archive next to what buck thinks the archive is input = args[-1]
+ ".secret" if not os.path.exists(input): input = args[-1] with open(options.output, "w") as output: output.write("linker:\n") with open(input) as inputfile: output.write(inputfile.read()) sys.exit(0)
tensorflow/graphics
tensorflow_graphics/projects/points_to_3Dobjects/utils/image.py
Python
apache-2.0
2,459
0.011793
# Copyright 2020 The TensorFlow 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def get_dir(point, rot_rad): sin_rot, cos_rot = np.sin(rot_rad), np.cos(rot_rad) result = [0, 0] result[0] = point[0] * cos_rot - point[1] * sin_rot result[1] = point[0] * sin_rot + point[1] * cos_rot return np.array(result) def transform_points(points, center, scale, output_size, inverse=False):
transform = get_affine_transform( center, scale, 0, output_size, inverse=inverse) new_points = np.concatenate([points, np.ones([points.shape[0], 1])], axis=1) points_transformed = np.dot(transform, new_points.T).T return points_transformed def transform_predictions(points, center, scale, output_size): ...
remotesyssupport/cobbler-1
koan/register.py
Python
gpl-2.0
6,100
0.008033
""" registration tool for cobbler. Copyright 2009 Red Hat, Inc. Michael DeHaan <mdehaan@redhat.com> 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 2 of the License, or (at your optio...
name = "" sysname = str(time.time()) else: raise InfoException("must specify --fqdn, could not discover") if
sysname == "": sysname = hostname if self.profile == "": raise InfoException("must specify --profile") # we'll do a profile check here just to avoid some log noise on the remote end. # network duplication checks and profile checks also happen on the remote end. ...
adjustive/caller
caller/settings/common.py
Python
gpl-3.0
4,021
0.002984
""" Common Django settings for the project. See the local, test, and production settings modules for the values used in each environment. 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...
'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',
], }, }, ] WSGI_APPLICATION = 'caller.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'caller', 'USER': 'calluser', 'PASSWORD': 'qq...
stackdump/txbitwrap
txbitwrap/_brython/ctl.py
Python
mit
7,943
0.001763
from browser import window, document as doc, console import net import sim import json CTX = None """ Bitwrap context """ CTL = None """ UI control interface """ def __onload(ctx): """ use snap to begin creating an SVG """ global CTL CTL = Editor() window.jQuery('#net').on('click', CTL.on_insert) ...
_defs[txn]['delta
'][offset] = diff self.selected_arc_endpoint = None # reset self.reset(callback=self.render) class Editor(Controller, EditorEvents): """ Petri-Net editor controls """ def __init__(self): self.callback = self.on_select self.move_enabled = True self.selected_insert_symb...
harwee/electrum-xvg-tor
lib/wallet.py
Python
gpl-3.0
73,225
0.003086
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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 3 of the License, or # (at...
rt threading import random import time import math import json import
copy from operator import itemgetter from util import print_msg, print_error, NotEnoughFunds from util import profiler from bitcoin import * from account import * from version import * from transaction import Transaction from plugins import run_hook import bitcoin from synchronizer import WalletSynchronizer from mn...
Antiun/yelizariev-addons
res_users_signature/__openerp__.py
Python
lgpl-3.0
443
0.015801
{ 'name' : 'Signature templates for user emails', 'version' : '1.0.0', 'author' : 'IT-Projects LLC, Ivan Yelizariev', 'license': 'GPL-3', 'category' : 'Social Network', 'website' : 'https://yelizariev.github.io', 'depends' : ['base'], 'data':[ 'res_users_signature_views.xml', ...
rs_signature_security.xml', 'security/i
r.model.access.csv', ], 'installable': True }
ruymanengithub/vison
vison/metatests/chinj01.py
Python
gpl-3.0
34,380
0.006603
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jul 22 17:01:36 2019 @author: raf """ # IMPORT STUFF from pdb import set_trace as stop import copy import numpy as np from collections import OrderedDict import string as st import os import pandas as pd from vison.datamodel import cdp from vison.supp...
toryitem['resroot'], 'products') metafitcdp_pick = os.path.join(productspath, os.path.split(sidd.products['METAFIT_CDP'])[-1]) metafitcdp = files.cPickleRead(metafitcdp_pick) metafit = copy.deepcopy(metafitcdp['data']['ANALYSIS']) metafitkey = '%s...
tafitkey_v = np.array([metafitkey]) sidd.addColumn(metafitkey_v, 'METAFIT', IndexS, ix=0) metacdp_pick = os.path.join(productspath, os.path.split( sidd.products['META_CDP'])[-1]) # change to META_CDP metacdp = files.cPickleRead(metacdp_pick) meta = metacdp['data']['ANALYSIS...
orione7/plugin.video.streamondemand-pureita
core/scrapertools.py
Python
gpl-3.0
17,985
0.015934
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand 5 # Copyright 2015 tvalacarta@gmail.com # http://www.mimediacenter.info/foro/viewforum.php?f=36 # # Distributed under the terms of GNU General Public License v3 (GPLv3) # http://www.gnu.org/licenses/gpl-3.0.html # -...
ch.group(1) == "#": return unichr(int(ent)).encode('utf-8') else: cp = n2cp.get(ent) if cp: return
unichr(cp).encode('utf-8') else: return match.group() return entity_re.subn(substitute_entity, string)[0] def entitiesfix(string): # Las entidades comienzan siempre con el símbolo & , y terminan con un punto y coma ( ; ). string = string.replace("&aacute","&aacute;") string...
pagekite/PyPagekite
pagekite/proto/conns.py
Python
agpl-3.0
74,627
0.011457
""" These are the Connection classes, relatively high level classes that handle incoming or outgoing network connections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function ############################################################################## LICE...
self.server_info[self.S_WEBSOCKET] = ( ''.join(conn.parser.Header('Sec-WebSocket-Key')) or True) self.ProcessPageKiteHeaders(conn.parser) requests = self
.GetKiteRequests(conn.parser) except Exception as err: self.LogError('Discarding connection: %s' % err) self.Cleanup() return None except socket.error as err: self.LogInfo('Discarding connection: %s' % err) self.Cleanup() return None try: ips, seconds = conns.con...
msegado/edx-platform
openedx/core/lib/tests/test_xblock_utils.py
Python
agpl-3.0
9,421
0.00138
""" Tests for xblock_utils.py """ import uuid import ddt import six from django.conf import settings from django.test.client import RequestFactory from mock import patch from opaque_keys.edx.asides import AsideUsageKeyV1, AsideUsageKeyV2 from web_fragments.fragment import Fragment from xblock.core import XBlockAside...
ourse, view='baseview', frag=fragment, context={"wrap_xblock_data": {"custom-attribute": "custom-value"}}, usage_id_s
erializer=lambda usage_id: quote_slashes(six.text_type(usage_id)), request_token=uuid.uuid1().hex ) self.assertIsInstance(test_wrap_output, Fragment) self.assertIn('xblock-baseview', test_wrap_output.content) self.assertIn('data-runtime-class="TestRuntime"', test_wrap_output....
ktan2020/legacy-automation
win/Lib/test/test_cookielib.py
Python
mit
73,964
0.001731
# -*- coding: latin-1 -*- """Tests for cookielib.py.""" import cookielib import os import re import time from unittest import TestCase from test import test_support class DateTimeTests(TestCase): def test_time2isoz(self): from cookielib import time2isoz base = 1019227000 ...
', 'foo=bar; port="80,81"; discard, bar=baz'), (r'Basic realm="\"foo\\\\bar\""', r'Basic; realm="\"foo\\\\bar\""') ] for arg, expect in tests: input = split_header_words([arg]) res = join_head
er_words(input) self.assertEqual(res, expect, """ When parsing: '%s' Expected: '%s' Got: '%s' Input was: '%s' """ % (arg, expect, res, input)) class FakeResponse: def __init__(self, headers=[], url=None): """ headers: list of RFC822-style 'Key: value' string...
ad-m/sledzenie_listow
sledzenie_listow/public/utils.py
Python
bsd-3-clause
1,220
0.002459
from bs4 import BeautifulSoup from requests imp
ort Session from ..extensions import cache # Settings URL = 'http://emonitoring.poczta-polska.pl/wssClient.php' # Init SESSION = Session() def get_number(real_number, s=None): s = s or Session() soup = BeautifulSoup(s.post(URL, data={'n': real_number}).text.encode('utf8')) sledzenie = soup.find(id='sledz...
find(id='zadarzenia_td')} return False def quest_number(nake_number, s=None): key = "nake_number=%s" % (nake_number) rv = cache.get(key) if rv is None: for i in range(0, 10): data = get_number("00" + str(nake_number) + str(i), s) if data: rv = data ...
sunner/buzz2weibo
weibopy/error.py
Python
mit
256
0.003906
# Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. class WeibopError(Exception): """Weib
opy exception""" def __init__(self, reason): self.reason = reason.encode('utf-8') def __str__(self): return self.re
ason
flacjacket/sympy
doc/src/conf.py
Python
bsd-3-clause
6,093
0.005416
# -*- coding: utf-8 -*- # # SymPy documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 19:34:32 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickle...
ime call. today_fmt = '%B %d, %Y' # Translations: locale_dirs = ["i
18n/"] # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names...
espenak/awsfabrictasks
awsfabrictasks/tests/s3/test_api.py
Python
bsd-3-clause
1,830
0.002186
from __future__ import unicode_literals from unittest import TestCase from shutil import rmtree from tempfile import mkdtemp from os import makedirs from os.path import join, exists, dirname from awsfabrictasks.s3.api import dirlist_absfilenames from awsfabrictasks.s3.api import localpath_to_s3path from awsfabrictask...
tEquals(result, self.paths) class TestLocalpathToS3path(TestCase): def setUp(self): self.temp
dir = mkdtemp() makefile(self.tempdir, 'hello/world.txt', '') def tearDown(self): rmtree(self.tempdir) def test_localpath_to_s3path(self): s3path = localpath_to_s3path(self.tempdir, join(self.tempdir, 'hello/world.txt'), 'my/test') self.assertEquals(s3path, 'my/test/hello/world...
seecr/meresco-harvester
test/throughputanalysertest.py
Python
gpl-2.0
6,185
0.011318
## begin license ## # # "Meresco Harvester" consists of two subsystems, namely an OAI-harvester and # a web-control panel. # "Meresco Harvester" is originally called "Sahara" and was developed for # SURFnet by: # Seek You Too B.V. (CQ2) http://www.cq2.nl # # Copyright (C) 2006-2007 SURFnet B.V. http://www.surfnet.nl # ...
# it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # "Meresco Harvester" is distributed in the hope th
at 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 General Public License # along with "Meresco Harvester"; if not, write to t...
qguv/config
weechat/plugins/python/confversion.py
Python
gpl-3.0
4,417
0.010414
# -*- coding: utf-8 -*- # # Copyright (c) 2010-2010 by drubin <drubin at smartcube.co.za> # # 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 3 of the License, or # (at your option)...
ersion_commit_finish_hook # only hook timer if not already hook
ed if confversion_commit_finish_hook == 0: confversion_commit_finish_hook = weechat.hook_timer(500, 0, 1, "commit_cb_finish", "") return weechat.WEECHAT_RC_OK def commit_cb_finish(data=None, remaining=None): global confversion_commit_finish_hook # save before doing commit weechat.command(...
nmercier/linux-cross-gcc
win32/bin/Lib/email/errors.py
Python
bsd-3-clause
1,685
0.005341
# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """email package exception classes.""" class MessageError(Exception): """Base class for errors in the email package.""" class MessageParseError(MessageError): """Base class for message...
arameter.""" class StartBoundaryNotFoundDefect(MessageDefect): """The claimed start boundary was never found.""" class FirstHeaderLineIsContinuationDefect(MessageDefect): """A message had a continuation line as its first header line.""" class MisplacedEnvelopeHeaderDefect(MessageDefect): """A 'U...
ng a colon, or was otherwise malformed.""" class MultipartInvariantViolationDefect(MessageDefect): """A message claimed to be a multipart but no subparts were found."""
bendykst/deluge
deluge/core/eventmanager.py
Python
gpl-3.0
2,071
0.001931
# -*- coding: utf-8 -*- # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # import...
ame]: # log.debug("Running handler %s for event %s with args: %s", event.name, handler, event.args) try: hand
ler(*event.args) except Exception as ex: log.error("Event handler %s failed in %s with exception %s", event.name, handler, ex) def register_event_handler(self, event, handler): """ Registers a function to be called when a `:param:event` is emitted. :para...
PLNech/thefuck
thefuck/shells/generic.py
Python
mit
2,400
0.000417
import io import os import shlex import six from ..utils import memoize from ..conf import settings class Generic(object): def get_aliases(self): return {} def _expand_aliases(self, command_script): aliases = self.get_aliases() binary = command_script.split(' ')[0] if binary i...
get_history_lines(self): """Returns list of history entries.""" history_fi
le_name = self._get_history_file_name() if os.path.isfile(history_file_name): with io.open(history_file_name, 'r', encoding='utf-8', errors='ignore') as history_file: lines = history_file.readlines() if settings.history_limit: ...
kg-bot/SupyBot
plugins/Gateway/gwcred.py
Python
gpl-3.0
5,416
0.003693
### # Copyright (c) 2005, Ali Afshar # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, a...
lic key checker """ __implements__ = (checkers.ICredentialsChecker,) credentialInterfaces = (ISSHPrivateKey,) def requestAvatarId(self, credentials): a = self.cb.getUser(protocol=self.cb.PROTOCOL, username=credentials.username, blob=credentials.blob, ...
e: return failure.Failure(error.UnauthorizedLogin()) #class SBPublicKeyChecker(SSHPublicKeyDatabase): # credentialInterfaces = ISSHPrivateKey, # __implements__ = ICredentialsChecker # # def requestAvatarId(self, credentials): # if not self.checkKey(credentials): # return defer.fa...
deets/raspberry-racer
python/setup.py
Python
mit
559
0.014311
from setuptools import setup, find_packages setup( name="RaspberryRacer", version="0.1", description="Raspberry Racer", author="Diez B. Roggisch", author_email="deets@web.de", entry_points= { 'console_scripts' : [ 'rracer = rracer.main:main', ]}, install...
], zip_safe=True, packages=find_pac
kages(), classifiers = [ 'Development Status :: 3 - Alpha', 'Operating System :: OS Independent', 'Programming Language :: Python', ], )
inbloom/legacy-projects
lri-middleware/ccss/insert.py
Python
apache-2.0
56,321
0.003196
############################################################################### # Insert ############################################################################### # 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 ...
Update(opts, data) elif ccssType == "/anchor_standard": if action == "/create": insert = AnchorCreate(opts, data) elif action == "/update": insert = AnchorUpdate(opts, data) elif ccssType == "/competency_path": web.debug("CreateInsert...
ched on action: %s" % action) insert = PathCreate(opts, data) else: raise web.NoMethod() elif ccssType == "/learning_resource": if action == "/create": insert = ResourceCreate(opts, data) else: raise web.NoMetho...
snowch/spark-cloudant
test/helpers/dataload.py
Python
apache-2.0
3,656
0.033643
#******************************************************************************* # Copyright (c) 2015 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 Licen...
************/ import requests import sys import os import json from helpers.dbutils import CloudantDbUtils from helpers.acmeair_utils import AcmeAirUtils import conftest # get the cloudant credentials from pytest config file test_properties = conftest.test_properties() class DataLoader: """ Test data loader relat...
rahulunair/nova
nova/objects/network.py
Python
apache-2.0
9,406
0
# Copyright 2014 Red Hat, 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 a...
ls._from_db_object(context, cls(), db_network) @obj_base.remotable_classmethod def get_by_uuid(cls, context, network_uuid): db_network = db.network_get_by_uuid(context, network_uuid) return cls._from_db_object(context, cls(), db_network) @obj_base.remotable_classmethod def get_by_cidr(...
and can be removed @obj_base.remotable_classmethod def associate(cls, context, project_id, network_id=None, force=False): db.network_associate(context, project_id, network_id=network_id, force=force) # TODO(stephenfin): This is no longer used and can be removed @ob...
noyainrain/micro
micro/error.py
Python
lgpl-3.0
1,216
0.007401
# micro # Copyright (C) 2021 micro contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU # Les
ser 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with this program. # If not, see <http://www.gnu.org/licenses/>. """micro errors.""" import builtins from typing imp...
joeythesaint/yocto-autobuilder
lib/python2.7/site-packages/autobuilder/buildsteps/BuildImages.py
Python
gpl-2.0
2,787
0.0061
''' Created on Jan 6, 2013 __author__ = "Elizabeth 'pidge' Flanagan" __copyright__ = "Copyright 2012-2013, Intel Corp." __credits__ = ["Elizabeth Flanagan"] __license__ = "GPL" __version__ = "2.0" __maintainer__ = "Elizabeth Flanagan" __email__ = "elizabeth.flanagan@intel.com" ''' from buildbot.steps.shell import Sh...
nd make sure we're on poky >1.7 if self.getProperty('bitbakeversion') and StrictVersion(self.getProperty('bitbakeversion')) >= StrictVersion("1.25"): bitbakeflags += "-w " self.command = ". ./oe-init-build-env; bitbake " + bitbakeflags + self.images self.description =...
str(self.images)] ShellCommand.start(self) def describe(self, done=False): description = ShellCommand.describe(self, done) if self.layerversion_yoctobsp is not None and int(self.layerversion_yoctobsp) < 2 and self.machine is not None and self.machine == "genericx86-64": descrip...
cangencer/hazelcast-python-client
hazelcast/protocol/codec/replicated_map_remove_entry_listener_codec.py
Python
apache-2.0
1,220
0.001639
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.replicated_map_message_type import * REQUEST_TYPE = REPLICATEDMAP_REMOVEENTRYLISTENER RESPO...
load size""" data_size = 0 data_size += calculate_
size_str(name) data_size += calculate_size_str(registration_id) return data_size def encode_request(name, registration_id): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, registration_id)) client_message.set_message_type(REQUEST_TYPE) ...
Djacket/djacket
core/backend/repository/admin.py
Python
mit
269
0.003717
from django.contrib import admin from repository.models import Repository, RepositoryAccess, RepositoryStar, R
epositoryFork admin.site.register(Repository) admin.site.register(RepositoryStar) admin.site.register(RepositoryFork) admin.
site.register(RepositoryAccess)
uArm-Developer/pyuarm
pyuarm/__init__.py
Python
mit
215
0.004651
import sys if sys.version > '3': PY3 = True else: PY3 = False from .uarm import UArm, UArmConnectExc
eption from .config import ua_dir, home_dir from .util import get_uarm from .ver
sion import __version__
zentralopensource/zentral
zentral/core/compliance_checks/__init__.py
Python
apache-2.0
1,092
0.001832
import logging from zentral.core.exceptions import ImproperlyConfigured default_app_config = "zentral.core.compliance_checks.apps.ZentralComplianceChecksAppConfig" logger = logging.getLogger("zentral.core.compliance_checks") # compliance checks classes compliance_check_classes = {} def register_compliance_che...
perlyConfigured(f'Compliance check class "{model}" already registered') compliance_check_classes[model] = compliance_check_
class logger.debug('Compliance check class "%s" registered', model) def compliance_check_class_from_model(model): try: return compliance_check_classes[model] except KeyError: logger.error('Unknown compliance check model "%s"', model) # BaseComplianceCheck registered in .compliance_...
eduardomallmann/vim-and-bash
pythonx/UltiSnips/text_objects/_visual.py
Python
gpl-3.0
2,074
0.000965
#!/usr/bin/env python # encoding: utf-8 """A ${VISUAL} placeholder that will use the text that was last visually selected and insert it here. If there was no text visually selected, this will be the empty string. """ import re import textwrap from UltiSnips import _vim from UltiSnips.indent_util import IndentUtil fr...
text = text[:-
1] # Strip final '\n' text = self._transform(text) self.overwrite(text) self._parent._del_child(self) # pylint:disable=protected-access return True
Vdragon/git-cola
qtpy/_version.py
Python
gpl-2.0
72
0
version_info = (1, 4,
2) __version__ = '.'.join(map
(str, version_info))
rosenvladimirov/addons
currency_rate_update_bg/services/currency_getter.py
Python
agpl-3.0
2,676
0.001121
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2009 CamptoCamp. All rights reserved. # @author Nicolas Bessi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Publi...
', '
MX_BdM_getter', 'CA_BOC_getter', 'RO_BNR_getter', 'BG_CUSTOMS_getter', 'BG_SIBANK_getter', 'BG_UNICRDT_getter', ] if class_name in allowed: exec "from .update_service_%s import %s" % (class_name.replace('_getter', ''), class_name) ...
xieta/mincoin
qa/rpc-tests/test_framework/mininode.py
Python
mit
55,509
0.00191
#!/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 # Copyright (c) 2013-2019 The Mincoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.op...
urn r def ser_string_vector(l): r = ser_compact_size(len(l)) for sv in l: r += ser_string(sv) return r def deser_int_vector(f): nit = deser_compact_size(f) r = [] for i in range(nit): t = struct.unpack("<i", f.read(4))[0] r.append(t) return r def ser_int_vector(...
ing representation (eg from RPC) def FromHex(obj, hex_string): obj.deserialize(BytesIO(hex_str_to_bytes(hex_string))) return obj # Convert a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj): return bytes_to_hex_str(obj.serialize()) # Objects that map to mincoind objects, which ...
okoye/spinnaker-monitoring
spinnaker-monitoring-daemon/spinnaker-monitoring/spectator_handlers.py
Python
apache-2.0
16,780
0.007867
# Copyright 2016 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 a...
umns, service_tag_map): tag_service_map = {} for service, tags in service_tag_map.items(): service_index = columns[service] for tag_group in tags: for tag_name, tag_value in tag_group.items(): if tag_name not in tag_service_map: tag_service_map[tag_name] = [set() for i...
header_html = ['<tr>', '<th>Metric</th>', '<th>Label</th>'] columns = {} for service_name in sorted(active_services): columns[service_name] = len(columns) header_html.append('<th><A href="/show?services={0}">{0}</A></th>'.format( service_name)) header_html.append('</tr>') htm...
mysql/mysql-utilities
mysql-test/suite/replication/t/binlog_purge_ms.py
Python
gpl-2.0
4,696
0
# # Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. # # 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; version 2 of the License. # # This program is distributed in the hope...
pat(5, 7, 6): raise MUTLibError("Test requires server version 5.7.6 or later") return self.check_num_servers(1) def setup(self): self.res_fname = "result.txt" res = super(test, self).setup() if not res: return False # Setup multiple channels for slave...
master.exec_query("SET SQL_LOG_BIN= 0") master.exec_query("GRANT REPLICATION SLAVE ON *.* TO 'rpl'@'{0}' " "IDENTIFIED BY 'rpl'".format(self.server1.host)) master.exec_query("SET SQL_LOG_BIN= 1") self.server1.exec_query("SET GLOBAL relay_log_info_repository...
google/mirandum
alerts/fanfunding/migrations/0003_auto_20160416_2023.py
Python
apache-2.0
2,470
0.002429
# -*- coding: utf-8 -*- # Copyright 2016 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 # # Un...
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__...
('fanfunding', '0002_auto_20160416_0621'), ] operations = [ migrations.RenameField( model_name='fanfundingevent', old_name='ffu', new_name='updater', ), migrations.RemoveField( model_name='fanfundingevent', name='funding_id', ...
rhyolight/nupic.son
app/soc/mapreduce/convert_student_info.py
Python
apache-2.0
1,918
0.008342
# Copyright 2011 the Melange 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 wr...
d 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. """GSoCStudentInfo updating MapReduce.""" import logging from mapreduce import operation # MapReduce requires these...
to have been imported. # pylint: disable=unused-import from soc.models.user import User from soc.modules.gsoc.models.profile import GSoCStudentInfo from soc.modules.gsoc.models.proposal import GSoCProposal from soc.modules.gsoc.models.project import GSoCProject # pylint: enable=unused-import def process(student_info...
sparkslabs/guild
examples/dogs_go_woof_actors.py
Python
apache-2.0
988
0.001012
#!/usr/bin/python from __future__ import print_function from guild.actor import Actor, actor_method, process_method, late_bind class Dog(Actor): @actor_method # Input - triggered by data coming in def woof(self): print("Woof", self) @process_method # Process - tr
iggered each time it's run def process(self): #print(" ", end="") pass @late_bind # Output def produce(self): pass class Shitzu(Dog): def __init__(self): self.count = 0 super(Dog, self).__init__() @process_method def process(self):
self.count += 1 print("I don't go meow", self.count) if self.count >= 20: self.stop() return False if __name__ == "__main__": import time dog = Dog() shitzu = Shitzu() dog.start() shitzu.start() dog.woof() shitzu.woof() time.sleep(0.1)...
muehlburger/gnucash
gnucash/python/init.py
Python
gpl-2.0
4,709
0.014865
import sys from gnucash import * from gnucash import _sw_app_utils from gnucash import _sw_core_utils from gnucash._sw_core_utils import gnc_prefs_is_extra_enabled, gnc_prefs_is_debugging_enabled from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk import os sys.path.append(os.pat...
Console.__init__(self, argv, shelltype, banner, filename, size, user_local_ns=user_local_ns, user_global_ns=user_global_ns) self.buffer.create_tag('center', justification=Gtk.Justification.CENTER, font='Mono 4') self.f...
ct ('key-press-event', self.key_press_event) self.view.connect ('button-press-event', self.button_press_event) self.view.connect ('scroll-event', self.scroll_event) def key_press_event (self, widget, event): """ Handle key press event """ if self.active_canvas: ...
antchain/antchain.org
web/ads.py
Python
mit
10,223
0.043138
# -*- coding:utf-8 -*- import math import web import tx def GetAdsPagination(assetid,page) : html = '' html = html + '<div name="pages" align="center">\n' if assetid != None : count = web.collection_ads.find({"asset":assetid}).count() else : count = web.collection_ads.find({"asset":{"$ne":"0"}}).count() ...
ages - 9 displayend = pages else : if pages <= 9 : displayend = pages else : displayend = displaystart + 9 if assetid != None : html = html + '<a href="/address/' + assetid + '/page/' + str(1) + '"><<</a> ' else : html = html + '<a href="/address/page/' + str(1) + '"><<</a> ' for i in range(display...
ref="/address/' + assetid + '/page/' + str(i) + '">' + str(i) + '</a> ' else : html = html + '<a href="/address/page/' + str(i) + '">' + str(i) + '</a> ' else : html = html + str(i) + ' ' if assetid != None : html = html + '<a href="/address/' + assetid + '/page/' + str(pages) + '">>></a> ' else : ht...
rdevon/cortex
cortex/_lib/utils.py
Python
bsd-3-clause
2,635
0
'''Utility methods ''' import logging import os import numpy as np import torch __author__ = 'R Devon Hjelm' __author_email__ = 'erroneus@gmail.com' logger = logging.getLogger('cortex.util') try: _, _columns = os.popen('stty size', 'r').read().split() _columns = int(_columns) except ValueError: _colum...
): fro
m sklearn.manifold import TSNE tsne = TSNE(2, perplexity=perplexity, n_iter=n_iter, init=init) points = X.tolist() return tsne.fit_transform(points)
muk-it/muk_dms
muk_dms_view/controllers/__init__.py
Python
lgpl-3.0
1,019
0.003925
################################################################################### # # Copyright (c) 2017-2019 MuK IT GmbH. # # This file is part of MuK Documents View # (see https://mukit.at). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Less...
es/>. # ################################################################
################### from . import main from . import backend
menren/openshift-ansible
roles/lib_zabbix/library/zbx_trigger.py
Python
apache-2.0
8,027
0.00436
#!/usr/bin/env python ''' ansible module for zabbix triggers ''' # vim: expandtab:tabstop=4:shiftwidth=4 # # Zabbix trigger ansible module # # # Copyright 2015 Red Hat Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
ict(default=None, type='str'), name=dict(default=Non
e, type='str'), description=dict(default=None, type='str'), dependencies=dict(default=[], type='list'), priority=dict(default='avg', type='str'), url=dict(default=None, type='str'), status=dict(default=None, type='str'), state=dict(default='present...
eredmiles/GeneralDataScienceToolsDSSG2015
WorldBank2015/Code/data_pipeline_src/supplier_feature_gen.py
Python
mit
24,730
0.016781
import pandas as pd from datetime import date, timedelta import time import numpy as np import re import psycopg2 import ConfigParser import argparse from sqlalchemy import create_engine import random import sql parser = argparse.ArgumentParser() parser.add_argument('-cf','--contract_file',help='Contract data file') ...
name="world_bank") return con def snake_case(name): """Clean entity name strings""" remove_list = ['llc','ltd','llc','ltd','co','corporation','srl','nv','limited','pvtltd'] remove = '|'.join(remove_list) regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE) try: s1 =...
egex.sub("", s1) s1 = s1.strip() s1 = re.sub(' +','_',s1) s1 = re.sub('-','_',s1) s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s1) s1 = s1.replace('*','') s1 = s1.replace('(','') s1 = s1.replace(')','') s1 = s1.replace('"','') s1 = s1.replace(',','')...
cliffano/swaggy-jenkins
clients/python-experimental/generated/openapi_client/api/remote_access_api.py
Python
mit
2,651
0.006413
# coding: utf-8 """ Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification # noqa: E501 The version of the OpenAPI document: 1.1.2-pre.0 Contact: blah@cliffano.com Generated by: https://openapi-generator.tech """ from openapi_client.api_client import ApiClient from o...
teItem, PostCreateView, PostJobBuild, PostJobConfig, P
ostJobDelete, PostJobDisable, PostJobEnable, PostJobLastBuildStop, PostViewConfig, ApiClient, ): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ pass
wenbinli/rl
cliffWalk_QL.py
Python
mit
6,866
0.026507
# solve cliff-walking task with Q-Learning, very similar to SARSA # original example problem from the book, introduction for reinforcement learning # Author: Wenbin Li # numeric backend import pygame from pygame.locals import * import numpy as np grid_size = 100 n_row = 4 n_col = 12 state = np.zeros((n_row * grid_siz...
next s_r = start_r s_c = start_c while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # draw gridworld background draw_bg(bg,n_row,n_col,grid_size,start_r,start_c,goal_r,goal_c) screen.blit(bg,(0,0)) # draw the state of...
ion function to find a optimal policy # in the loop, should provide a step function #print (s_r,s_c) s_r_next,s_c_next = step_q(q,s_r,s_c,n_row,n_col) #print (s_r_next,s_c_next) if s_r_next != goal_r or s_c_next != goal_c: pygame.draw.circle(surface,(255,255,255),(s_c_next * grid_size + g...
glogiotatidis/mozillians-new
mozillians/funfacts/tests/test_helpers.py
Python
bsd-3-clause
563
0
from mock import patch from nose.tools import eq_ from test_utils import TestCase from mozillians.funfacts.helpers import random_funfact from mozill
ians.funfacts.tests import FunFactFactory class HelperTests(TestCase): @patch('mozillians.funfacts.helpers.FunFact.objects') def test_helper_calls_random(self, funfact_mock): funfact_mock.objects.random.assert_called() def test_helper_returns_none(self): """Test helper returns None when ...
" FunFactFactory.create() eq_(random_funfact(), None)
eeue56/code-golf
game-of-life/game_of_life.py
Python
bsd-3-clause
957
0.018809
z = len u = x = y = r = 0 def v(): global u if z(r) < 3: if y < 1: c, n = r else: n, c = r s = 0 else: l, c, n = r s = l[x - 1] + l[x] + (l[x+1] if x == z(l) else 0) u = s + {x : sum(c[x - 1:x+2] + n[x - 1:x + 2]) - c[x], 0 : n[0] ...
open(w)] n = range(1, z(m)) r = m[0:2] v() e = [{u:0,2: r[0][0], 3: 1}[u]] for x in n: v() a(e, {u:0,2: r[1][x], 3: 1}[u]) o = [e] for y in n: r = m[y - 1:y + 2] x = 0 v() e = [{u:0,2: r[1][1], 3: 1}[u]] for x in n: ...
[u]) a(o, e) f = open(w, 'w') f.write('\n'.join(''.join(map(str, q)) for q in o))
Jgarcia-IAS/Fidelizacion_odoo
openerp/addons/auth_ldap/users_ldap.py
Python
agpl-3.0
10,747
0.002885
############################################################################## # # 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 Affero General Publ...
ers :rtype: dict """ values = { 'name': ldap_entry[1]['cn'][0], 'login': login, 'company_id': conf['company'] }
return values def get_or_create_user(self, cr, uid, conf, login, ldap_entry, context=None): """ Retrieve an active resource of model res_users with the specified login. Create the user if it is not initially found. :param dict conf: LDAP configuratio...
timcera/tsgettoolbox
docs/conf.py
Python
bsd-3-clause
8,064
0.001736
# -*- coding: utf-8 -*- # # TSgettoolbox documentation build configuration file, created by # sphinx-quickstart on Mon Jun 10 23:11:56 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
stom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of ...
o use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "defau...
mahim97/zulip
zerver/webhooks/gogs/tests.py
Python
apache-2.0
7,893
0.003547
# -*- coding: utf-8 -*- from typing import Optional, Text from mock import MagicMock, patch from zerver.lib.test_classes import WebhookTestCase from zerver.lib.webhooks.git import COMMITS_LIMIT class GogsHookTests(WebhookTestCase): STREAM_NAME = 'commits' URL_TEMPLATE = "/api/v1/external/gogs?&api_key={api_k...
ters(self) -> None: commit_info = u'* Webhook Test ([d8fce16](http://localhost:3000/john/try-git/commit/d8fce16c72a2ff56a5afc8a08645a6ce45491794))\n' expected_subject = u"try-git / master" expected_messa
ge = u"""john [pushed](http://localhost:3000/john/try-git/compare/479e6b772b7fba19412457483f50b201286d0103...d8fce16c72a2ff56a5afc8a08645a6ce45491794) 2 commits to branch master. Commits by Benjamin (1) and John (1).\n\n{}* Webhook Test ([d8fce16](http://localhost:3000/john/try-git/commit/d8fce16c72a2ff56a5afc8a08645a6...
orontee/porte-monnaie
site/tracker/tests/test_views.py
Python
gpl-3.0
19,399
0
"""Tests for views of tracker application.""" from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.test import TestCase from tracker.models import (Expenditure, Purse) User = get_user_model() class HomeTest(TestCase): """Test home view.""" def setUp(self): ...
token} response = self.client.post(self.url, data) self.assertEqual(response.status_code, 302) url = self.url + '?date=2014-05-25' self.assertEqual(response.ur
l, url) self.assertEqual(u.expenditure_set.count(), 1) def test_post_with_multiple_occurence(self): """Get page then post to create multiple expenditures.""" credentials = {'username': 'username', 'password': 'password'} u = create_user(**credentials) ...
robmcmullen/peppy
editra.in/syntax/pike.py
Python
gpl-2.0
3,246
0.005237
############################################################################### # Name: pike.py # # Purpose: Define highlighting/syntax for Pike programming language # # Author: Cody Precord <cprecord@editra.org> # ...
IKE: return cpp.Properties(synglob.ID_LANG_CPP) else: return list() def CommentPattern(lang_id=0): """Returns a list of characters used to comment a block of code @keyword lang_id: used to select a specific sub
set of comment pattern(s) """ if lang_id == synglob.ID_LANG_PIKE: return cpp.CommentPattern(synglob.ID_LANG_CPP) else: return list() #---- End Required Module Functions ----# AutoIndenter = cpp.AutoIndenter #---- Syntax Modules Internal Functions ----# def KeywordString(): """Returns...
jmschrei/yabn
yabn/__init__.py
Python
mit
1,279
0.009382
# __init__.py: Yet Another Bayes Net library # Contact: Jacob Schreiber ( jmschreiber91@gmail.com ) """ For detailed documentation and examples, see the README. """ # Make our dependencies explicit so compiled Cython code won't segfault trying # to load them
. import networkx, matplotlib.pyplot, scipy import numpy as np import os import pyximport # Adapted from Cython docs https://github.com/cython/cython/wiki/ # InstallingOnWindows#mingw--numpy--pyximport-at-runtime if os.name == 'nt': if 'CPATH' in os.environ: os.environ['CPATH'] = os.environ['CPATH'] + ...
in C:\MinGW (default) if 'PATH' in os.environ: os.environ['PATH'] = os.environ['PATH'] + ';C:\MinGW\bin' else: os.environ['PATH'] = 'C:\MinGW\bin' mingw_setup_args = { 'options': { 'build_ext': { 'compiler': 'mingw32' } } } pyximport.install(setup_args=mingw_setup_args) elif os.name ==...
neillc/zookeepr
zkpylons/controllers/secret_hash.py
Python
gpl-2.0
4,319
0.005094
##### import sys import inspect from pylons import config import logging import zkpylons.lib.helpers as h from pylons import request, response, session, tmpl_context as c from zkpylons.lib.helpers import redirect_to from pylons.util import class_name_from_module_name from zkpylons.model import meta from pylons.control...
replace("/", ".") if (action == None): action = match_route["action"] # if del(match_route["controller"])
del(match_route["action"]) kwargs.update(match_route) else: controller = controller.replace("/", ".") if (action == None): action = "index" # if # if # if full_module_name = config['...
kmike/DAWG-Python
tests/utils.py
Python
mit
479
0.004175
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import zipfile DEV_DATA_PATH = os.path.join( os.path.dirname(__file__), '..',
'dev_data', ) def data_path(*args): """ Returns a path to dev data """ return os.path.join(DEV_DATA_PATH, *args) def words100k(): zip_name = data_path('words100k.txt.
zip') zf = zipfile.ZipFile(zip_name) txt = zf.open(zf.namelist()[0]).read().decode('utf8') return txt.splitlines()
omco/mpir
yasm/tools/python-yasm/pyxelator/genpyx.py
Python
lgpl-3.0
18,513
0.022471
#!/usr/bin/env python """ genpyx.py - parse c declarations (c) 2002, 2003, 2004, 2005 Simon Burton <simon@arrowtheory.com> Released under GNU LGPL license. version 0.xx This is a module of mixin classes for ir.py . Towards the end of ir.py our global class definitions are remapped to point to the class definitions ...
_toks=[] names = kw.get('names',{}) kw['names'] = names tag_lookup = kw.get('tag_lookup') if self.tag: tag=self.tag.name else: tag = '' if isinstance(self,Struct): descr = 'struct' elif isinstan
ce(self,Union): descr = 'union' _node = names.get(self.tag.name,None) if ( _node is not None and _node.has_members() ) or \ ( _node is not None and not self.has_members() ): descr = '' # i am not defining myself here #print "Compound.pyxstr", tag #...
sbg/sevenbridges-python
sevenbridges/models/user.py
Python
apache-2.0
2,815
0
import logging from sevenbridges.meta.resource import Resource from sevenbridges.meta.fields import HrefField, StringField from sevenbridges.meta.transformer import Transform logger = logging.getLogger(__name__) class User(Resource): """ Central resource for managing users. """ _URL = { 'me'...
e) username = StringField(read_only=True) email = StringField(read_only=True) first_name = StringField(read_only=True) last_name = StringField(read_only=True) affiliation = StringField(read_only=True) phone = StringField(read_only=True) address = StringF
ield(read_only=True) state = StringField(read_only=True) country = StringField(read_only=True) zip_code = StringField(read_only=True) city = StringField(read_only=True) role = StringField(read_only=True) def __eq__(self, other): if type(other) is not type(self): return False...
funkypawz/MakerRobot
peewee-master/playhouse/tests/test_apsw.py
Python
gpl-3.0
4,048
0.002223
import apsw import datetime from playhouse.apsw_ext import * from playhouse.tests.base import ModelTestCase db = APSWDatabase(':memory:') class BaseModel(Model): class Meta: database = db class User(BaseModel): username = CharField() class Message(BaseModel): user = ForeignKeyField(User) m...
me__in=['u1', 'u3'])], ['u1', 'u3']) dt = datet
ime.datetime(2012, 1, 1, 11, 11, 11) Message.create(user=User.get(username='u1'), message='herps', pub_date=dt, published=True) Message.create(user=User.get(username='u2'), message='derps', pub_date=dt, published=False) m1 = Message.get(message='herps') self.assertEqual(m1.user.username...
pulkitpahwa/smart-image-coordinates
smarter/base/views.py
Python
mit
9,603
0.001041
from django.shortcuts import render_to_response, get_object_or_404 from django.http import JsonResponse, HttpResponseRedirect from django.template import RequestContext from django.core.urlresolvers import reverse from django.views.decorators.csrf import csrf_exempt from django.db.models import Avg from django.db impor...
context_instance=RequestContext(request)) elif request.method == "POST": form = CreateCategoryForm(data=request.POST) if not form.is_
valid(): return render_to_response("create_category.html", {"form": form, "errors": form.errors}, context_instance=RequestContext(request)) try: category = Category.objects.create( categor...
Yipit/pyeqs
tests/unit/test_connection.py
Python
mit
4,100
0.002439
# -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a querys...
ponse. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t =...
ction_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, ...
cga-harvard/cga-worldmap
geonode/sitemap.py
Python
gpl-3.0
398
0.005025
from django.contrib.sitemaps import Sitemap from geonode.maps.models import Layer, Map class LayerSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Layer.objects.all() de
f lastmod
(self, obj): return obj.date class MapSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Map.objects.all()
google-research/google-research
smu/parser/smu_atomic_input_verifier.py
Python
apache-2.0
2,945
0.006452
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
riter_lib
.DatFormatMismatchError as e: mismatches += 1 print(e) if FLAGS.output_dir: with gfile.GFile( os.path.join( FLAGS.output_dir, atomic_writer.get_filename_for_atomic_input(conformer)), 'w') as f: f.write(actual_c...
lm-tools/situational
situational/apps/travel_report/migrations/0001_initial.py
Python
bsd-3-clause
1,406
0.002845
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import jsonfield.fields import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('travel_times', '0002_auto_20150717_1221'), ] operatio...
('id', models.AutoField(primary_key=True, serialize=False, auto_cre
ated=True, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(editable=False, default=django.utils.timezone.now, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(editable=False, default=django.utils.timezone.now, verbose_name='modified')),...
dmlc/tvm
python/tvm/topi/math.py
Python
apache-2.0
15,214
0.000329
# 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...
i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def isinf(x): """Check if value of x is infinite, element-wise. Parameters ---------- x : tvm
.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.isinf(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def round(x): """Round elements of x to nearest in
opentext/storyteller
docplatform/distribution/py/pfdesigns/javascript/lint.py
Python
apache-2.0
1,390
0.010791
import docapi import docbuilder import testtools g_trace = """\ lint-syntax.js:3:32 JSLintWarning: Unexpected trailing space. lint-syntax.js:7:10 JSLintWarni
ng: Redefinition of 'some_function' from line 2. lint-syntax.js:8:16 JSLintWarning: Expected '{' and instead saw 'return'. lint-syntax.js:9:2 JSLintWarning: Use spaces, not tabs. lint-semantics.js:
3:10 JSLintWarning: Unused 'find_key'. lint-semantics.js:3:20 JSLintWarning: Unexpected space between '(' and 'obj'. lint-semantics.js:3:29 JSLintWarning: Unexpected space between 'val' and ')'. lint-semantics.js:5:5 JSLintWarning: Unexpected 'for'. lint-semantics.js:5:8 JSLintWarning: Expected one space betwee...
brake/python-utl
utl/files.py
Python
mit
6,385
0.000783
#!/usr/bin/env python # -*- coding: UTF-8 -*- # ------------------------------------------------------------------------------ # Name: files.py # Package: utl # Project: utl # # Created: 10.10.13 11:37 # Copyright 2013-2016 © Constantin Roganov # License: The MIT License # ---------------------------------...
ead, line
s_total, lines_processed)) ... progress_co.send(lines_saved) # finalizing work Generates output data in format produced by parse_line() """ files = None if iterable is None else lines_stripped(iterable) inp = fileinput.input(files=files) pth, name, lines_total = (None...
ARTbio/tools-artbio
scripts/helper_scripts/rename_history_items/rename_hist_items.py
Python
mit
2,334
0.008997
#!/usr/bin/env python2.7 from bioblend.galaxy import GalaxyInstance import requests import datetime import argparse requests.packages.urllib3.disable_warnings() def parse_args(): args = argparse.ArgumentParser(description="Rename history items using a tabular file." +"\n" + "Ex...
e, help="url of galaxy instance") args.add_argument("-key", "--api_key", required=True, help="api key for galaxy instance" ) args.add_argument("-hid", "--history_id", required=True, help="History id of hitory containing files to be renamed") args.add_argument("-table", "--rename_table", required=True, type=...
erated file with first column current filename,\ and second column the desired name") return args.parse_args() def return_datetime(string_representation): """ returns current time, to find last modified history. Currently ununsed, may be used in the future. """ date, ...
ATNF/askapsdp
Tools/Dev/rbuild/askapdev/rbuild/dependencies/dependency.py
Python
gpl-2.0
18,614
0.005104
## @file # Module to gather dependency information for ASKAP packages # # @copyright (c) 2006 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ASKAP ...
malte.marquarding@csiro.au> # import glob import os import socket import askapdev.rbuild.utils as utils from ..exceptions import BuildError from ordereddict import OrderedDict ## An object to hold information about a dependency tree for a nominated package # This package can be added manually, or if None specified,...
the information # will be taken from a file 'dependencies.{default,hostname}' in the current # directory. # # Example: # @code # f = file("dependencies.default") # f.write("numpy=3rdParty/numpy/numpy-1.0.2;==1.0.2\n") # f.close() # from askapdev.rbuild.dependencies import Dependency # dep = Dependency() # dep....
runekaagaard/django-contrib-locking
django/contrib/gis/db/backends/postgis/operations.py
Python
bsd-3-clause
15,371
0.001106
import re from django.conf import settings from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geometry.backend import Geometry...
= prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = prefix + 'Union' self.unionagg = prefix + 'Union' # Followin
g "attributes" are properties due to the spatial_version check and # to delay database access @property def extent3d(self): if self.spatial_version >= (2, 0, 0): return self.geom_func_prefix + '3DExtent' else: return self.geom_func_prefix + 'Extent3D' @property ...
raildo/python-keystoneclient
python-keystoneclient-0.4.1.7.gdca1d42/keystoneclient/service_catalog.py
Python
apache-2.0
11,013
0
# Copyright 2011 OpenStack Foundation # Copyright 2011, Piston Cloud Computing, Inc. # Copyright 2011 Nebula, 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 # #...
for endpoint in endpoints: if (self.region_name and endpoint.get('region') != self.region_name): continue
if not filter_value or endpoint.get(attr) == filter_value: return endpoint[endpoint_type] raise exceptions.EndpointNotFound('%s endpoint for %s not found.' % (endpoint_type, service_type)) class ServiceCatalogV3(ServiceCatalog): """An obj...
incuna/incuna-test-utils
tests/testcases/test_api_request.py
Python
bsd-2-clause
918
0
from django.test import override_settings from incuna_test_utils.testcases.api_request import ( BaseAPIExampleTestCase, BaseAPIRequestTestCase, ) from tests.factories import UserFactory class APIRequestTestCase(BaseAPIRequestTestCase): user_factory = UserFactory def test_create_request_format(self):
request = self.create_request() assert request.META['format'] == 'json' def test_create_request_auth(self): request = self.create_request() assert request.user.is_authenticated def test_create_request_no_auth(self): request = self.create_request(auth=False) asser...
ExampleTestCase): @override_settings(ALLOWED_HOSTS=['localhost']) def test_create_request(self): request = self.create_request(auth=False) assert request.get_host() == self.SERVER_NAME
nsi-iff/nsi_site
apps/members/views.py
Python
mit
1,044
0.003831
from django.shortcuts import render_to_response from django
.template import RequestContext from apps.members.models import Member def show_all_current_members(request): members = Member.objects.filter(is_renegade=False).order_by('function', 'started_nsi_date') return render_to_response( 'show_all_current_members.html', {'members': members}, co...
equest, slug): member = Member.objects.get(slug=slug) participation_list = member.participation_set.all() members = Member.objects.all() return render_to_response( 'show_member.html', {'member': member, 'participation_list': participation_list, 'members': members}, context_instan...
jhl667/galaxy_tools
tools/jhl_tools/send_to_cgd.py
Python
apache-2.0
2,897
0.007249
#!/usr/bin/env python ### <command interpreter="python">send_to_cgd.py ### $pipeline_output $endpoint $cgd_url $output $runid $barcodeid $qcversion ### </command> ### Galaxy wrapper for cgd_client.jar. ### CGD_CLIENT is hard coded, but this is not expected to move. import argparse import subprocess from subproc...
mentParser(description='') parser.add_argument("--pipeline_out", help='') parser.add_argument("--cgd_url", help='') parser.add_argument(dest='stdout_log', help='') parser.add_argument(dest='endpoint', help='') parser.add_argument("--runid", help='') parser.add_argumen
t("--barcodeid", help='') parser.add_argument("--qcversion", help='') args = parser.parse_args() if args.endpoint != "none": newfile = renameOutput(args.runid, args.barcodeid, args.endpoint) else: id_list = splitUrl(args.cgd_url, 3) newfile = renameOutput(id_list[1], id_list[2]...
LightStage-Aber/LightStage-Repo
exp/Lettvin_Repulsion/helpers/parse_diffuse_results_to_obj_file.py
Python
apache-2.0
1,750
0.017714
""" Module to parse a Lettvin Results File C array of vertex points (and distances) into an OBJ file format of vertex points. arg1: the path to the results file. (File must exist) arg2: the file extension of the output OBJ filename. (e.g. ".obj") Default is ".obj" (File must not exist) Vertex ...
assert os.path.exists( path ) , "Input file does not exist, aborting.\nFilename: "+str(path) file_extension = sys.argv[2] if sys.argv[2] == "" else ".obj" assert not os.path.exists( path+file_extension ), "Output file already exists, aborting.\nFilename: "+str(path+file_extension) # extract the c array of vertex poin...
l.append( line.strip() ) c+=1 # convert string of c array to python list positions = eval("["+("".join(l)).replace("{","[").replace("}","]")+"]") # remove different value pos = [x[0:3] for x in positions] # prepare the Obj file format header and content: w = [] w.append("""# Blender v2.69 (sub 0) OBJ Fil...
leongold/lago
ovirtlago/reposetup.py
Python
gpl-2.0
7,082
0
#!/usr/bin/env python # Copyright 2016 Red Hat, Inc. # # 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 2 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 General Publ
ic License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # import functools import re import itertools import shutil import logging import os from l...
M4rtinK/anaconda
tests/unit_tests/pyanaconda_tests/modules/boss/test_set_file_contexts_task.py
Python
gpl-2.0
2,587
0
# # Copyrigh
t (C) 2021 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your opt
ion) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy o...
aio-libs/aiobotocore
tests/test_sqs.py
Python
apache-2.0
2,198
0
import time import pytest @pytest.mark.moto @pytest.mark.asyncio async def test_list_queues(sqs_client, sqs_queue_url): response = await sqs_client.list_queues() pytest.aio.assert_status_code(response, 200) assert sqs_queue_url in response['QueueUrls'] @pytest.mark.moto @pytest.mark.asyncio async def t...
ing', 'StringValue': 'value1'} } ) pytest.aio.assert_status_code(response, 200) response = await sqs_client.receive_message( QueueUrl=sqs_queue_url, MessageAttributeNames=['attr1'] ) pytest.aio.assert_status_code(response, 200) # Messages wont be a key if its empty ...
nse.get('Messages', [])) == 1 msg = response['Messages'][0] assert msg['Body'] == 'test_message_1' assert msg['MessageAttributes']['attr1']['StringValue'] == 'value1' receipt_handle = response['Messages'][0]['ReceiptHandle'] response = await sqs_client.delete_message( QueueUrl=sqs_queue_url...
AdmitHub/heroku-auto-ssl
hooks/heroku-auto-ssl/hook.py
Python
mit
8,401
0.00488
#!/usr/bin/env python import sys, logging, getpass, subprocess, os, json # List of Heroku App ids to update _heroku_app_ids = None _HEROKU_APP_IDS_ENV_KEY = "HEROKU_APP_IDS" def get_heroku_app_ids(): global _heroku_app_ids # Lazy load if _heroku_app_ids is None: env = os.environ.get(_HEROKU_APP_ID...
- chain_file (str): Path to SSL intermediate certificates file. - timestamp (str): Timestamp when the SSL cert was created """ def deploy_cert(args): # Extract args domain, key_file, cert_file, full_chain_file, chain_file, timestamp = args # Get Heroku app Id for domain heroku
_app_ids = None try: heroku_app_ids = get_heroku_app_ids() logging.debug("Got Heroku Ids=\"{}\"".format(heroku_app_ids)) except ValueError as e: # If ENV['HEROKU_AUTO_SSL_DOMAIN_MAPPING'] isn't set logging.exception("Failed to deploy certificate for domain=\"{}\", HEROKU_AUTO_SSL_DOMAIN...
markovmodel/msmtools
msmtools/analysis/dense/decomposition.py
Python
lgpl-3.0
17,097
0.000643
# This file is part of MSMTools. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # MSMTools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either ...
ion of T Returns ------- eig : (n,) ndarray, The eigenvalues of T ordered with decreasing absolute value. If k is None then n=d, if k is int then n=k otherwise n is the length of the given tuple of eigenvalue indices. Raises ------ ValueError If
stationary distribution is nonpositive. """ """compute stationary distribution if not given""" if mu is None: mu = stationary_distribution(T) if np.any(mu <= 0): raise ValueError('Cannot symmetrize transition matrix') """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] *...
rangsimanketkaew/NWChem
contrib/marat/python/XYZ_file.py
Python
mit
2,936
0.012602
''' Created on Feb 3, 2012 @author: marat ''' import string from myvector import Vector class XYZ_file: ''' classdocs ''' def __init__(self,name=None): if name==None: self.FileName = " " self.NumAtom = 0 self.AtomName = [] self.AtomPos = [] ...
ileName lines = fp.readlines() NumAtom = string.atoi(lines[0]) self.NumAtom = NumAtom AtomStr = []*4 self.AtomName = [None]*NumAtom self.AtomId = [None]*NumAtom self.AtomPos = [None]*NumAtom self.AtomVel = [None]*NumAtom x = 0.0 y...
for i in range(NumAtom): self.AtomId[i] = i+1 AtomStr = string.split(lines[i+2])[0:4] self.AtomName[i] = AtomStr[0] x = string.atof(AtomStr[1]) y = string.atof(AtomStr[2]) z = string.atof(AtomStr[3]) self.AtomPos[i] = Vector(x,y,z) ...
ypid-bot/check_mk
web/plugins/cron/user_sync.py
Python
gpl-2.0
1,544
0
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
NU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, # Boston, MA 02110-1301 USA. import userdb multisite_cronjobs.append(userdb.execute_userdb_job)
googleads/google-ads-python
google/ads/googleads/v8/services/services/conversion_upload_service/client.py
Python
apache-2.0
25,206
0.001071
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[ConversionUploadServiceTransport]] _transport_registry["grpc"] = ConversionUploadServiceGrpcTransport def get_transport_cl...
s. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: ...
vabs22/zulip
zerver/lib/create_user.py
Python
apache-2.0
3,927
0.002546
from __future__ import absolute_import from django.contrib.auth.models import UserManager from django.utils.timezone import now as timezone_now from zerver.models import UserProfile, Recipient, Subscription, Realm, Stream import base64 import ujson import os import string from six.moves import range from typing impor...
=now, date_joined=now, realm=realm, pointer=-1, i
s_bot=bool(bot_type), bot_type=bot_type, bot_owner=bot_owner, is_mirror_dummy=is_mirror_dummy, tos_version=tos_version, timezone=timezone, tutorial_status=tutorial_status, enter_sends=enter_sends,...
foyzur/gpdb
gpMgmt/bin/gppylib/operations/backup_utils.py
Python
apache-2.0
38,070
0.00633
import fnmatch import glob import os import re import tempfile from gppylib import gplog from gppylib.commands.base import WorkerPool, Command, REMOTE from gppylib.commands.unix import Scp from gppylib.db import dbconn from gppylib.db.dbconn import execSQL from gppylib.gparray import GpArray from pygresql import pg fro...
rent_tables.append(table) expanded_list += non_parent_tables local_batch_size = 1000 for (s, e) in get_batch_from_list(len(parent_tables), local_batch_size): tmp = convert_parents_to_leafs(dbname, parent_tables[s:e])
expanded_list += tmp return expanded_list def get_batch_from_list(length, batch_size): indices = [] for i in range(0, length, batch_size): indices.append((i, i+batch_size)) return indices def create_temp_file_from_list(entries, prefix): """ When writing the entries into temp ...
EdDev/vdsm
lib/yajsonrpc/stompreactor.py
Python
gpl-2.0
22,060
0
# Copyright (C) 2014-2017 Red Hat Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY;...
nection): res = stomp.Frame( stomp.Command.ERROR, None, msg ) connection.send_raw(res) def _cmd_unsubscribe(self, dispatcher, frame): self.log.info("Unsubscribe command received") sub_id = frame.headers.get("id", None) if not sub_...
iption = self._sub_ids.pop(sub_id) except KeyError: self.log.debug("No subscription for %s id", sub_id) return else: self._remove_subscription(subscription) def _cmd_disconnect(self, dispatcher, frame): self.log.info("Disconnect...
Yadnyawalkya/integration_tests
cfme/utils/ports.py
Python
gpl-2.0
747
0.002677
# -*- coding: utf-8 -*- """Storage for ports. Set defaults here, then :py:mod:`fixtures.portset` will make overrides."""
import sys from cfme.utils import clear_property_cache from cfme.utils.log import logger class Ports(object): SSH = 22 DB = 5432 TOWER = 54322 logger = logger @property def _top(self, m=sys.modules): mod = m.get('utils.appliance') return mod and mod.stack.top def __set...
if self._top is not None: self.logger.info("Invalidating lazy_cache ssh_client current_appliance object") clear_property_cache(self._top, 'ssh_client') sys.modules[__name__] = Ports()
DrZhang/LogAnalyst
Analysts/AbsAnalyst.py
Python
lgpl-3.0
353
0.05949
import re import Queue class AbsAn
alyst(object): """docstring for AbsAnalyst""" LOGTIME_REGEXP = re.compile("(?P<log_time>\w{4}-\w{2}-\w{2} \w{2}:\w{2}:\w{2})") def __init__(self): raise NotImplemented def isMatch(self, line): raise NotImplemented def doSta
tistic(self): raise NotImplemented def doAnalyse(self): raise NotImplemented
open-synergy/runbot-addons
runbot_language/models/__init__.py
Python
agpl-3.0
433
0
# -*- coding: utf-8 -*- ############################################################## # Module Writen For Odoo, Open Source Management Solution # # Copyright (c) 2011 Vauxoo - http://www.vauxoo.com #
All Righ
ts Reserved. # info Vauxoo (info@vauxoo.com) # coded by: moylop260@vauxoo.com ############################################################################ from . import runbot_repo from . import runbot_build
Acehaidrey/incubator-airflow
airflow/providers/amazon/aws/hooks/redshift.py
Python
apache-2.0
1,282
0.00078
# # 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...
oks.redshift_cluster import RedshiftHook fr
om airflow.providers.amazon.aws.hooks.redshift_sql import RedshiftSQLHook warnings.warn( "This module is deprecated. Please use `airflow.providers.amazon.aws.hooks.redshift_cluster` " "or `airflow.providers.amazon.aws.hooks.redshift_sql` as appropriate.", DeprecationWarning, stacklevel=2, ) __all__ = ...
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/ipv6_express_route_circuit_peering_config.py
Python
mit
2,366
0.001691
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
=None, state=None): super(Ipv6ExpressRouteCircuitPeeringConfig, self).__init__() self.primary_peer_address_prefix = primary_peer_address_prefix sel
f.secondary_peer_address_prefix = secondary_peer_address_prefix self.microsoft_peering_config = microsoft_peering_config self.route_filter = route_filter self.state = state
alessandroHenrique/coinpricemonitor
dashboard/urls.py
Python
mit
134
0
from .views imp
ort IndexView from django.conf.u
rls import url urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), ]
lchi/blimp
blimp/commands/terminate.py
Python
mit
1,260
0.001587
from pprint import pformat import boto3 from clint.textui import indent, puts, prompt def _get_instance_details(instance): return { 'tags': instance.tags, 'launch_time': instance.launch_time.isoformat(), 'instance_type': instance.instance_type, 'state': instance.s
tate, 'key_name': instance.key_name, 'public_dns_name': instance.public_dns_name, 'private_dns_name': instance.private_dns_name, 'placement': instance.placement, } def terminate(args, config): ec2 = boto3.resource('ec2') instance_id = args.instance_id instance = ec2.Ins...
format(instance_id), validators=[]) if confirm is "y": instance.terminate() puts("termination request issued") else: puts("aborted") def _register_terminate(subparsers): parser_terminate = subparsers.add_parser('terminate', help='terminate help') parser_terminate.add_argument(...
geertj/gruvi
tests/test_jsonrpc.py
Python
mit
27,989
0.000322
# # This file is part of Gruvi. Gruvi is free software available under the # terms of the MIT license. See the file "LICENSE" that was provided # together with this source file for the licensing terms. # # Copyright (c) 2012-2017 the Gruvi authors. See the file "AUTHORS" for a # complete list. from __future__ import a...
x.error, 0) self.assertEqual(ctx.offset, len(r)) def test_leading_whitespace(self): r = b' { "foo": "bar" }' ctx = split_string(r) self.assertEqual(ctx.error, 0) self.assertEqual(ctx.offse
t, len(r)) r = b' \t\n{ "foo": "bar" }' ctx = split_string(r) self.assertEqual(ctx.error, 0) self.assertEqual(ctx.offset, len(r)) def test_trailing_whitespace(self): r = b'{ "foo": "bar" } ' ctx = split_string(r) self.assertEqual(ctx.error, 0) self.as...
xhava/hippyvm
hippy/module/hash/cjoaat.py
Python
mit
1,324
0.001511
from rpython.translator.tool.cbuild import ExternalCompilationInfo from rpython.rtyper.tool import rffi_platform as platform from rpython.rtyper.lltypesystem import rffi, lltype from hippy.tool.platform import get_gmake import subprocess import py LIBDIR = py.path.local(__file__).join('..', 'lib', 'joaat/') subproces...
call([get_gmake(), '-C', str(LIBDIR)]) eci = ExternalCompilationInfo( includes=['joaat.h'], library_dirs=[str(LIBDIR)], libraries=['joaat1'], testonly_libraries=['joaat'], include_dirs=[st
r(LIBDIR)]) class CConfig: _compilation_info_ = eci JOAAT_CTX = platform.Struct('JOAAT_CTX', []) globals().update(platform.configure(CConfig)) def external(name, args, result): return rffi.llexternal(name, args, result, compilation_info=eci, releasegil=False) PTR_JOAAT_CTX =...
denisenkom/django
tests/proxy_models/models.py
Python
bsd-3-clause
4,379
0.005481
""" By specifying the 'proxy' Meta attribute, model subclasses can specify that they will take data directly from the table of their base class table rather than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ from django.db ...
y(State): class Meta: proxy = True # Proxy models still works with filters (on related fields) # and select_related, even when mixed with model inheritance @python_2_unicode_compatible class BaseUser(models.Model): name = models.CharField(max_length=255) def __str__(self): return ':'.join(...
rUser): class Meta: proxy = True @python_2_unicode_compatible class Issue(models.Model): summary = models.CharField(max_length=255) assignee = models.ForeignKey(TrackerUser) def __str__(self): return ':'.join((self.__class__.__name__, self.summary,)) class Bug(Issue): version = m...