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
compiteing/flask-ponywhoosh
docs/src/conf.py
Python
mit
8,701
0.004252
# -*- coding: utf-8 -*- # # flask-ponywhoosh documentation build configuration file, created by # sphinx-quickstart on Tue Jun 1 14:31:57 2010. # # 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...
lative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append(os.path.abspath('_themes')) # -- General configuration ----
------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.aut...
stevecassidy/signbank-video
video/admin.py
Python
bsd-3-clause
264
0.007576
from django.contrib import admin from video.models import Tag
gedVideo, Video class VideoAdmin(admin.TabularInline): model = Video @admin.register(TaggedVideo) class TaggedVideoAdmin(admin.ModelAdmin): search
_fields = ['^tag'] inlines = [VideoAdmin]
mission-liao/pyopenapi
pyopenapi/tests/migration/test_scan.py
Python
mit
6,151
0.000488
# -*- coding: utf-8 -*- import unittest import weakref from pyopenapi.migration.scan import Scanner, Dispatcher, scan from pyopenapi.migration.versions.v1_2.objects import ( ApiDeclaration, Authorization, Operation, ResponseMessage, Parameter) from pyopenapi.migration.versions.v3_0_0.objects import ( Header as...
pass def __init__(self): self.total = {
Header3: 0, Parameter3: 0, } @Disp.register([Header3, Parameter3]) def _count(self, _, obj): self.total[obj.__class__] = self.total[obj.__class__] + 1 class Scanner2TestCase(unittest.TestCase): """ test case for Scanner2 """ def test_child_class_called_twice(self): ...
tellesnobrega/sahara
sahara/utils/notification/sender.py
Python
apache-2.0
2,996
0
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
'verification_id': v
erification['id'], 'health_check_status': health_check['status'], 'health_check_name': health_check['name'], 'health_check_description': health_check['description'], 'created_at': health_check['created_at'], 'updated_at': health_check['updated_at'] } def status_notify(clust...
ToxicWar/bibliotheque
library/admin.py
Python
mit
326
0
# coding: utf-8 from __future__ import unicode_literals from django.contrib import admin from .models import Book, Au
thor, Publisher, Genre admin.site.register(Book, admin.ModelAd
min) admin.site.register(Author, admin.ModelAdmin) admin.site.register(Publisher, admin.ModelAdmin) admin.site.register(Genre, admin.ModelAdmin)
ibc/MediaSoup
worker/deps/gyp/test/actions-bare/gyptest-bare.py
Python
isc
558
0
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights re
served. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies actions which are not depended on by other targets get executed. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('bare.gyp', chdir='src') test.relocate('src', 'relocate/src') test.bui...
om bare.py\n' test.built_file_must_match('out.txt', file_content, chdir='relocate/src') test.pass_test()
pirata-cat/agora-ciudadana
userena/tests/managers.py
Python
agpl-3.0
6,047
0.001984
from django.test import TestCase from django.core import mail from django.contrib.auth.models import User from userena.models import UserenaSignup from userena import settings as userena_settings from guardian.shortcuts import get_perms import datetime, re class UserenaManagerTests(TestCase): """ Test the manag...
confirm_email('john', 'sha1')) # Correct SHA1, but non-existend in db. self.failIf(UserenaSignup.objects.confirm_email('john', 10 * 'a1b2')) def test_delete_expired_users(self): """ Test if expired users are del
eted from the database. """ expired_user = UserenaSignup.objects.create_user(**self.user_info) expired_user.date_joined -= datetime.timedelta(days=userena_settings.USERENA_ACTIVATION_DAYS + 1) expired_user.save() deleted_users = UserenaSignup.objects.delete_expired_users() ...
selwin/django-mailer
django_mailer/engine.py
Python
mit
7,863
0.001145
""" The "engine room" of django mailer. Methods here actually handle the sending of queued messages. """ from django_mailer import constants, models, settings from lockfile import FileLock, AlreadyLocked, LockTimeout from socket import error as SocketError import logging import os import smtplib import tempfile impo...
1 # Don't try to send this message again for now exclude_messages.append(message.pk) elif result == constants.RESULT_SKIPPED: skipped += 1 connection.close() finally: logger.debug("Releasing lock...") lock.release() logger.d...
log("%s sent, %s deferred, %s skipped." % (sent, deferred, skipped)) logger.debug("Completed in %.2f seconds." % (time.time() - start_time)) def send_loop(empty_queue_sleep=None): """ Loop indefinitely, checking queue at intervals and sending and queued messages. The interval (in seconds) ca...
francis-taylor/Timotty-Master
cybot/plug/myid.py
Python
mit
625
0.0224
# -*- coding: utf-8 -*- import config from metodos import * from mensagens import myid def my_id(msg): chat_id = msg['chat']['id'] t
ry: user = '@' + msg['from']['username'] except:user = " " if msg['text'] == '/id': if msg['chat']['type'] == 'private': sendMessage(chat_id, myid['private'].decode('utf8').format(msg['from']['first_name'].encode('utf-8'),msg['from']['id'],user)) if msg['chat']['type'] == 'supergr...
ssage(chat_id, myid['private'].decode('utf8').format(msg['from']['first_name'],msg['from']['id'],user))
the-blue-alliance/the-blue-alliance
src/backend/common/queries/suggestion_query.py
Python
mit
1,368
0.000731
from typing import Any, Generator, List, Optional from backend.common.consts.suggestion_state import Su
ggestionState from backend.common.models.account import Account from backend.common.models.suggestion import Suggestion from backend.common.queries.database_query import DatabaseQuery from backend.common.tasklets import typed_tasklet class SuggestionQuery(DatabaseQuery[List[Suggestion], None]): DICT_CONVERTER = ...
r: Optional[Account] = None, reviewer: Optional[Account] = None, keys_only: bool = False, ) -> None: super().__init__( review_state=review_state, author=author, reviewer=reviewer, keys_only=keys_only, ) @typed_tasklet def _quer...
hkawasaki/kawasaki-aio8-1
lms/djangoapps/courseware/views.py
Python
agpl-3.0
32,876
0.002555
""" Courseware views functions """ import logging import urllib import json from collections import defaultdict from django.utils.translation import ugettext as _ from django.conf import settings from django.core.context_processors import csrf from django.core.exceptions import PermissionDenied from django.core.urlr...
s not necessarily tied to a # particular course 'password': "{USER}@{DOMAIN}".format( USER=user.username, DOMAIN=domain ), } @login_required @ensure_csrf_cookie @cache_control(no_cache=True, no_store=True, must_revalidate=True) def index(request, course_id, chapter=None, ...
tent. If course, chapter, and section are all specified, renders the page, or returns an error if they are invalid. If section is not specified, displays the accordion opened to the right chapter. If neither chapter or section are specified, redirects to user's most recent chapter, or the first c...
cyruscyliu/diffentropy
week3/w3_lnn.py
Python
mit
2,275
0
import numpy as np from week3 import lnn, tools import os def f(x): if 0 <= x < 0.25: return float(0) elif 0.25 <= x < 0.5: return 16.0 * (x - 0.25) elif 0.5 <= x < 0.75: return -16.0 * (x - 0.75) elif 0.75 < x <= 1: return float(0) else: raise ValueError('v...
= 0.5 for i in range(0, size): next_ = np.random.rand() u = np.random.rand() if f(current) == float(0): condition = 0 else: condition = min(f(next_) / f(current), 1) if u < condition: # accept result.append(next_) ...
ples size = 100000 data = MCMC_SD(size) data = [[data[i]] for i in range(size)] data = np.array(data) true = -1.276263936 # for k in (24): k = 27 result = [] for tr in range(k, 40, 5): try: entropy = lnn.LNN_2_entropy(data, k=k, tr=tr, bw=0) print ent...
kamyu104/LeetCode
Python/binary-tree-tilt.py
Python
mit
1,289
0
# Time: O(n) # Space: O(n) # Given a binary tree, return the tilt of the whole tree. # # The tilt of a tree node is defined as the absolute difference # between the sum of all left subtree node values and # the sum of all right subtree node values. Null node has tilt 0. # # The tilt of the whole tree is defined as th...
# Tilt of node 2 : 0 # Tilt of node 3 : 0 # Tilt of node 1 : |2-3| = 1 # Tilt of binary tree : 0 + 0 + 1 = 1 # Note: # # The sum of node values in any subtree won't exceed # the range of 32-bit integer. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x...
def postOrderTraverse(root, tilt): if not root: return 0, tilt left, tilt = postOrderTraverse(root.left, tilt) right, tilt = postOrderTraverse(root.right, tilt) tilt += abs(left-right) return left+right+root.val, tilt return postOrderT...
PyQwt/PyQwt4
configure/configure.py
Python
gpl-2.0
29,680
0.003605
#!/usr/bin/python # # Generate the build trees and Makefiles for PyQwt. import compileall import glob import optparse import os import pprint import re import shutil import sys import traceback class Die(Exception): def __init__(self, info): Exception.__init__(self, info) # __init__() # class Die ...
tra_lib_dirs is a list of extra directories to search for libraries extra_libs is a list of extra libraries """ makefile = sipconfig.ProgramMakefile( configuration, console=True, qt=True, warnings=True) makefile.extra_defines.extend(extra_defines) makefile.extra_include_dirs.extend(...
makefile.extra_libs.extend(extra_libs) exe, build = makefile.build_command(name) # zap a spurious executable try: os.remove(exe) except OSError: pass os.system(build) if not os.access(exe, os.X_OK): return None if sys.platform != 'win32': exe = './' + ex...
alexandrucoman/vbox-neutron-agent
neutron/tests/unit/api/v2/test_attributes.py
Python
apache-2.0
35,656
0
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
attributes._validate_no_whitespace, 'i\thave\twhitespace') for ws in string.whitespace: self.assertRaises(n_exc.InvalidInput, attributes._validate_no_whites
pace, '%swhitespace-at-head' % ws) self.assertRaises(n_exc.InvalidInput, attributes._validate_no_whitespace, 'whitespace-at-tail%s' % ws) def test_validate_range(self): msg = attributes._validate_range(1, ...
JelleAalbers/plunc
plunc/intervals/base.py
Python
mit
13,686
0.004749
import numpy as np import logging from plunc.common import round_to_digits from plunc.exceptions import SearchFailedException, InsufficientPrecisionError, OutsideDomainError from plunc.WaryInterpolator import WaryInterpolator class IntervalChoice(object): """Base interval choice method class """ method = ...
elf.precision_digits), domain=self.interpolator_log_domain) if self.fixed_upper_limit is None: self.high_limit_interpolator = Wa
ryInterpolator(precision=10**(-self.precision_digits), domain=self.interpolator_log_domain) # "Joints" of the interpolator must have better precision than required of the interpolator results self.precision_digits += 1 # Di...
serverdensity/sdbot
limbo/settings/__init__.py
Python
mit
431
0.00464
from ..utils import getif def init_config(): config = {} getif(config, "token", "SLACK_TOKEN") getif(config, "loglevel", "LIMBO_LOGLEVEL") getif(config, "logfile", "LIMBO_LOGFILE") getif(config, "log
format", "LIMBO_LOGFORMAT
") getif(config, "plugins", "LIMBO_PLUGINS") getif(config, "heroku", "LIMBO_ON_HEROKU") getif(config, "beepboop", "BEEPBOOP_TOKEN") return config CONFIG = init_config()
LucaBongiorni/openlte
LTE_fdd_dl_file_gen/python/LTE_fdd_dl_file_gen.py
Python
agpl-3.0
1,147
0.004359
#!/usr/bin/env python from gnuradio import gr from gnuradio.eng_option import eng_option from optparse import OptionParser import LTE_fdd_dl_fg import sys class LTE_fdd_dl_file_gen (gr.top_block): def __init__(self): gr.top_block.__init__(self)
usage = "usage: %prog [options] file N_frames N_ant N_id_cell bandwidth mcc mnc" parser=OptionParser(option_class=eng_option, usage=usage) # Add options here (options, args) = parser.parse_args() if len(args) != 7: parser.print_help() sys.exit(1) outp...
mcc = args[5] mnc = args[6] # Build flow graph self.samp_buf = LTE_fdd_dl_fg.samp_buf(int(N_frames), int(N_ant), int(N_id_cell), float(bandwidth), mcc, mnc) self.fsink = gr.file_sink(gr.sizeof_char, output_filename) self.connect(self.samp_buf, self.fsink) if __name__ == '__main...
werkt/bazel
src/test/py/bazel/bazel_windows_cpp_test.py
Python
apache-2.0
32,128
0.001276
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
'#include <stdio.h>', '#include "a.h"', '#include "b.h"', '', 'void hello_C() {', ' hello_A();', ' hello_B();', ' printf("Hello C\\n");', '}', '', 'int main() {', ' hello_C();', ' return 0;', '}', ] ...
' name = "A",', ' srcs = ["dummy.cc"],', ' features = ["windows_export_all_symbols"],', ' visibility = ["//visibility:public"],', ')', ]) self.ScratchFile('lib/dummy.cc', ['void dummy() {}']) self.ScratchFile('main/main.cc', c_cc_content) def getBazelInfo(self,...
jlzirani/cache-storing
store.py
Python
gpl-3.0
1,439
0.039611
from datetime import datetime class store: def __init__(self, delta): self.delta = delta self.dataDict = {} self.ordList = [] def store(self, data, info): ob2store = [data,info] if data in self.dataDict: try: self.ordList.remove(self.dataDict[data]) e...
self.dataDict = {} def getIndex(self, pivot): endIndex = len(self.ordList) if endIndex == 0: return 0
(d0,i0) = self.ordList[0] (dE,iE) = self.ordList[-1] if i0 > pivot: return 0 if iE < pivot: return endIndex return self.getIndexRec(pivot, 0, endIndex) def getIndexRec(self, pivot, startIndex, endIndex): if startIndex == endIndex: return startIn...
chengduoZH/Paddle
python/paddle/fluid/dygraph/parallel_helper.py
Python
apache-2.0
1,499
0
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except jin compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
d once." __parallel_ctx__clz__ = nccl_parallel_context def _init_parallel_ctx(): global __parallel_ctx__clz__ assert __parallel_ctx__clz__ is not None, \
"ParallelContext should be initialized." __parallel_ctx__clz__.init() def _broadcast_parameters(parameters): for param in parameters: if isinstance(param, Parameter) and param.trainable: collective._broadcast(param, 0, sync_mode=True)
krull/docker-zenoss4
init_fs/usr/local/zenoss/ZenPacks/ZenPacks.zenoss.ZenJMX-3.12.1.egg/ZenPacks/zenoss/ZenJMX/zenjmx.py
Python
gpl-3.0
25,284
0.006051
#! /usr/bin/env python ############################################################################## # # Copyright (C) Zenoss, Inc. 2008, 2009, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the directory where your Zenoss product is installed. # #####...
ient(zope.interface.Interface): listenPort = zope.interface.Attribute("listenPort") class ZenJMXJavaClientImpl(ProcessProtocol): """ Protocol to control the zenjmxjava process """ zope.interface.implements(IZenJMXJavaClient) def __init__( self, args, cycle=True, ...
@param cycle: whether to run once or repeat @type cycle: boolean @param zenjmxjavaport: port on which java process will listen for queries @type zenjmxjavaport: int """ self.deferred = Deferred() self.stopCalled = False self.pro...
EvanBianco/pickr
main.py
Python
apache-2.0
13,664
0.009075
import webapp2 from jinja2 import Environment, FileSystemLoader from os.path import dirname, join import os import json import base64 import hashlib import StringIO from google.appengine.api import users import numpy as np if not os.environ.get('SERVER_SOFTWARE','').startswith('Development'): import PIL import...
data = data.fetch(1000)[index] if vote > 0: vote
= 1 else: vote =-1 data.votes += vote data.put() self.response.write(data.votes) class MainPage(webapp2.RequestHandler): def get(self): user = users.get_current_user() if not user: login_url = users.create_login_url...
safwanrahman/kuma
kuma/search/tests/test_types.py
Python
mpl-2.0
1,629
0
from elasticsearch_dsl import query from kuma.core.tests import eq_, ok_ from kuma.wiki.search import WikiDocumentType from . import ElasticTestCase class WikiDocumentTypeTests(ElasticTestCase): fixtures = ElasticTestCase.fixtures + ['wiki/documents.json'] def test_get_excerpt_strips_html(self): se...
() ok_('the word for tough things' in excerpt) ok_('extra content' not in excerpt) def test_hidden_slugs_get_indexable(self): self.refresh() title_list = WikiDocumentType.get_indexable().values_list('ti
tle', flat=True) ok_('User:jezdez' not in title_list)
thomasperrot/MTGTrader
mtg/config/urls.py
Python
mit
915
0
"""config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(
r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: ...
l(r'^admin/', admin.site.urls), url(r'^cards/', include('cards.urls')), url(r'^tournaments/', include('tournaments.urls')), url(r'^stats/', include('stats.urls')) ]
dwavesystems/dimod
dimod/bqm/construction.py
Python
apache-2.0
4,145
0.000241
# Copyright 2020 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ls` kwargs below. as_bqm(n, vartype) Creates a BQM with `n` variables, indexed linearly from zero, setting all biases to zero. as_bqm(quadratic, vartype) Creates a BQM from quadratic biases given as a square array_like_ or a dictionary of the form `{(u, ...
}`. Note that when formed with SPIN-variables, biases on the diagonal are added to the offset. as_bqm(linear, quadratic, vartype) Creates a BQM from linear and quadratic biases, where `linear` is a one-dimensional array_like_ or a dictionary of the form ...
luetgendorf/Espruino
boards/ESP32.py
Python
mpl-2.0
4,723
0.035994
#!/bin/false # This file is part of Espruino, a JavaScript interpreter for Microcontrollers # # Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at h...
1"]=0; pinutils.findpin(pins, "PD26", True)["functions"]["DAC_OUT2"]=0; pinutils.findpin(pins, "PD0", True)["functions"]["LED_1"]=0; pinutils.findpin(pins, "PD10", True)["functions"]["USART0_TX"]=0; pinutils.findpin(pins, "PD16", True)["functions"]["USART2_RX"]=0; pinutils.findpin(pins, "PD17", True)["func...
=0; # everything is non-5v tolerant #for pin in pins: # pin["functions"]["3.3"]=0; return pins
ERICUdL/ISTEX_MentalRotation
ids2docs_years.py
Python
bsd-3-clause
2,227
0.021105
# -*- coding: utf-8 -*- # # This file is part of Istex_Mental_Rotation. # Copyright (C) 2016 3ST ERIC Laboratory. # # This is a free software; you can redistribute it and/or modify it # under the terms of the Revised BSD License; see LICENSE file for # more details. # Load and transform ISTEX and wiki articles into ba...
-out_dir", default="results", type=str) # name of the output directory args = parser.parse_args() results_file = args.results_file istex_dir = args.istex_dir out_file = args.out_file out_dir = args.out_dir if not os.path.exists(out_dir): os.makedirs(out_dir) results = pickle.load(open(results_file,'rb')) i...
ds) articles = get_article_by_istex_id(istex_ids, istex_dir) json.dump(articles, open(os.path.join(out_dir, out_file), "w"), indent=2) print 'length of response file: ', len(articles) print 'response file could be found at: ', os.path.join(out_dir, out_file)
ulif/pulp
server/pulp/server/db/model/auth.py
Python
gpl-2.0
1,467
0.001363
# -*- coding: utf-8 -*- from pulp.server.db.model.base import Model class Role(Model): """ Represents a role and a set of permissions associated with that role. Users that are added to this role will inherit all the permissions associated with the role. @ivar id: role's id, must be unique for ea...
h role @type id: str @ivar display_name: user-readable name of the role
@type display_name: str @ivar description: free form text used to describe the role @type description: str @ivar permissions: dictionary of resource: tuple of allowed operations @type permissions: dict """ collection_name = 'roles' unique_indices = ('id',) def __init__(self, id,...
lemon24/intercessor
examples/book.py
Python
bsd-3-clause
78
0.038462
#: one x = 1 print(x) im
por
t time time.sleep(10) #: two #x = 2 print(x)
daluu/AutoPyDriverServer
sample-code/webdriver_integration_demo.py
Python
apache-2.0
1,719
0.007563
from selenium import webdriver from selenium.webdriver import ActionChains from os import p
ath import time #NOTE: this demo uses images under images subfolder to find by name. # Be sure to configure AutoPyDriverServer to use that folder for images by name # start up both Firefox & AutoPyDriver for demo browser = webdriver.Firefox() autopy_driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/...
red Capabilities returned by server:\n" print autopy_driver.desired_capabilities print "" # launch browser to Drag & drop page for demo test browser.get("http://html5demos.com/drag") if len(browser.find_elements_by_tag_name("li")) != 5: print "Drag & drop test page not in correct state for demo test" time.sleep(5) ...
0x7678/youtube-dl
youtube_dl/extractor/tvigle.py
Python
unlicense
2,889
0.001065
# encoding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( float_or_none, parse_age_limit, ) class TvigleIE(InfoExtractor): IE_NAME = 'tvigle' IE_DESC = 'Интернет-телевидение Tvigle.ru' _VALID_URL = r'http://(?:www\.)?tvigle\.ru/(?:[^/]+/)+(?...
ideo_id, display_id) item = video_data['playlist']['items'][0] title = item['title'] description = item['description'] thumbnail = item['thumbnail'] duration = float_or_none(item.get('durationMilliseconds
'), 1000) age_limit = parse_age_limit(item.get('ageRestrictions')) formats = [] for vcodec, fmts in item['videos'].items(): for quality, video_url in fmts.items(): formats.append({ 'url': video_url, 'format_id': '%s-%s' % (vcod...
ehouarn-perret/EhouarnPerret.Python.Kattis
Trivial/Peg.py
Python
mit
719
0.030598
def count_moves(a, x, y): character = a[x][y] if character == ".": count = 0 rows = len(a) columns = len(a[x]) # Top Check if ((x - 2) >= 0) and (a[x - 1][y] == "o") and (a[x - 2][y] == "o"): count += 1 # Bottom Check if ((x + 2) < rows) and (a[x + 1][y] == "o") and (a[x +
2][y] == "o"): count += 1 # Left Check if ((y - 2) >= 0
) and (a[x][y - 1] == "o") and (a[x][y - 2] == "o"): count += 1 # Right Check if ((y + 2) < columns) and (a[x][y + 1] == "o") and (a[x][y + 2] == "o"): count += 1 return count else: return 0 moves = 0 size = 7 board = [input() for _ in range(size)] for cx in range(size): for cy in range(size): moves...
lpakula/django-oscar-paypal
paypal/express_checkout/gateway.py
Python
bsd-3-clause
7,616
0.001576
from decimal import Decimal as D from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.template.defaultfilters import striptags, truncatechars from django.utils.translation import gettext_lazy as _ from paypalcheckoutsdk.core import LiveEnvironment, PayPalHttpClient, Sand...
sAuthorizeRequest, OrdersCaptureRequest, OrdersCreateRequest, OrdersGetRequest) from paypalcheckoutsdk.payments import AuthorizationsCaptureRequest, AuthorizationsVoidRequest, CapturesRefundRequest
INTENT_AUTHORIZE = 'AUTHORIZE' INTENT_CAPTURE = 'CAPTURE' INTENT_REQUEST_MAPPING = { INTENT_AUTHORIZE: AuthorizationsCaptureRequest, INTENT_CAPTURE: OrdersCaptureRequest, } LANDING_PAGE_LOGIN = 'LOGIN' LANDING_PAGE_BILLING = 'BILLING' LANDING_PAGE_NO_PREFERENCE = 'NO_PREFERENCE' USER_ACTION_CONTINUE = 'CONTI...
kobejean/tensorflow
tensorflow/python/ops/numerics.py
Python
apache-2.0
4,096
0.004395
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
me for this operation (optional). Returns: Same tensor as `t`.
""" with ops.name_scope(name, "VerifyFinite", [t]) as name: t = ops.convert_to_tensor(t, name="t") with ops.colocate_with(t): verify_input = array_ops.check_numerics(t, message=msg) out = control_flow_ops.with_dependencies([verify_input], t) return out @tf_export("add_check_numerics_ops") d...
vladimir-ipatov/ganeti
lib/outils.py
Python
gpl-2.0
4,426
0.005874
# # # Copyright (C) 2012 Google 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 ...
ENCE_TYPES = (list, tuple, set, frozenset) class AutoSlots(type): """Meta base class for __slots__ definitions. """ def __new__(mcs, n
ame, bases, attrs): """Called when a class should be created. @param mcs: The meta class @param name: Name of created class @param bases: Base classes @type attrs: dict @param attrs: Class attributes """ assert "__slots__" not in attrs, \ "Class '%s' defines __slots__ when it sho...
DirtyUnicorns/android_external_chromium-org
tools/perf/benchmarks/media.py
Python
bsd-3-clause
1,514
0.015852
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys from measurements import media from telemetry import test class Media(test.Test): """Obtains media metrics for key user scenarios.""" test =...
est): """Obtains media metrics for key media source extensions functions.""" test = media.Media enabled = not sys.platform.startswith('l
inux') page_set = 'page_sets/mse_cases.json' def CustomizeBrowserOptions(self, options): # Needed to allow XHR requests to return stream objects. options.AppendExtraBrowserArgs( '--enable-experimental-web-platform-features')
klingebj/regreg
code/regreg/problems/composite.py
Python
bsd-3-clause
14,743
0.005698
from numpy.linalg import norm from numpy import zeros, array, any as npany import new from copy import copy # local imports from ..identity_quadratic import identity_quadratic as sq from ..algorithms import FISTA from ..objdoctemplates import
objective_doc_templater from ..doctemplates import (doc_template_user, doc_template_provider) @objective_doc_templater() class composite(object): """ A generic way to specify a problem in composite form. """ objective_template = r"""f(%(var)s)""" objective_vars = {'var': r'\beta', 'shape':'p', 'o...
quadratic=None, initial=None): self.offset = offset if offset is not None: self.offset = array(offset) if type(shape) == type(1): self.shape = (shape,) else: self.shape = shape if quadratic is not None: self.quadratic = q...
bigmlcom/python
bigml/api_handlers/evaluationhandler.py
Python
apache-2.0
3,626
0
# -*- coding: utf-8 -*- # # Copyright 2014-2022 BigML # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
ecked: body = json.dumps(create_args) return self._create(self.evaluation_url, body) return def get_evaluation(self, evaluation, query_string=''):
"""Retrieves an evaluation. The evaluation parameter should be a string containing the evaluation id or the dict returned by create_evaluation. As evaluation is an evolving object that is processed until it reaches the FINISHED or FAULTY state, the function will ...
blakev/tappy
tap/i18n.py
Python
bsd-2-clause
229
0
# Copyright (c) 2015, Matt Layman import gettext import os localedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'locale') tr
anslate = gettext.translation('tappy', localedir, fallback=Tru
e) _ = translate.gettext
openworm/PyOpenWorm
owmeta/data_trans/common_data.py
Python
mit
496
0
from .. import BASE_SCHEMA_URL, BASE_DATA_URL from rdflib.namespace import Namespace TRANS_N
S = Namespace(BASE_SCHEMA_URL + '/translators/'
) TRANS_DATA_NS = Namespace(BASE_DATA_URL + '/translators/') DS_NS = Namespace(BASE_SCHEMA_URL + '/data_sources/') DS_DATA_NS = Namespace(BASE_DATA_URL + '/data_sources/') class DSMixin(object): base_namespace = DS_NS base_data_namespace = DS_DATA_NS class DTMixin(object): base_namespace = TRANS_NS ...
sai9/weewx-gitsvn
bin/weewx/drivers/ws28xx.py
Python
gpl-3.0
174,398
0.006061
# $Id$ # Copyright 2013 Matthew Wall # See the file LICENSE.txt for your full rights. # # Thanks to Eddie De Pieri for the first Python implementation for WS-28xx. # Eddie did the difficult work of decompiling HeavyWeather then converting # and reverse engineering into a functional Python implementation. Eddie's # wor...
n a synology ds209+ii, for an average of 2.2 seconds per history record. Reading 1750 history records took 19 minutes using HeavyWeatherPro on a Windows 7 64-bit laptop. Message Types The first byte of a message determines the message type. ID Type Length 01 ? 0x0f (15
) d0 SetRX 0x15 (21) d1 SetTX 0x15 (21) d5 SetFrame 0x111 (273) d6 GetFrame 0x111 (273) d7 SetState 0x15 (21) d8 SetPreamblePattern 0x15 (21) d9 Execute 0x0f (15) dc ReadConfigFlash< 0x15 (21) dd ReadConfigFlash> 0x15 (21) d...
andrebellafronte/stoq
stoqlib/gui/dialogs/tillhistory.py
Python
gpl-2.0
4,857
0.003088
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2007 Async Open Source <http://www.async.com.br> ## 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 Foundati...
NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should ha
ve received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., or visit: http://www.gnu.org/. ## ## Author(s): Stoq Team <stoq-devel@async.com.br> ## """ Implementation of classes related to till operations. """ import datetime import gtk fro...
jorge-marques/shoop
shoop/discount_pricing/admin_form_part.py
Python
agpl-3.0
2,820
0.000355
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from djang...
field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, ...
(spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): ...
jly8866/archer
sql/data_masking.py
Python
apache-2.0
16,236
0.002478
# -*- coding:utf-8 -*- from .inception import InceptionDao from .models import DataMaskingRules, DataMaskingColumns from simplejson import JSONDecodeError import simplejson as json import re inceptionDao = InceptionDao() class Masking(object): # 脱敏数据 def data_masking(self, cluster_name, db_name, sql, sql_res...
table_name=table['table'], active=1).exists(): is_exist = True # 不存在脱敏字段则直接跳过规则解析 if is_exist: # 遍历select_list columns = [] hit_columns = [] # 命中列 table_hit_columns = [] # 涉及表命中的列,仅select ...
raise Exception('不支持该查询语句脱敏!') if select_item['type'] == 'aggregate': if select_item['aggregate'].get('type') not in ('FIELD_ITEM', 'INT_ITEM'): raise Exception('不支持该查询语句脱敏!') # 获取select信息的规则,仅处理type为FIELD_ITEM和aggregate类型的select信息,如[*],[*,col...
TAKEALOT/Diamond
src/collectors/docker_collector/test/testdocker_collector.py
Python
mit
5,993
0.001335
#!/usr/bin/python # coding=utf-8 ################################################################################ import os from test import CollectorTestCase from test import get_collector_config from test import unittest from test import run_only from mock import Mock from mock import patch from mock import mock_open...
mages_count': 100, # 'images_dangling_count': 100, # }) # @run_only_if_docker_client_is_available # @patch('__builtin__.open') # @patch.object(Client, 'containers', Mock(return_value=[])) # @patch.object(Collector, 'publish') # def test_should_open_memory_stat(self, publish_...
self.collector.collect() # print open_mock.mock_calls # open_mock.assert_any_call(fixtures_path + # 'docker/c3341726a9b4235a35b' # '390c5f6f28e5a6869879a48da1d609db8f6bf4275bdc5/memory.stat') # # open_mock.assert_any_call(fixtures_path + # 'lxc/testcontai...
0xPoly/ooni-probe
ooni/otime.py
Python
bsd-2-clause
479
0.006263
from datetime import datetime def prettyDat
eNow(): """ Returns a good looking string for the local time. """ return datetime.now().ctime() def prettyDat
eNowUTC(): """ Returns a good looking string for utc time. """ return datetime.utcnow().ctime() def timestampNowLongUTC(): """ Returns a timestamp in the format of %Y-%m-%d %H:%M:%S in Universal Time Coordinates. """ return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
lah7/polychromatic
pylib/controller/preferences.py
Python
gpl-3.0
23,790
0.003153
#!/usr/bin/python3 # # Polychromatic is licensed under the GPLv3. # Copyright (C) 2020-2021 Luke Horwell <code@horwell.me> # """ This module controls the 'Preferences' window of the Controller GUI. """ from .. import common from .. import effects from .. import locales from .. import middleman from .. import procpid f...
alog.findChild(QComboBox, "LandingTabCombo") for i in range(0, combo.count()): combo.setItemIcon(i, QIcon()) # Prompt for a restart after changing these options def _cb_set_restart_flag(): self.prompt_restart = True self.dialog.findChild(QCheckBox, "UseS...
ns def _cb_set_applet_flag(i): self.restart_applet = True self.dialog.findChild(QComboBox, "TrayModeCombo").currentIndexChanged.connect(_cb_set_applet_flag) self.dialog.findChild(QCheckBox, "DPIStagesAuto").stateChanged.connect(_cb_set_applet_flag) self.dialog.findChild(QChe...
revesansparole/oacontainer
setup.py
Python
mit
1,872
0.001603
#!/usr/bin/env python # -*- coding: utf-8 -*- # {{pkglts pysetup, from os import walk from os.path import abspath, normpath from os.path import join as pj from setuptools import setup, find_packages short_descr = "Set of data structures used in openalea such as : graph, grid, topomesh" readme = open('README.rst').re...
if len(line) > 0 and not line.startswith("#"): reqs.append(line) return reqs # find version number in /src/$pkg_pth/version.py version = {} with open("src/openalea/container/version.py") as fp: exec(fp.read(), version) setup( name='openalea.container', version=version["__version__"...
esansparole", author_email='revesansparole@gmail.com', url='', license="mit", zip_safe=False, packages=find_packages('src'), package_dir={'': 'src'}, install_requires=parse_requirements("requirements.txt"), tests_require=parse_requirements("dvlpt_requirements.txt"), entry_points={ ...
StackPointCloud/libcloud
docs/examples/misc/twisted_create_node.py
Python
apache-2.0
898
0.001114
from __future__ import absolute_import from pprint import pprint # pylint: disable=import-error from twisted.internet import defer, threads, reactor from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver @defer.inlineCallbacks def create_node(name): node = yield threads.de...
node def stop(*args, **kwargs): reacto
r.stop() d = create_node(name='my-lc-node') d.addCallback(stop) # pylint: disable=no-member d.addErrback(stop) # pylint: disable=no-member reactor.run()
arozumenko/locust
tests/locust/tests_enable_network_adapters.py
Python
apache-2.0
8,175
0.000367
""" Tests for locust api module These tests requires locust installed """ #pylint: disable=W0403,C0103,too-many-public-methods import unittest from subprocess import call from netifaces import interfaces from locust.api import Agent from time import time, sleep STATUSES = {'success': 'success', 'error': ...
ter = get_active_adapter() disable_adapters_error = disable_adapters(adapter) self.assertFalse(disable_adapters_error, msg=disable_adapters_error) self.assertTrue(wait_for_network_disabled(), 'Initially Network is enabled.') result = Agent.enable_network_adapt...
ssertEqual(type(result), dict, 'Returned result should be dict') status_from_result = result['list'][0]['status'] message_from_result = result['list'][0]['message'] self.assertEqual(status_from_result, STATUSES['success'], self.wrong_status.format( ...
kaiocesar/simplemooc
simplemooc/core/views.py
Python
mit
192
0.026042
from
django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html') def contact(request): return render(request, 'contact.h
tml')
metabrainz/picard
picard/pluginmanager.py
Python
gpl-2.0
17,081
0.000995
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2007 Lukáš Lalinský # Copyright (C) 2014 Shadab Zafar # Copyright (C) 2015-2021 Laurent Monin # Copyright (C) 2019 Wieland Hoffmann # Copyright (C) 2019-2020 Philipp Wolfer # # This program is free software; you can redistribut...
# now load found plugins names = set() for path in [os.path.join(plugindir, file) for file in os.listdir(plugindir)]: name = _plugin_name_from_path(path) if name: names.add(name) log.debug("Looking for plugins in directory %r, %d names found", ...
plugindir, len(names)) for name in sorted(names): try: self._load_plugin_from_directory(name, plugindir) except Exception: self.plugin_error(name, _("Unable to load plugin '%s'"), name, log_func=log.exception) def _get_plugin_inde...
tomhenderson/ns-3-dev-git
src/olsr/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
542,189
0.014563
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
pe', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] ...
ns
gusai-francelabs/datafari
windows/python/Lib/warnings.py
Python
apache-2.0
14,748
0.001492
"""Python part of the warnings subsystem.""" # Note: function level imports should *not* be used # in this module as it may cause import lock deadlock. # See bug 683658. import linecache import sys import types __all__ = ["warn", "warn_explicit", "showwarning", "formatwarning", "filterwarnings", "simplefil...
rn "default" if action == "all": return "always" # Alias for a in ('default', 'always', 'ignore', 'module', 'once', 'error'): if a.startswith(action): return a raise _OptionError("invalid action: %r" % (action,)) # Helper for _setoption() def _getcategory(category): import re if...
cat = eval(category) except NameError: raise _OptionError("unknown warning category: %r" % (category,)) else: i = category.rfind(".") module = category[:i] klass = category[i+1:] try: m = __import__(module, None, None, [klass]) except Impor...
collinstocks/eventlet
setup.py
Python
mit
1,289
0
#!/usr/bin/env python from setuptools import find_packages, setup from eventlet import __version__ from os import path setup( name='eventlet', version=__version__, description='Highly concurrent networking library', author='Linden Lab', author_email='eventletdev@lists.secondlife.com', url='htt...
alse, long_description=open( path.join( path.dirname(__file__), 'README.rst' )
).read(), test_suite='nose.collector', classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Programming Languag...
openilabs/falconlab
env/lib/python2.7/site-packages/talons/helpers.py
Python
mit
1,777
0
# -*- encoding: utf-8 -*- # # Copyright 2013 Jay Pipes # # 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...
mat_exception(*sys.exc_info()) LOG.error(msg + ' Details: (%s)'.format(err_details)) raise ImportError(msg) except ImportError: msg = 'Module {0} cannot be found.'.format(import_str) err_details = traceback.
format_exception(*sys.exc_info()) LOG.error(msg + ' Details: (%s)'.format(err_details)) raise
VisualComputingInstitute/towards-reid-tracking
lib/models/lunet2.py
Python
mit
1,896
0.007384
import DeepFried2 as df from .. import dfext def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)): kw = dict(mkbn=mkbn) net = df.Sequential( # -> 128x48 df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None), dfext.resblock(64, **kw), df.PoolingCUDNN((2,2...
s=None), mkbn(256), df.ReLU(), df.StoreOut(df.SpatialConvolutionCUDNN(256, 128, (1,1))) ) net.emb_mod = net[-1] net.in_sh
ape = (128, 48) net.scale_factor = (2*2*2*2*2, 2*2*2*2*3) print("Net has {:.2f}M params".format(df.utils.count_params(net)/1000/1000), flush=True) return net def add_piou(lunet2): newnet = lunet2[:-1] newnet.emb_mod = lunet2[-1] newnet.iou_mod = df.StoreOut(df.Sequential(df.SpatialConvolution...
bennymartinson/Oort
oort/__init__.py
Python
gpl-3.0
335
0.008955
from utilities import docs, ftom, mtof, scale_val from dynamic_value import * f
rom behaviors import *
from schedule import now, wait, sprout from rtcmix_import.commands import * from instruments import * import busses #__all__ = ["rtcmix_import", "utilities", "abstract", "dynamic_value", "instruments", "behaviors", "schedule"]
harvardinformatics/jobTree
batchSystems/lsf.py
Python
mit
12,569
0.010661
#!/usr/bin/env python #Copyright (C) 2013 by Thomas Keane (tk2@sanger.ac.uk) # #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 #to u...
self.updatedJobsQueue.put((lsfJobID, exit))
self.runningjobs.remove(lsfJobID) time.sleep(10) class LSFBatchSystem(AbstractBatchSystem): """The interface for running jobs on lsf, runs all the jobs you give it as they come in, but in parallel. """ @classmethod def getDisplayNames(cls): """ Names used...
GHubgenius/clusterd
src/platform/weblogic/fingerprints/WL10s.py
Python
mit
510
0.001961
from src.platform.weblogic.interfaces impor
t WINTERFACES, WLConsole class FPrint(WLConsole): """ WebLogic 10 is bugged when using Oracle's custom implementation of SSL. Only if the default Java implementation is set will this work; otherwise, Oracle sends an SSL23_GET_SERVER_HELLO and breaks OpenSSL. """ def __init__(self): ...
rdhyee/waterbutler
tests/providers/onedrive/test_path.py
Python
apache-2.0
5,141
0.003307
import pytest from waterbutler.providers.onedrive.path import OneDrivePath from tests.providers.onedrive.fixtures import (path_fixtures, root_provider_fixtures, subfolder_provider_fixtures) class TestApiIdentifier: de...
['root', root_provider_fixtures['file_id']] def test_f
older_in_root(self, root_provider_fixtures): od_path = OneDrivePath.new_from_response(root_provider_fixtures['folder_metadata'], 'root') assert od_path.identifier == root_provider_fixtures['folder_id'] assert str(od_path) == '/teeth/' assert len(od_path.parts) == 2 ids = [x.iden...
bramfoo/solarstats
tests/__init__.py
Python
gpl-2.0
82
0
import loggin
g # Disable logging in unit t
ests logging.disable(logging.CRITICAL)
hacpai/show-me-the-code
Python/0033/main.py
Python
gpl-2.0
540
0.038889
import math def square_root ( a ): """Computes squar root of a """ espilon = 0.1e-11 x = a while True: y = ( x + a / x ) / 2.0 if abs( y - x ) < espilon: return y x = y def test_square_root(): """Compares custom square and math.sqrt. """ a = 1
.0 while a < 10.0: print a, '{:<13}'.format( square_root( a ) ), \ '{:<1
3}'.format( math.sqrt( a ) ), \ abs( square_root( a ) - math.sqrt( a ) ) a += 1 test_square_root()
pydicom/sendit
sendit/apps/main/management/commands/export_metrics.py
Python
mit
1,497
0.014028
from sendit.logger import bot from sendit.apps.main.models import Batch from django.core.management.base import ( BaseCommand ) from sendit.apps.main.models
import Batch from sendit.apps.main.tasks import import_dicomdir from sendit.apps.main.utils import ls_fullpath from sendit.apps.api.utils import get_size import sys import os import datetime import pandas class Command(BaseCommand): help = '''export metrics about size and times to file''' def handle...
'start_time','finish_time', 'total_time_sec','total_time_min']) output_file = 'sendit-process-time-%s.tsv' %datetime.datetime.today().strftime('%Y-%m-%d') for batch in Batch.objects.all(): df.loc[batch.id,'batch_id'] = batch.id df.loc[ba...
mattduan/proof
ProofResourceStrategy.py
Python
bsd-3-clause
946
0.004228
""" ProofResourceStrategy is the real implementation of initializing the resource data for ProofResource. There can be multiple strategies for one ProofResource. Main considerations are configure file, database (may use a ProofInstance), XML file. This is the base class with all interfaces needed by ProofResource. Eac...
resource interfaces, we can make ProofInstance work both as stand-alone and shared persistent data layer. It also make testing easier by creating some dummy strategy implementations. """ __version__='$Revision: 117 $'[11:-2] __author__ = "Duan Guoqiang (mattgduan@gmail.com)" import logging class ProofResourceStrat...
def getDatabaseMap(self, schema): pass
sputnick-dev/weboob
modules/lutim/browser.py
Python
agpl-3.0
1,959
0.001021
# -*- coding: utf-8 -*- # Copyright(C) 2015 Vincent A # # This file is part of weboob. # # weboob 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. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANT
Y; 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 weboob. If not, see <http://www.gnu.org/licenses/>. import math from ur...
jentjr/enviropy
enviropy/io/file.py
Python
mit
123
0.01626
import
pandas as pd from enviropy import Enviropy def read_csv(fname): df = p
d.read_csv(fname) return Enviropy(df)
pythonvlc/PyConES-2015
pycones/blog/admin.py
Python
mit
336
0.002976
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import ModelForm, TextInput fr
om django.contrib import admin from blog.models import Post class PostAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'created', 'status'] list_filter = ('status', ) ad
min.site.register(Post, PostAdmin)
yosefk/heapprof
ok.py
Python
bsd-2-clause
823
0.010936
#!/usr/bin/python '''test that the build and run results are OK''' # threads.heapprof sh
ould have 2 call stacks allocating 1024 blocks each import commands, sys print 'testing that *.heapprof files contain the expected results...' assert commands.getoutput("grep ' 1024 ' threads.heapprof | wc -l").strip() == '2' second = open('second.heapprof').read() if 'no heap blocks foun
d' in second: print "threads.heapprof is OK but second.heapprof is not - perhaps gdb's gcore command doesn't work? Is it gdb 7.2 and up?" print "anyway, this test failed but presumably heapprof itself works correctly." sys.exit() assert '1048576 [1048576]' in second assert '1048576 [131073, 131073, 131071, 131073...
DevinDewitt/pyqt5
examples/quick/scenegraph/customgeometry/customgeometry.py
Python
gpl-3.0
5,911
0.005414
#!/usr/bin/env python ##################################
########################################### ## ## Copyright (C) 2013 Riverbank Computing Limited. ## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file under the terms of the BSD license as follows: ## ## "Redi...
on, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions ...
achamely/omniwallet
api/debug.py
Python
agpl-3.0
530
0.032075
import os, sys, commands def print_debug( msg, verbose ): data_dir_root = os.environ.get('DATADIR') de
bug_level = int(os.environ.get('DEBUGLEVEL')) #print the message to debug log if debug variable is set #add 'from debug import *' to header # call with print_debug("my message",5) # outputs to Datadir/debug.log if the number above is > than the number in Datadir/debug.level if int(verbose) < debug_level:...
s.getoutput('echo '+msg+' >> '+data_dir_root+'/debug.log') return 1 return 0
dsweet04/rekall
rekall-core/rekall/plugins/renderers/xls.py
Python
gpl-2.0
9,365
0.000427
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # Authors: # Michael Cohen <scudette@google.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 ...
session=self.session, renderer=self.renderer.delegate_text_renderer) def RenderHeader(self, worksheet, column): cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.value = column.name cell.style = HEADER_STYLE
# Advance the pointer by 1 cell. worksheet.current_column += 1 def RenderCell(self, value, worksheet, **options): # By default just render a single value into the current cell. cell = worksheet.cell( row=worksheet.current_row, column=worksheet.current_column) cell.val...
diekhans/ga4gh-server
ga4gh/datamodel/references.py
Python
apache-2.0
15,873
0.000126
""" Module responsible for translating reference sequence data into GA4GH native objects. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import hashlib import json import os import random import pysam import ga4gh.datamodel as datamodel import ga4gh....
this ReferenceSet. """ return len(self._referenceIds) def getReferenceByIndex(self, index): """ Returns the reference at the specified index in this ReferenceSet. """ return self._referenceIdMap[self._referenceIds[index]] def getReferenceByName(self, name): ...
lf._referenceNameMap: raise exceptions.ReferenceNameNotFoundException(name) return self._referenceNameMap[name] def getReference(self, id_): """ Returns the Reference with the specified ID or raises a ReferenceNotFoundException if it does not exist. """ i...
b-ritter/python-notes
concurrency/tests_integration/test_collection_times.py
Python
mit
1,528
0.003272
from concurrency.get_websites import get_number_of_links import time # Run get_number_of_links and compare it to a serial version # stub out load_url with a sleep function so the time is always the same # Show that the concurrent version takes less time than the serial import unittest from unittest.mock import patch...
da foo: time.sleep(self.loadtime) concurrent_start = time.time() list(get_number_of_links(self.fake_urls)) concurrent_total = time.time() -
concurrent_start serial_start = time.time() get_number_of_links_serial(self.fake_urls) serial_total = time.time() - serial_start print("Concurrent collection: {}".format(concurrent_total)) print("Serial collection: {}".format(serial_total)) self.assertLess(concurrent_to...
2Habibie/ctocpp
c2cpp/pmake.py
Python
gpl-2.0
1,606
0.009963
#!/usr/bin/env python """ C to C++ Translator Convert a C program or whole project to C++ Copyright (C) 2001-2009 Denis Sureau 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 F...
5 Mass Ave, Cambridge, MA 02139, USA. webmaster@scriptol.com http://www.scriptol.com PMAKE Compile a list of sources """ import os import string import sys # remove unwanted codes from lines def chop(n): while (len(n) > 1) & (n[-1] in ("\n", "\r")): n = n[0:-1] return n ...
fic.close() sortie = open("test", "w") sys.stdout = sortie # scan the list of sources and compile each .C one for n in liste: n = chop(n) if os.path.isdir(n): continue node, ext = os.path.splitext(n) ext = string.upper(ext) if ext in [ ".c", ".C" ]: print "compiling " + n, os.system("bcc3...
webadmin87/midnight
midnight_catalog/services.py
Python
bsd-3-clause
1,282
0.00266
from django.conf import settings from django.db.models import Prefetch from midnight_catalog.models import Product, ParamValue def get_all(slug=None): """ Возвращает QuerySet содержащий выборку товаров :param slug: символьный код категории каталога, если не задан выбираются товары в не зависимости от кате...
attr(settings, 'MIDNIGHT_CATALOG_PREFETCH_PARAMS', False): q = q.prefetch_related(Prefetch("paramvalue_set", queryset=ParamVal
ue.objects.published().order_by('sort').prefetch_related("param"))) q = q.prefetch_related('sections').order_by('sort', '-id') return q.all() def get_one(slug): """ Возвращает один товар :param slug: символьный код товара :return: """ item = Product.objects.published()\ .pref...
oeeagle/quantum
neutron/plugins/nicira/extensions/maclearning.py
Python
apache-2.0
1,838
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 Nicira Networks, 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.apac...
method def get_alias(cls): return "mac-learning" @classmethod def get_description(cls): return "Provides mac learning capabilities" @classmethod def get_namespace(cls):
return "http://docs.openstack.org/ext/maclearning/api/v1.0" @classmethod def get_updated(cls): return "2013-05-1T10:00:00-00:00" @classmethod def get_resources(cls): """Returns Ext Resources.""" return [] def get_extended_resources(self, version): if versio...
Jannes123/inasafe
safe/gui/widgets/test/test_dock.py
Python
gpl-3.0
37,784
0.000106
# coding=utf-8 """ InaSAFE Disaster risk assessment
tool developed by AusAid and World Bank - **GUI Test Cases.** Contact : ole.moller.nielsen@gmail.com .. note:: 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. """ __author__ = 'tim@kartoza.com' __date__ = '10/01/2011' __copyright__ = ('Copyright 2012, Australia Indonesia Facility for ' 'Disaster Reduction') import unittest import sys import os import logging import codecs from os.path import join fro...
buhe/judge
sysinfo.py
Python
agpl-3.0
1,249
0.001601
import os from multiprocessing import cpu_count _cpu_co
unt = cpu_count() if hasattr(os, 'getloadavg'): def load_fair(): return 'load', os.getloadavg()[0] / _cpu_count else: from winperfmon import PerformanceCounter from threading import Thread from collections import deque from time import sleep class SystemLoadThread(Thread): def...
self.load = 0.5 self.counter = PerformanceCounter(r'\System\Processor Queue Length', r'\Processor(_Total)\% Processor Time') def run(self): while True: pql, pt = self.counter.query() self.samples.append(pql) if pt >= 100: ...
Tassemble/jewelry
polls/admin.py
Python
mit
475
0.023158
from django.contrib import admin # Register your models here. from polls.models import Question,Choice class ChoiceInline(admin.TabularInline):
model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fields = ["question_text", "pub_date"] inlines = [ChoiceInline] list_display = ('questio
n_text', 'pub_date', 'was_published_recently') search_fields = ['question_text'] list_filter = ['pub_date'] admin.site.register(Question, QuestionAdmin)
gdetrez/MyConf
apps/people/management/commands/addperson.py
Python
agpl-3.0
933
0.004287
from people.models import Person from optparse import make_option try: import json except ImportError: try: import simplejson as json except ImportError: raise ImportError("Neither json or simplejson are available on your system") from django.core.management.base import BaseCommand,
CommandError from django.db.models import Count class Command(BaseCommand): args = 'NAME' help = 'Export speakers from the database' option_list = BaseCommand.option_list + ( make_option('--staff', action='store_true', dest='sta
ff', default=False, help='This person is staff'), ) def handle(self, *args, **options): name = u" ".join(map(lambda s: s.decode("utf8"),args)) print options person = Person(name=name, staff=options['staff']) person.save() print...
lfairchild/PmagPy
programs/core_depthplot.py
Python
bsd-3-clause
8,467
0.005551
#!/usr/bin/env pythonw #from __future__ import print_function import sys import wx import os import matplotlib if matplotlib.get_backend() != "WXAgg": matplotlib.use("WXAgg") import matplotlib.pyplot as plt from pmagpy import pmagplotlib import pmagpy.command_line_extractor as extractor import pmagpy.ipmag as ipm...
ta (if this is set, you don't need the -LP) -sym SYM SIZE, symbol, size for continuous points (e.g., ro 5, bs 10, g^ 10 for red dot, blue square, green triangle), default is blue dot at 5 pt -D do not plot declination -M do not plot magnetization -log plot magnetization on a log scale ...
max [in m] depth range to plot -n normalize by weight in er_specimen table -Iex: plot the expected inc at lat - only available for results with lat info in file -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma) TS: [ck95, gts04, gts12] ...
cryptapus/electrum
electrum/gui/kivy/uix/dialogs/qr_scanner.py
Python
mit
1,153
0.001735
from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder Factory.register('QRScanner', module='electrum.gui.kivy.qr_scanner') class QrScannerDialog(Factory.AnimatedPopup): __events__ = ('on_complete', ) def on_symbols(self, instance, value): instance.stop() sel...
7, 1 #background: 'atlas://electrum/gu
i/kivy/theming/light/dialog' on_activate: qrscr.start() qrscr.size = self.size on_deactivate: qrscr.stop() QRScanner: id: qrscr on_symbols: root.on_symbols(*args) ''')
linyvxiang/tera
test/testcase/test_root.py
Python
bsd-3-clause
3,730
0.006702
""" Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. """ import common from conf import const def setUp(): """ set env """ common.print_debug_msg(1, "setup()") def test_create_user(): cmd = ...
wd root helloroot --flagfile=" + const.user_root_flag_path common.execute_and_check_returncode(cmd, 0) #restore the original root password in flag file cmd = ("sed -i 's/^--tera_user_passcode=.*/--tera_user_passcode=helloroot/' " + const.user_root_flag_path) common.execute_and_check_returncod...
oops z1pw2 --flagfile=" + const.user_root_flag_path common.execute_and_check_returncode(cmd, 255) def test_addtogroup(): cmd = "./teracli user addtogroup z1 z1g --flagfile=" + const.user_root_flag_path common.execute_and_check_returncode(cmd, 0) cmd = "./teracli user show z1" common.check_show_use...
ddico/odoo
addons/sale_product_configurator/__init__.py
Python
agpl-3.0
93
0
# -*- cod
ing: utf-8 -*- from . import models from . import controlle
rs from . import wizard
jlaine/django-timegraph
timegraph/admin.py
Python
bsd-2-clause
2,072
0.005794
# -*- coding: utf-8 -*- # # django-timegraph - monitoring graphs for django # Copyright (c) 2011-2012, Wifirst # Copyright (c) 2013, Jeremy Lainé # All rights reserved. # # See AUTHORS file for a full list of contributors. # # Redistribution and use in source and binary forms, with or without modification, # are permit...
RACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from django.contrib import admin from timegraph.models import Graph, Metric class GraphAdmin(admin.ModelAdmin): list_display = ('slug', ...
rch_fields = ('slug', 'title') class MetricAdmin(admin.ModelAdmin): list_display = ('name', 'parameter', 'type', 'unit', 'rrd_enabled', 'graph_order') list_filter = ('type', 'unit', 'rrd_enabled') search_fields = ('name', 'parameter') admin.site.register(Graph, GraphAdmin) admin.site.register(Metric, Metr...
s-good/AutoQC
tests/EN_stability_check_validation.py
Python
mit
2,925
0.008547
import qctests.EN_stability_check import util.testingProfile import numpy import util.main as main ##### EN_stability_check ---------------------------------------------- class TestClass(): parameters = { "table": 'unit' } def setUp(self): # this qc test will go looking for the profile ...
rovided in McDougall padded with the same level to avoid flagging the entire profile ''' p = util.testingProfile.fakeProfile([13.5, 25.5, 20.4, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5], [0, 10, 20, 30, 40, 50, 60,
70, 80], salinities=[40, 35, 20, 40, 40, 40, 40, 40, 40], pressures=[8000, 2000, 1000, 8000, 8000, 8000, 8000, 8000, 8000], uid=8888) qc = qctests.EN_stability_check.test(p, self.parameters) truth = numpy.ma.array([False, True, True, False, False, False, False, False, False], mask=False) assert...
EnergyID/opengrid
scripts/job_cache_anonymous_houseprint.py
Python
gpl-2.0
730
0.005479
# -*- coding: utf-8 -*- """ Script to cache anonymous houseprint data into hp_anonymous.
pkl Created on 05/07/2014 by Roel De Coninck """ import os, sys import inspect script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # add the path to openg
rid to sys.path sys.path.append(os.path.join(script_dir, os.pardir, os.pardir)) from opengrid.library.houseprint import Houseprint ############################################################################## hp = Houseprint() all_sensordata = hp.get_all_fluksosensors() print('Sensor data fetched') hp.sav...
johnkastler/aws
get_account_urls.py
Python
gpl-3.0
456
0.013158
#!/usr/bin/env python from keyring i
mport get_password from boto.iam.connection import IAMConnection im
port lib.LoadBotoConfig as BotoConfig from sys import exit envs = ['dev', 'qa', 'staging', 'demo', 'prod'] for env in envs: id = BotoConfig.config.get(env, 'aws_access_key_id') key = get_password(BotoConfig.config.get(env, 'keyring'), id) conn = IAMConnection(aws_access_key_id=id, aws_secret_access_key=key) ...
jmbott/test-repo
motion_cam.py
Python
mit
1,069
0
import time import picamera import RPi.G
PIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) GPIO.setup(18, GPIO.OUT) GPIO.output(18, False) while True: if(GPIO.input(23) == 1): print "motion" GPIO.output(18, True) with picamera.PiCamera
() as camera: # Turn the camera's LED off camera.led = False # Take video camera.resolution = (1280, 720) filename = 'video%02d.h264' % i camera.start_recording(filename) while(GPIO.input(23) == 1): camera.wait_recording...
enkidulan/enkiblog
src/enkiblog/core/deform/tempstorage.py
Python
apache-2.0
2,365
0
import os.path from uuid import uuid4 import shutil import logging logger = logging.getLogger(__name__) _MARKER = object() class FileUploadTempStore(object): session_storage_slug = 'websauna.tempstore' def __init__(self, request): self.tempdir = request.registry.settings['websauna.uploads_tempdir'...
f _tempstore_set(self, name, data): # cope with sessioning implementations that cant deal with # in-place mutation of mutable values (temporarily?) existing = self.session.get(self.session_storage_slug, {}) existing[name] = data self.session[self.session_storage_slug] = existing ...
file_name = os.path.join(self.tempdir, randid) try: os.remove(file_name) except OSError: pass def get(self, name, default=None): data = self.session.get(self.session_storage_slug, {}).get(name) if data is None: return default...
presidentielcoin/presidentielcoin
qa/rpc-tests/bip68-sequence.py
Python
mit
18,409
0.003477
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Presidentielcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test BIP68 implementation # from test_framework.test_framework import PresidentielcoinTestF...
NOT_FINAL_ERROR = "64: non-BIP68-final" class BIP68Test(PresidentielcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.op
tions.tmpdir, ["-debug", "-blockprioritysize=0"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-blockprioritysize=0", "-acceptnonstdtxn=0"])) self.is_network_split = False self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"] connect_nodes(self.nodes[0], 1) ...
Jgarcia-IAS/SAT
openerp/addons-extra/odoo-pruebas/odoo-server/addons-extra/ifrs_report/wizard/ifrs_report_wizard.py
Python
agpl-3.0
7,032
0.002418
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
context = {} res = super(ifrs_report_wizard, self).default_get( cr, uid, fields, context=context) # res.update({'uid_country': # self._get_country_code(cr,uid,context=context)}) return res def _get_period(self, cr, uid, context={}): """ Return the current ...
d_obj.find( cr, uid, time.strftime('%Y-%m-%d'), context=context) period_id = ids[0] return period_id def _get_fiscalyear(self, cr, uid, context={}, period_id=False): """ Return fiscalyear id for the period_id given. If period_id is nor given then return the current ...
emacsen/changemonger
features.py
Python
agpl-3.0
10,844
0.003689
## Changemonger: An OpenStreetMap change analyzer ## Copyright (C) 2012 Serge Wroclawski ## ## 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...
egories are precision 3 by default" return 3 def compare_precision(a, b): """Compare the precision of two features""" return b.precision - a.precision class FeatureDB: """This is the abstraction against using the features""" def __init__(se
lf, directory = 'features'): """Initialize feature database, use the argument as the directory""" self._simple = [] self._magic = [] # We almost never iterate through categories, but we do call # them by name a lot self._categories = {} # The index contains unique...
xaratustrah/pypiscope
zmq_listener.py
Python
gpl-3.0
1,215
0
""" A client/server code for Raspberry Pi ADC input Xaratustrah@GitHUB 2016 adapted from: https://wiki.python.org/moin/PyQt/Writing%20a%20client%20for%20a%20zeromq%20service """ from PyQt5.QtCore import pyqtSignal, QThread import zmq class ZMQListener(QThread): message = pyqtSignal(str) err_msg = pyqtSig...
pic_filter = topic_filter self.running = True context = zmq.Context() try: self.sock = context.socket(zmq.SUB) self.sock.connect("tcp://{}:{}".format(self.host, self.port)) self.sock.setsockopt_string(zmq.SUBSCRIBE, self.topic_filter) except(Connect...
ncelled. Aborting...') def loop(self): while self.running: ba = self.sock.recv() self.message.emit(ba.decode("utf-8")) def __del__(self): self.terminate() self.quit() self.wait()
GoogleCloudPlatform/analytics-componentized-patterns
retail/recommendation-system/bqml-scann/ann_grpc/match_pb2_grpc.py
Python
apache-2.0
4,364
0.008937
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import match_pb2 as match__pb2 class MatchServiceStub(object): """MatchService is a Google managed service for efficient vector similarity search at sc...
)) # This class is part of an EXPERIMENTAL API. class MatchService(object): """MatchService is a Google managed
service for efficient vector similarity search at scale. """ @staticmethod def Match(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, ...
PanDAWMS/panda-server
pandaserver/test/lsst/lsstSubmit.py
Python
apache-2.0
5,693
0.006499
import sys import time import uuid import pandaserver.userinterface.Client as Client from pandaserver.taskbuffer.JobSpec import JobSpec from pandaserver.taskbuffer.FileSpec import FileSpec aSrvID = None prodUserNameDefault = 'unknown-user' prodUserName = None prodUserNameDP = None prodUserNamePipeline = None site = '...
E_TASK), \ 'PIPELINE_EXECUTIONNUMBER': str(PIPELINE_EXECUTIONNUMBER), \ 'PIPELINE_STREAM': str(PIPELINE_STREAM), \ 'PIPELINE_PROCESSINSTANCE': str(PIPELINE_PROCESSINSTANCE) \ } else: jobName = "%s" % str(uuid.uuid4()) if PIPELINE_STREAM is not None: jobDefinitionID = PIPELINE_STREAM else: ...
D = jobDefinitionID job.jobName = jobName job.transformation = 'http://pandawms.org/pandawms-jobcache/lsst-trf.sh' job.destinationDBlock = datasetName job.destinationSE = 'local' job.currentPriority = 1000 job.prodSourceLabel = 'panda' job.jobParameters = ' --lsstJobParams="%s" ' % lsstJobParams if prodUserNa...
globaltoken/globaltoken
test/functional/feature_bip9_softforks.py
Python
mit
12,919
0.004722
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BIP 9 soft forks. Connect to a single node. regtest lock-in with 108/144 block signalling activat...
k.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEG
ATE, OP_CHECKSEQUENCEVERIFY, OP_DROP class BIP9SoftForksTest(ComparisonTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [['-whitelist=127.0.0.1']] self.setup_clean_chain = True def run_test(self): self.test = TestManager(self, self.options.tmpdir)...
GAngelov5/Sportvendor
sportvendor/sportvendor/users/forms.py
Python
gpl-2.0
1,164
0
from django.forms import ModelForm from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserLogin(ModelForm): class Meta: model = User fields = ['username', 'password'] class UserRegister(UserCreationForm): email = ...
['last_name'] if commit: user.save() return user class UserProfile(ModelForm): class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name'] def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs) self.fields["username"].disabled = True self.fields["email"].disabled = True