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
thergames/thergames.github.io
lib/tomorrow-pygments/styles/tomorrownighteighties.py
Python
mit
5,525
0.000362
# -*- coding: utf-8 -*- """ tomorrow night eighties --------------------- Port of the Tomorrow Night Eighties colour scheme https://github.com/chriskempson/tomorrow-theme """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, Text, \ Number, Operator, Generic, Whit...
"", # class: 'mh'
Number.Integer: "", # class: 'mi' Number.Integer.Long: "", # class: 'il' Number.Oct: "", # class: 'mo' Literal: ORANGE, # class: 'l' Literal.Date: GREEN, # class: 'ld' String: ...
magul/pywikibot-core
tests/eventstreams_tests.py
Python
mit
8,303
0
# -*- coding: utf-8 -*- """Tests for the eventstreams module.""" # # (C) Pywikibot team, 2017 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals from types import FunctionType from tests import mock from pywikibot.comms.eventstreams import EventStreams from...
.format(fam, site)) stream = 'recentchanges' e = EventStreams(stream=stream) self.assertEqual( e._url, 'https://stream.wikimedia.org/v2/stream/'
+ stream) self.assertEqual(e._url, e.url) self.assertEqual(e._url, e.sse_kwargs.get('url')) self.assertIsNone(e._total) self.assertEqual(e._stream, stream) def test_url_missing_stream(self): """Test EventStreams with url from site with missing stream.""" with self.as...
googleads/google-ads-python
google/ads/googleads/interceptors/metadata_interceptor.py
Python
apache-2.0
5,368
0.000186
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
a) metadata.append(self.developer_token_meta) if self.login_customer_id_meta: metadata.append(self.login_customer_id_meta) if self.linked_customer_id_meta: metadata.append(self.linked_customer_id_meta) client_call_details = self._update_client_call_details_met...
def intercept_unary_unary(self, continuation, client_call_details, request): """Intercepts and appends custom metadata for Unary-Unary requests. Overrides abstract method defined in grpc.UnaryUnaryClientInterceptor. Args: continuation: a function to continue the request proce...
tgalal/yowsup
yowsup/layers/protocol_media/protocolentities/message_media_downloadable_image.py
Python
gpl-3.0
1,903
0.003153
from .message_media_downloadable import DownloadableMediaMessageProtocolEntity from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_image import ImageAttributes from yowsup.layers.protocol_messages.protocolentities.attributes.attributes_message_meta import MessageMetaAttributes from yowsup.layers...
_attributes.caption = value if value is not None else
""
softctrl/AndroidPinning
tools/pin-b64.py
Python
gpl-3.0
1,590
0.00566
#!/usr/bin/env python """pin generates SPKI pin hashes from X.509 PEM files.""" __author__ = "Moxie Marlinspike" __email__ = "[email protected]" __license__= """ Copyright (c) 2011 Moxie Marlinspike <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms ...
nd me an email. """ from M2Crypto import X509 import sys, binascii, hashlib, base64 def main(argv): if len(argv) < 1: print "Usage: pin.py <certificate_path>" return x509 = X509.load_cert(argv[0]) spki = x509.get_pubkey() encodedSpki =
spki.as_der() digest = hashlib.sha1() digest.update(encodedSpki) print "Calculating PIN for certificate: " + x509.get_subject().as_text() byteResult = digest.digest() print "Pin Value: " + binascii.hexlify(byteResult) print "Pin Value: " + base64.b64encode(byteResult) if __name__ == '__main_...
mesosphere/marathon
tests/shakedown/shakedown/dcos/marathon.py
Python
apache-2.0
4,526
0.001989
import contextlib import pytest import logging from distutils.version import LooseVersion from .service import service_available_predicate from ..clients import marathon from ..matcher import assert_that, eventually, has_len logger = logging.getLogger(__name__) marathon_1_3 = pytest.mark.skipif('marathon_version_l...
ytest.mark.skipif('marathon_version_less_than("1.4")') marathon_1_5 = pytest.mark.skipif('marathon_version_less_than("1.5")')
def marathon_version(client=None): client = client or marathon.create_client() about = client.get_about() # 1.3.9 or 1.4.0-RC8 return LooseVersion(about.get("version")) def marathon_version_less_than(version): return marathon_version() < LooseVersion(version) def mom_version(name='marathon-user'...
litui/openparliament
parliament/committees/admin.py
Python
agpl-3.0
1,334
0.008246
from django.contrib import admin from parliament.committees.models import * class CommitteeAdmin(admin.ModelAdmin): list_display = ('short_name', 'slug', 'latest_session', 'display') list_filter = ('sessions', 'display') class CommitteeInSessionAdmin(admin.ModelAdmin): list_display = ('committee', 'acron...
ce', 'activities') search_fields = ['number', 'committee__name_en', 'source_id'] class ReportAdmin(admin.ModelAdmin): list_display = ('committee', 'number', 'session', 'name', 'government_response') list_filter = ('committee', 'session', 'government_response') search_fields =
('name_en', 'number') class ActivityAdmin(admin.ModelAdmin): list_display = ('name_en', 'committee', 'study') list_filter = ('committee', 'study') search_fields = ('name_en',) admin.site.register(Committee, CommitteeAdmin) admin.site.register(CommitteeInSession, CommitteeInSessionAdmin) admin.site.re...
Fantomas42/veliberator
veliberator/grabber.py
Python
bsd-3-clause
1,041
0.000961
"""Grabber for collecting data""" import urllib2 from random import sample from veliberator.settings import PROXY_SERVERS class Grabber(object): """Url encapsultation for making request throught HTTP""" page = None data = None def __init__(self, url, proxies=PROXY_SERVERS): """Init the grabb...
self.proxies = proxies self.opener = self.build_opener() def build_opener(self): """Build the url opener""" handlers = [] if self.proxies: server = sample(self.proxies, 1)[0] handlers.append(urllib2.ProxyHandler({'http': server})) return url...
abbed""" if self.data: return self.data try: self.page = self.opener.open(self.url) self.data = ''.join(self.page.readlines()) self.page.close() return self.data except: return ''
aosingh/lexpy
lexpy/tests/test_dawg.py
Python
gpl-3.0
12,133
0.004616
import os import unittest from lexpy.dawg import DAWG from lexpy.utils import build_dawg_from_file from lexpy.exceptions import InvalidWildCardExpressionError HERE = os.path.dirname(__file__) large_dataset = os.path.join(HERE, 'data/ridyhew_master.txt') small_dataset = os.path.join(HERE, 'data/TWL06.txt') class Te...
assertEqual(4, self.dawg.get_word_count(), "Word count not equal") self.assertTrue(self.dawg.contains_prefix('ash'), "Prefix should be present in DAWG") self.assertEqual(sorted(self.dawg.search_with_prefix('ash')), sorted(['ashlame', 'ashley', 'ashlo']), 'The lists should b...
search(self): self.dawg = DAWG() s
kaixinjxq/web-testing-service
wts/tests/csp/csp_font-src_cross-origin_allowed-manual.py
Python
bsd-3-clause
2,615
0.000765
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) _CSP = "font-src " + url1 response.headers.set("Content-Security-Policy", _CSP) response....
L, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING ...
DAMAGE. Authors: Hao, Yunfei <[email protected]> --> <html> <head> <title>CSP Test: csp_font-src_cross-origin_allowed</title> <link rel="author" title="Intel" href="http://www.intel.com"/> <link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#font-src"/> <meta name="flags" c...
galaxy-team/website
newrelic/hooks/framework_twisted.py
Python
agpl-3.0
20,328
0.002312
from __future__ import with_statement import logging import types import urllib import sys import weakref import UserList import newrelic.api.application import newrelic.api.object_wrapper import newrelic.api.transaction import newrelic.api.web_transaction import newrelic.api.function_trace import newrelic.api.error_...
request object # in the transaction as only able to stash the transaction in a # deferred. Need to use a weakref to avoid an object cycle which # may prevent cleanup of transaction. transaction._nr_current_request = weakref.ref(self._nr_instance) try: # Call the or...
n turn # called can return a result immediately which means user # code should have called finish() on the request, it can # raise an exception which is caught in process() function # where error handling calls finish(), or it can return that # it is not done ...
freevoid/django-datafilters
setup.py
Python
mit
1,032
0.006783
from setuptools import setup, find_packages readme_file = 'README.rst' setup( name='datafilters', version='0.3.3', packages=find_packages('.'),
package_data = {'': [ 'locale/*/LC_MESSAGES/django.po', 'locale/*/LC_MESSAGES/django.mo', ]}, # Metadata author='Nikolay Zakharov', author_email='[email protected]', url = 'https://github.com/freevoid/django-datafilters', description='Neat QuerySet filter for dja
ngo apps with filterforms based on django forms', long_description=open(readme_file).read(), keywords='django filter datafilter queryset', license = 'MIT', install_requires=['django>=1.3'], extras_require={ 'extra_specs': ['forms-extras'], }, classifiers=[ 'Development Stat...
nikdoof/limetime
app/timer/forms.py
Python
bsd-3-clause
204
0.004902
from django im
port forms from timer.models import Timer, Location class TimerForm(forms.ModelForm): location = forms.ModelChoiceField(Location.objects.none()) class Meta:
model = Timer
nsnam/ns-3-dev-git
src/core/examples/sample-simulator.py
Python
gpl-2.0
2,886
0.011781
# -*- Mode:Python; -*- # /* # * Copyright (c) 2010 INRIA # * # * 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 b...
: """Simple event handler.""" print ("Member method received event at", ns.core.Simulator.Now().GetSeconds(), \ "s started at", value, "s") ## Example function - starts MyModel. ## \param [in] model The instance of MyModel ## \return None. def ExampleFunction(model): print ("ExampleFunc...
ore.Simulator.Now().GetSeconds(), "s") model.Start() ## Example function - triggered at a random time. ## \param [in] model The instance of MyModel ## \return None. def RandomFunction(model): print ("RandomFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s") ## Example function - triggered ...
cwho/pyfileserver
PyFileServer/pyfileserver/httpdatehelper.py
Python
lgpl-2.1
2,135
0.020141
""" httpdatehelper ============== :Module: pyfileserver.httpdatehelper :Author: Ho Chun Wei, fuzzybr80(at)gmail.com :Project: PyFileServer, http://pyfilesync.berlios.de/ :Copyright: Lesser GNU Public License, see LICENSE file attached with package HTTP dates helper - an assorted library of helpful date funct...
GMT ; RFC 822, updated by RFC 1123 try: vtime = time.strptime(timeformat, "%a, %d %b %Y %H:%M:%S GMT") return vtime except: pass # Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC
1036 try: vtime = time.strptime(timeformat, "%A %d-%b-%y %H:%M:%S GMT") return vtime except: pass # Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format try: vtime = time.strptime(timeformat, "%a %b %d %H:%M:%S %Y") return vtime except: pa...
fkie-cad/FACT_core
src/plugins/analysis/string_evaluation/code/string_eval.py
Python
gpl-3.0
1,282
0.0039
import sys from pathlib import Path from analysis.PluginBase import AnalysisBasePlugin from plugins.mime_blacklists import MIME_BLACKLIST_COMPRESSED try: from ..internal.string_eval import eval_strings except ImportError: sys.path.append(s
tr(Path(__file__).parent.parent / 'internal')) from string_eval import eval_strings class AnalysisPlugin(AnalysisBasePlugin): ''' Sort strings by relevance Credits: Original version by Paul Schiffer created during Firmware Bootcamp WT16/17 at University of Bonn Refactored and improved by Frau...
'string_evaluator' DEPENDENCIES = ['printable_strings'] MIME_BLACKLIST = MIME_BLACKLIST_COMPRESSED DESCRIPTION = 'Tries to sort strings based on usefulness' VERSION = '0.2.1' def __init__(self, plugin_administrator, config=None, recursive=True, timeout=300): super().__init__(plugin_administ...
dotpy/offtheshelf
offtheshelf/tests/cmd.py
Python
bsd-3-clause
527
0
"""Comman
d for running unit tests for the module from setup.py""" from distutils.cmd import Command from unittest import TextTestRunner, TestLoader import offtheshelf.tests class TestCommand(Command): """Command for running unit tests for the module from setup.py""" user_options = [] def initialize_options(sel...
1).run(suite)
hoyjustin/ScopusAdapter
CorsTests/test_app_extension.py
Python
mit
9,998
0.0001
# -*- coding: utf-8 -*- """ test ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from tests.base_test import FlaskCorsTes...
n '' @self.app.route('/api/') def test_exact_match(): return '' def test_index(self): ''' If regex does not match, do not set CORS ''' for resp in self.iter_responses('/'): self.assertFalse(ACL_ORIGIN in resp.headers) def test_wildca...
''' Match anything matching the path /api/* with an origin of 'http://blah.com' or 'http://foo.bar' ''' for origin in ['http://foo.bar', 'http://blah.com']: for resp in self.iter_responses('/api/foo', origin=origin): self.assertTrue(ACL_ORIGIN...
cs-au-dk/Artemis
WebKit/Tools/Scripts/webkitpy/layout_tests/views/printing_unittest.py
Python
gpl-3.0
21,671
0.001061
#!/usr/bin/python # Copyright (C) 2010, 2012 Google Inc. 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 lis...
ere shouldn't be a carriage return here; updates() # are meant to be overwritten. self.do_switch_tests('print_update', 'updates', to_buildbot=False
,
ThreatConnect-Inc/tcex
tcex/api/tc/v2/threat_intelligence/mappings/group/group_types/tactic.py
Python
apache-2.0
841
0.003567
"""ThreatConnect TI Email""" # standard library from typing import TYPE_CHECKING # first-party from tcex.api.tc.v2.threat_intelligence.mappings.group.group import Group if TYPE_CHECKING: # first-party from tcex.api.tc.v2.threat_intelligence.threat_intelligence import ThreatIntelligence class Tactic(Group): ...
e ThreatIntelligence Class. name (
str, kwargs): [Required for Create] The name for this Group. owner (str, kwargs): The name for this Group. Default to default Org when not provided """ def __init__(self, ti: 'ThreatIntelligence', **kwargs): """Initialize Class properties.""" super().__init__(ti, sub_type='Tactic', api_...
Aladom/django-mailing
mailing/models/__init__.py
Python
mit
103
0
# -*- codi
ng: utf-8 -*- # Copyright (c) 2016 Aladom S
AS & Hosting Dvpt SAS from .base import * # noqa
KaranToor/MA450
google-cloud-sdk/lib/googlecloudsdk/calliope/__init__.py
Python
apache-2.0
623
0
# Copyright 2014 Google Inc. All Rights Reserved. #
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
se for the specific language governing permissions and # limitations under the License. """Package marker file."""
hovel/pybbm
test/example_thirdparty/example_thirdparty/urls.py
Python
bsd-2-clause
911
0.001098
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django from account.views import ChangePasswordView, SignupView, LoginView from django.conf.urls import include, url from django.contrib import admin from example_thirdparty.forms import SignupFormWithCaptcha urlpatterns = [ url(r'^admin/', in...
ss=SignupFormWithCaptcha), name="registration_register"), url(r"^accounts/login/$", Lo
ginView.as_view(), name="auth_login"), url(r'^accounts/', include('account.urls')), url(r'^captcha/', include('captcha.urls')), url(r'^', include('pybb.urls', namespace='pybb')), ]
tcstewar/testing_notebooks
show_remote_spikes/sink.py
Python
gpl-2.0
399
0
import nengo import numpy as np import redis import struct r = redis.StrictRedis('127.0.0.1') model = nengo.
Network() with model: def receive_spikes(t)
: msg = r.get('spikes') v = np.zeros(10) if len(msg) > 0: ii = struct.unpack('%dI' % (len(msg)/4), msg) v[[ii]] = 1000.0 return v sink_node = nengo.Node(receive_spikes, size_in=0)
Dinoshauer/pryvate
docs/source/conf.py
Python
mit
8,998
0.004779
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=unused-import # pylint: disable=redefined-builtin # # Pryvate documentation build configuration file, created by # sphinx-quickstart on Sat Feb 21 11:31:08 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note...
oplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false,...
ce start file, name, description, authors, manual section). man_pages = [ ('index', 'pryvate', 'Pryvate Documentation', ['Kasper Jacobsen'], 1) ] # I
ethanhlc/streamlink
src/streamlink/plugins/filmon.py
Python
bsd-2-clause
4,570
0.001751
import re from streamlink.compat import urlparse from streamlink.plugin import Plugin from st
reamlink.plugin.api import http, validate from streamlink.stream import HLSStream, RTMPStream CHINFO_URL = "http://www.filmon.com/ajax/getChannelInfo" SWF_URL = "http://www.filmon.com/tv/modules/FilmOnTV/files/flashapp/filmon/FilmonPlayer.swf" VODINFO_URL = "http://www.filmon.com/vod/info/{0}" AJAX_HEADERS = { "R...
"high": 720, "low": 480 } STREAM_TYPES = ("hls", "rtmp") _url_re = re.compile("http(s)?://(\w+\.)?filmon.com/(channel|tv|vod)/") _channel_id_re = re.compile("/channels/(\d+)/extra_big_logo.png") _vod_id_re = re.compile("movie_id=(\d+)") _channel_schema = validate.Schema({ "streams": [{ "name": validat...
f3at/feat
src/feat/test/test_database_client.py
Python
gpl-2.0
2,476
0.000808
from feat.common.serialization import base from feat.common import defer from feat.database import client, document, common as dcommon, emu, migration from feat.test import common cla
ss Inside(d
ocument.VersionedFormatable): type_name = 'dummy' version = 2 document.field("field", None) document.field("nested", None) @staticmethod def upgrade_to_2(snapshot): snapshot['field'] = 'migrated' return snapshot class MigratableDoc(document.VersionedDocument): version =...
eduNEXT/edunext-ecommerce
ecommerce/enterprise/tests/test_utils.py
Python
agpl-3.0
16,925
0.003604
import uuid import ddt import httpretty from django.conf import settings from django.http.response import HttpResponse from django.test import RequestFactory from edx_django_utils.cache import TieredCache from mock import patch from oscar.core.loading import get_class from oscar.test.factories import BasketFactory, ...
erFactory from ecommerce.tests.testcases import TestCase Applicator = get_class('offer.applicator', 'Applicator') TEST_ENTERPRISE_CUSTOMER_UUID = 'cf246b88-d5f6-4908-a522-fc307e0b0c59' @ddt.ddt @httpretty.activate class EnterpriseUtilsTests(EnterpriseServiceMockMixin, TestCase): def setUp(self): super(E...
tUp() self.learner = self.create_user(is_staff=True) self.client.login(username=self.learner.username, password=self.password) def test_get_enterprise_customers(self): """ Verify that "get_enterprise_customers" returns an appropriate response from the "enterprise-customer" E...
sgagnon/lyman-tools
roi/extract_copes.py
Python
bsd-2-clause
9,264
0.005289
#! /usr/bin/env python """ Extract mean parameter estimates from ROI """ import os import sys import re import os.path as op from textwrap import dedent import argparse from subprocess import call from scipy import stats import scipy as sp import numpy as np import pandas as pd import nibabel as nib import lyman fro...
just use roi if not isinstance(hemi, float): if roi_type == 'anat': mask_name = hemi + '-' + roi else: mask_name = hemi + '-' + roi
else: mask_name = roi # Read in the mask as bool using nibabel: if exp['regspace'] == 'mni': # threshold a group level contrast if type(exp['threshold']) in [float, int]: if output: ...
0vercl0k/rp
src/third_party/beaengine/tests/0f383d.py
Python
mit
4,045
0.001236
#!/usr/bin/python # -*- coding: utf-8 -*- # 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) any later version. # # This progra...
/r # vpmaxsd ymm1, ymm2, ymm3/m256 Buffer = bytes.fromhex('c402053d0e') myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Mnemonic, b'v
pmaxsd') assert_equal(myDisasm.repr(), 'vpmaxsd ymm9, ymm15, ymmword ptr [r14]') # EVEX.NDS.128.66.0F38.WIG 3d /r # vpmaxsd xmm1 {k1}{z}, xmm2, xmm3/m128 Buffer = bytes.fromhex('620205063d0e') myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos....
Arthaey/anki
thirdparty/BeautifulSoup.py
Python
agpl-3.0
79,554
0.006247
"""Beautiful Soup Elixir and Tonic "The Screen-Scraper's Friend" http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup parses a (possibly invalid) XML or HTML document into a tree representation. It provides methods and Pythonic idioms that make it easy to navig
ate, search, and modify the tree. A well-formed XML/HTML document yields a well-formed data structure. An ill-formed XML/HTML document yields a correspondingly ill-formed data structure. If your document is only locally well-formed, you can use this library to find and process the well-formed part of it. Beautiful So...
o UTF-8 if you also install these three packages: * chardet, for auto-detecting character encodings http://chardet.feedparser.org/ * cjkcodecs and iconv_codec, which add more encodings to the ones supported by stock Python. http://cjkpython.i18n.org/ Beautiful Soup defines classes for two main parsing strategie...
cloudmesh/cmd3
cmd3/plugins/clear.py
Python
apache-2.0
1,563
0.003199
from cmd3.shell import command from cmd3.console import Console import os import sys class clear: # # CLEAR # def activate_clear(self): """activates the clear command""" pass @command def do_clear(self, arg, arguments): """ Usage: clear ...
anner CHAR The character for the frame. WIDTH Width of the banner INDENT indentation of the banner COLOR the color Options: -c CHAR The character for the frame. [default: #] -n WIDTH The width of t
he banner. [default: 70] -i INDENT The width of the banner. [default: 0] -r COLOR The color of the banner. [default: BLACK] Prints a banner form a one line text message. """ print arguments n = int(arguments['-n']) c = arguments[...
leighpauls/k2cro4
third_party/python_26/Lib/site-packages/win32com/demos/ietoolbar.py
Python
bsd-3-clause
10,756
0.009483
# encoding: latin-1 # PyWin32 Internet Explorer Toolbar # # written by Leonard Ritter ([email protected]) # and Robert Förtsch ([email protected]) """ This sample implements a simple IE Toolbar COM server supporting Windows XP styles and access to the IWebBrowser2 interface. It also demonstrates how to hijack th...
# first get a command target cmdtarget = unknown.QueryInterface(axcontrol.IID_IOleCommandTarget) # then travel over to a service provider serviceprovider = cmdtarget.QueryInterface(pythoncom.IID_IServiceProvider) # finally ask for the internet explore
r application, returned as a dispatch object self.webbrowser = win32com.client.Dispatch(serviceprovider.QueryService('{0002DF05-0000-0000-C000-000000000046}',pythoncom.IID_IDispatch)) # now create and set up the toolbar self.toolbar = IEToolbarCtrl(hwndparent) buttons =...
sebastienhupin/qxrad
qooxdoo/tool/pylib/graph/algorithms/heuristics/__init__.py
Python
lgpl-3.0
1,517
0.000659
# Copyright (c) 2008-2009 Pedro Matiello <[email protected]> # Salim Fadhley <[email protected]> # # 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...
THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """ Set of search heuristics. This subpackage exposes the following heuristics: - L{chow} - L{euclidean} Which ...
lamby/trydiffoscope
trydiffoscope/compare/enums.py
Python
agpl-3.0
170
0.041176
import enum class StateEnum(enum.
IntEnum): queued = 10 running = 20 identical = 30 different = 40 error =
50 timeout = 60
bowlofstew/bii-server
user/user_service.py
Python
mit
12,755
0.001568
from biicode.common.exception import (NotInStoreException, NotFoundException, InvalidNameException, ForbiddenException, AuthenticationException) from biicode.server.authorize import Security from biicode.server.model.user import User from biico...
= JWTCredentialsManagerFactory.new(self.store) token = jwt_auth_manager.get_token_for(brl_user) return token, brl_user, user.ga_client_id else: raise NotFoundException("Invalid
user or token") def confirm_password_reset(self, confirmation_token): ''' Confirms password change. User and password are inside the token ''' try: # Decode token jwt_manager = JWTPasswordResetManagerFactory.new() brl_user, plain_password = jwt_m...
codeback/openerp-cbk_external_adapter
sale_order.py
Python
agpl-3.0
7,807
0.009098
# -*- encoding: utf-8 -*- ############################################################################## # # external_adapter_sale_order # Copyright (c) 2013 Codeback Software S.L. (http://codeback.es) # @author: Miguel García <[email protected]> # @author: Javier Fuentes <[email protected]> # # Th...
# Se obtiene el precio del producto padre prod_id = prod["parent_prod_id"][0] else: prod_id = li
ne["product_id"] product_price = ext_prod_model.get_pricelist(cr, uid, [prod_id], pricelist_id, partner_id)[prod_id][pricelist_id] # Aplicar descuento web company = company_model.read(cr, uid, [1], ["web_discount"])[0] if company["web_discount"]...
Leoniela/nipype
nipype/interfaces/fsl/tests/test_auto_SigLoss.py
Python
bsd-3-clause
1,163
0.022356
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from
nipype.testing import assert_equal from nipype.interfaces.fsl.utils import SigLoss def test_SigLoss_inputs(): input_map = dict(args=dict(argstr='%s', ), echo_time=dict(argstr='--te=%f', ), environ=dict(nohash=True,
usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='-i %s', mandatory=True, ), mask_file=dict(argstr='-m %s', ), out_file=dict(argstr='-s %s', genfile=True, ), output_type=dict(), slice_direction=dict(argstr='-d %s', ...
deepmind/dm_alchemy
dm_alchemy/types/helpers.py
Python
apache-2.0
4,418
0.009959
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. 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 # # U...
+ 1 + int(np.ravel_multi_index( (first_kno
wn, known_val), (num_axes, num_axes))) def partial_perm_from_index( ind: int, num_elements: int, index_to_perm_index: np.ndarray ) -> List[int]: """Converts int to permutation of length 3 with potentially unknown values.""" num_simple_perms = math.factorial(num_elements) if ind < num_simple_perms: retur...
mac389/brainpy
examples/a_2.py
Python
gpl-3.0
2,546
0.021995
from numpy import * from numpy.random import randint from scipy import * import matplotlib.pyplot as plt import neuroTools as tech from matplotlib import rcParams, text #--------------------------------------Plotting Options-------------------------------------------- params = {'backend': 'ps', 'axes.labels...
eights,record[:,iteration-1])) overlap[iteration] = dot(record[:,iteration], memories[2])/float(neuron_count)
fig1 = plt.figure() evol = fig1.add_subplot(211) cevol = evol.imshow(record,aspect='auto',interpolation='nearest', cmap = plt.cm.binary) fig1.colorbar(cevol) similar = fig1.add_subplot(212) similar.plot(overlap) fig = plt.figure() plt.subplots_adjust(hspace=0.3) mems = fig.add_subplot(211) mem_ax = mems.imshow(memori...
vicky2135/lucious
oscar/lib/python2.7/site-packages/faker/providers/address/uk_UA/__init__.py
Python
bsd-3-clause
5,601
0
# coding=utf-8 from __future__ import unicode_literals from random import randint from .. import Provider as AddressProvider class Provider(AddressProvider): address_formats = ['{{street_address}}, {{city}}, {{postcode}}'] building_number_formats = ['#', '##', '###'] city_formats = ['{{city_prefix}} {{f...
узвіз'] @classmethod def city_prefix(cls): return cls.random_element(cls.city_prefixes) @classmethod def postcode(cls): """The code consists of five digits (01000-99999)""" return '{}{}'.format(randint(0, 10), randint(1000, 10
000)) @classmethod def street_prefix(cls): return cls.random_element(cls.street_prefixes)
polyaxon/polyaxon
hypertune/hypertune/search_managers/random_search/manager.py
Python
apache-2.0
2,436
0.000821
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
lyaxon.polyflow import V1RandomSearch class RandomSearchManager(BaseManager): """Random search strategy manager for hyperparameter optimization.""" CONFIG = V1RandomSearch def get_suggestions(self, params: Dict = None) -> List[Dict]: if not self.config.num_runs:
raise ValueError("This search strategy requires `num_runs`.") suggestions = [] params = params or {} rand_generator = get_random_generator(seed=self.config.seed) # Validate number of suggestions and total space all_discrete = True for v in self.config.params.val...
piksels-and-lines-orchestra/inkscape
share/extensions/extrude.py
Python
gpl-2.0
3,989
0.003008
#!/usr/bin/env python ''' Copyright (C) 2007 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 t...
uperpath inkex.localize() class Extrude(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) opts = [('-m', '--mode', 'string', 'mode', 'Lines', 'Join paths with lines or polygons'), ] for o in opts: self.OptionParser.add_option(o[0], ...
dest=o[3], default=o[4], help=o[5]) def effect(self): paths = [] for id, node in self.selected.iteritems(): if node.tag == '{http://www.w3.org/2000/svg}path': paths.append(node) if len(paths) < 2: inkex.errormsg(_('Need at least 2 paths selected'...
nicky-ji/edx-nicky
common/djangoapps/student/admin.py
Python
agpl-3.0
609
0.003284
''' django admin pages for co
urseware model ''' from student.models import UserProfile, UserTestGroup, CourseEnrollmentAllowed from student.models import CourseEnrollment, Registration, PendingNameChange, CourseAccessRole, Cours
eAccessRoleAdmin, School from ratelimitbackend import admin admin.site.register(UserProfile) admin.site.register(UserTestGroup) admin.site.register(CourseEnrollment) admin.site.register(CourseEnrollmentAllowed) admin.site.register(Registration) admin.site.register(PendingNameChange) admin.site.register(CourseAcc...
endlessm/chromium-browser
third_party/angle/third_party/vulkan-validation-layers/src/build-gn/generate_vulkan_layers_json.py
Python
bsd-3-clause
4,768
0.001049
#!/usr/bin/env python # Copyright (C) 2016 The ANGLE Project 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 ...
.path.basename
(json_in_name) layer_name = json_in_fname[:-len('.json.in')] layer_lib_name = layer_name + file_type_suffix json_out_fname = os.path.join(target_dir, json_in_fname[:-len('.in')]) with open(json_out_fname,'w') as json_out_file, \ open(json_in_name) as infile: for ...
carschar/django-popularity
popularity/models.py
Python
agpl-3.0
22,870
0.002973
# This file is part of django-popularity. # # django-popularity: A generic view- and popularity tracking pluggable for Django. # Copyright (C) 2008-2010 Mathijs de Bruin # # 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 ...
is not compatible with this functionality.' if not value: value = now() _SQL_NOW = self._SQL_NOW % connection.ops.value_to_db_datetime(value) return _SQL_NOW def _add_extra(self, field, sql): """ Add the extra parameter 'field' with value 'sql' to the queryset (witho...
r(), \ "Cannot change a query once a slice has been taken" logging.debug(sql) clone = self._clone() clone.query.add_extra({field: sql}, None, None, None, None, None) return clone def select_age(self): """ Adds age with regards to NOW to the QuerySet ...
jordanemedlock/psychtruths
temboo/core/Library/Facebook/Actions/Fitness/Bikes/UpdateBike.py
Python
apache-2.0
4,899
0.005307
# -*- coding: utf-8 -*- ############################################################################### # # UpdateBike # Updates an existing bike action. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file exc...
ue of the Course input for this Chore
o. ((optional, string) The URL or ID for an Open Graph object representing the course.) """ super(UpdateBikeInputSet, self)._set_input('Course', value) def set_EndTime(self, value): """ Set the value of the EndTime input for this Choreo. ((optional, date) The time that the user ended...
catapult-project/catapult
third_party/gsutil/gslib/tests/test_parallelism_framework.py
Python
bsd-3-clause
33,777
0.007727
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to u...
MAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """Unit tests for gsutil parallelism framewor
k.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import functools import mock import os import signal import six import threading import textwrap import time import boto from boto.storage_uri import BucketStorag...
glitchassassin/keyboard
keyboard/_winkeyboard.py
Python
mit
20,607
0.003009
# -*- coding: utf-8 -*- """ This is the Windows backend for keyboard events, and is implemented by invoking the Win32 API through the ctypes module. This is error prone and can introduce very unpythonic failure modes, such as segfaults and low level memory leaks. But it is also dependency-free, very performant well doc...
0x42: ('b', False), 0x43: ('c', False), 0x44: ('d', False), 0x45: ('e', False), 0x46: ('f', False), 0x47: ('g', False), 0x48: ('h', False), 0x49: ('i', False), 0x4a: ('j', False), 0x4b: ('k', False), 0x4c: ('l', False), 0x4d: ('m', False), 0x4e: ('n', False), 0x4f: ('...
: ('p', False), 0x51: ('q', False), 0x52: ('r', False), 0x53: ('s', False), 0x54: ('t', False), 0x55: ('u', False), 0x56: ('v', False), 0x57: ('w', False), 0x58: ('x', False), 0x59: ('y', False), 0x5a: ('z', False), 0x5b: ('left windows', False), 0x5c: ('right windows', F...
luotao1/Paddle
python/paddle/distributed/fleet/runtime/the_one_ps.py
Python
apache-2.0
57,329
0.000994
# Copyright (c) 2020 PaddlePaddle 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 appli...
[" "] * indent) PSERVER_SAVE_SUFFIX = ".shard" def parse_table_class(varname, o_main_program): from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_di
stributed_sparse_op from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_sparse_op for op in o_main_program.global_block().ops: if not is_distributed_sparse_op(op) and not is_sparse_op(op): continue param_name = op.input("W")[0] if param_name == varname an...
lesglaneurs/lesglaneurs
presentation/migrations/0010_auto_20160505_1432.py
Python
gpl-3.0
636
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('presentation', '0009_role_user_userprojectrole'), ] operations = [ migrations.RenameModel( old_name='User',
new_name='Person', ), migrations.RenameModel( old_name='UserProjectRole', new_name='PersonProjectRole', ), migrations.RenameField( model_name='personprojectrole', old_name='user', new_name='p
erson', ), ]
zwChan/VATEC
~/eb-virt/Lib/site-packages/flask/testsuite/subclassing.py
Python
apache-2.0
1,214
0
# -*- coding: utf-8 -*- """ flask.testsuite.subclassing ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test that certain behavior of flask can be customized by subclasses. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import flask import unittest from logging import Str...
e = unittest.TestSuite() suite.addTest(unittest.makeSuite(Flask
SubclassingTestCase)) return suite
VolodyaEsk/selenium-python-vkhatianovskyi
php4dvd/selenium_fixture.py
Python
apache-2.0
272
0
from selenium import webdriver from model.
application import Application import pytest @pytest.fixture(scope="module") def app(request): driver = webdriver.Firefox() driver.implicitly_wait(10) request.addfinalizer(d
river.quit) return Application(driver)
tuturto/pyherc
src/pyherc/data/magic/spell.py
Python
mit
3,082
0.000973
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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 use, copy,...
S OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SH
ALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ Module for spell objects """ from pyherc.aspects import log_d...
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_8_0/if_perf_hourly_broker.py
Python
apache-2.0
73,070
0.002012
from ..broker import Broker class IfPerfHourlyBroker(Broker): contr
oller = "if_perf_hourlies" def index(self, **kwargs): """Lists the available if perf hourlies. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is most efficient. **Inputs** | ``api ver...
:param DeviceID: The internal NetMRI identifier for the device from which interface hourly performance information was collected. :type DeviceID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``defau...
GroestlCoin/electrum-grs
electrum_grs/gui/qt/rbf_dialog.py
Python
gpl-3.0
7,458
0.000805
# Copyright (C) 2021 The Electrum developers # Distributed under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php from typing import TYPE_CHECKING from PyQt5.QtWidgets import (QCheckBox, QLabel, QVBoxLayout, QGridLayout, QWidget, ...
title=_('Bump Fee'), help_text=help_text, ) def rbf_func(self, fee_rate): return self.wallet.bump_fee( tx=self.tx, txid=self.txid, new_fee_rate=fee_rate, coins=self.window.get_coins(), stra
tegies=self.option_index_to_strats[self.strat_combo.currentIndex()], ) def _add_advanced_options(self, adv_vbox: QVBoxLayout) -> None: self.cb_rbf = QCheckBox(_('Keep Replace-By-Fee enabled')) self.cb_rbf.setChecked(True) adv_vbox.addWidget(self.cb_rbf) self.strat_combo = Q...
metabrainz/listenbrainz-server
listenbrainz/mbid_mapping/mapping/typesense_index.py
Python
gpl-2.0
4,028
0.002483
import sys import re import time import datetime import typesense import typesense.exceptions from unidecode import unidecode import psycopg2 import config from mapping.utils import log BATCH_SIZE = 5000 COLLECTION_NAME_PREFIX = 'mbid_mapping_' def prepare_string(text): return unidecode(re.sub(" +", " ", re.s...
nd: log("typesense index: Failed to delete collection '%s'.", str(err)) return 0 def build(client, collection_name): schema = { 'name': collection_name, 'fields': [ { 'name': 'combined', 'type': 'string' }, { 'name':...
], 'default_sorting_field': 'score' } client.collections.create(schema) with psycopg2.connect(config.MBID_MAPPING_DATABASE_URI) as conn: with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as curs: curs.execute("SELECT max(score) FROM mapping.mbid_mapping") ...
DeepThoughtTeam/tensorflow
tensorflow/python/kernel_tests/edit_distance_op_test.py
Python
apache-2.0
6,429
0.002489
# Copyright 2015 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...
cted_output=expected_output) def testEditDistanceProperDistance(self): # In this case, the values are individual characters stored in the # SparseTensor (type DT_STRING) hypothesis_indices = ([[0, i] for i, _ in enumerate("algorithm")] + [[1, i] for i, _ in enumerate("altruistic...
i, _ in enumerate("altruistic")] + [[1, i] for i, _ in enumerate("algorithm")]) truth_values = [x for x in "altruistic"] + [x for x in "algorithm"] truth_shape = [2, 11] expected_unnormalized = [6.0, 6.0] expected_normalized = [6.0/len("altruistic"), 6.0/...
KlubbAlfaRomeoNorge/members
model.py
Python
gpl-2.0
9,213
0.001737
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------- # Portello membership system # Copyright (C) 2014 Klubb Alfa Romeo Norge # # 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 # t...
must be handled # differently. self.update_index() @classmethod def search_member_from_document(cls, document): ret = SearchMember() ret.key = document.doc_id for field in document.fields: if field.name == 'number': ret.number = field.value ...
lue if field.name == 'address': ret.address = field.value if field.name == 'country': ret.country = field.value if field.name == 'type': ret.membertype = field.value if field.name == 'email': ret.email = fiel...
ryanraaum/oldowan.mitotype
oldowan/mitotype/commandline.py
Python
mit
3,160
0.001582
from optparse import OptionParser import os,sys from oldowan.mitotype.matcher import HVRMatcher from oldowan.mitotype.prevalidate import prevalidate_submission def run_command(): """Perform automated human mtDNA haplotype identification.""" # Set up the options parser usage = "usage: %prog [options] sequ...
If we've made it this far we're probably going to have to do some # actual work; initialize the matcher. hvrm = HVRMatcher
() # Do the work, either: # (1) load the fasta file # (2) use sequence passed on the command line working_text = '' if options.use_file: if os.path.exists(args[0]): f = open(args[0], 'r') working_text = f.read() f.close() else: print '...
nickerso/libcellml
tests/resources/generator/dependent_eqns/model.py
Python
apache-2.0
1,256
0.003981
# The content of this file was generated using the Python profile of libCellML 0.2.0. from enum import Enum from math import * __version__ = "0.3.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 1 VARIABLE_COUNT = 2 class VariableType(Enum): VARIABLE_OF_INTEGRATION = 1 STATE = 2 CONSTANT = 3 COMPUTED_...
: "second", "component": "my_component", "type": VariableType.VARIABLE_OF_INTEGRATION} STATE_INFO = [ {"name": "x", "units": "dimensionless", "component": "my_component", "type": Va
riableType.STATE} ] VARIABLE_INFO = [ {"name": "b", "units": "second", "component": "my_component", "type": VariableType.ALGEBRAIC}, {"name": "a", "units": "second", "component": "my_component", "type": VariableType.ALGEBRAIC} ] def create_states_array(): return [nan]*STATE_COUNT def create_variables_a...
mozilla/mozilla-badges
mozbadges/site/teams/views.py
Python
bsd-3-clause
501
0.001996
from mozbadges.views.generic.detail import HybridDetailView from mozbadges.views.generic.list import HybridListView from models import Team class TeamDetailView(HybridDetailView): model = Team pk_url_kwarg = '
team' context_object_name = 'team' template_name = 'teams/detail.html' class TeamListView(HybridListView): model = Team context_object_name = 'teams' template_name = 'teams/list.html' team_detail = TeamDetailView.as_view() team_list = TeamListView.as_vi
ew()
jamesscottbrown/sbml-diff
sbml_diff/miriam.py
Python
bsd-3-clause
4,701
0.002978
import sys from collections import OrderedDict def get_identifiers(obj): """ Given a BeautifulSoup object, find all of the annotations of type "is" (rather than e.g. "isDerivedFrom", or "isHomologTo") """ identifiers = set() if not obj.find("annotation"): return identifiers for a...
two or more sets of annotations\n" % (element_type, tag_id)) print("Set one: \n", get_identifiers(all_identifiers[tag_id])) print("Set two: \n", identifiers) sys.exit() identifier_values = list(all_identifiers.values()) ...
ntifier_values: rename_to = list(all_identifiers.keys())[identifier_values.index(identifiers)] if rename_to != tag_id: elements.append((model, tag_id, rename_to)) all_identifiers[tag_id] = identifiers if len(list(all_identifiers.keys())) == 0: ...
flask-kr/githubarium
githubarium/user.py
Python
mit
2,165
0
from flask import (Blueprint, request, session, g, render_template, url_for, redirect, jsonify) from werkzeug.contrib.cache import SimpleCache from flask.ext.oauthlib.client import OAuth, OAuthException bp = Blueprint('user', __name__) oauth = OAuth() github = oauth.remote_app( 'github', app_...
l=None, access_token_method='POST', access_token_url='https://github.com/login/oauth/access_toke
n', authorize_url='https://github.com/login/oauth/authorize', ) _cache = SimpleCache() @github.tokengetter def get_github_oauth_token(): return session.get('github_token') def authenticated(): """사용자가 GitHub 계정으로 인증한 상태인지 확인한다""" try: token, _ = session['github_token'] except KeyError: ...
xia2/xia2
tests/regression/test_vmxi_thaumatin.py
Python
bsd-3-clause
808
0
from __future__ import annotations import procrunner import pytest import xia2.Test.regression @pytest.mark.parametrize("pipeline", ["dials", "3dii
"]) def test_xia2(pipelin
e, regression_test, dials_data, tmpdir, ccp4): master_h5 = dials_data("vmxi_thaumatin") / "image_15799_master.h5:1:20" command_line = [ "xia2", f"pipeline={pipeline}", "nproc=1", "trust_beam_centre=True", "read_all_image_headers=False", "space_group=P41212", ...
commonsense/conceptdb
conceptdb/test/test_sentence.py
Python
gpl-2.0
1,640
0.010976
from conceptdb.metadata import Dataset import conceptdb from conceptdb.assertion import Sentence conceptdb.connect_to_mongodb('test') def test_sentence(): dataset = Dataset.create(language='en', name='/data/test') #create test sentence with dataset sentence1 = Sentence.make('/data/test', "This is a ...
ntence.") #check it was saved to the database assert sentence1.id is not None #make sure its attributes are readable sentence1.text sentence1.words sentence1.dataset sentence1.derived_assertions sentence1.confidence #make the same sentence, this time using dataset object instead o...
assert sentence2.id is not None #check that sentence1 and sentence2 have the same ID assert (sentence1.id == sentence2.id) #check that its attributes are readable sentence2.text sentence2.words sentence2.dataset sentence2.derived_assertions sentence2.confidence #make a diffe...
domin1101/malmo-challenge
ai_challenge/pig_chase/environment.py
Python
mit
11,366
0.001672
# Copyright (c) 2017 Microsoft Corporation. # # 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 use, copy, modify, merge, publis...
'<MsPerTick>50</MsPerTick>', self._mission_xml) super(PigChaseEnvironment, self)._
_init__(self._mission_xml, actions, remotes, role, exp_name, True) self._internal_symbolic_builder = PigChaseSymbolicStateBuilder() self._user_defined_builder = state_builder self._randomize_positions = randomize_positions self._agent_t...
internship2016/sovolo
app/user/migrations/0010_auto_20160816_0939.py
Python
mit
1,662
0.000728
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-16 00:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0009_auto_20160816_0720'), ] operations = [ migrations.AlterField( ...
, ('Ishikawa', '石川県'), ('Kagoshima', '鹿児島県'), ('Ooita', '大分県'), ('Shiga', '滋賀県'), ('Toyama', '富山県'), ('Saga', '佐賀県'), ('Kouchi', '高知県'), ('Gunnma', '群馬県'), ('Osaka', '大阪府'), ('Fukuoka', '福岡県'), ('Tochigi', '栃木県'), ('Fukui', '福井県'), ('Wakayama', '和歌山県'),
('Shizuoka', '静岡県'), ('Okayama', '岡山県'), ('Yamanashi', '山梨県')], max_length=10), ), ]
tlevis/Pepino
user-interface/python-scripts/port-test.py
Python
mit
682
0.019062
import os import sys import time import pygame import socket import fcntl import struct import serial import RPi.GPIO as GPIO time_stamp_prev=0 def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP) loop_forever = True prev_input = 1 wh
ile True: input = GPIO.input(22) print input #if ( prev_input and (not input)): # print "Pressed\n" # loop_forever = False #prev_input = input time.sleep(0.05) #displaytext(get_ip_address('eth0'),40,3,(0,0,0),False) #pygame.d...
if __name__ == '__main__': main()
odoo-arg/odoo_l10n_ar
l10n_ar_account_check_sale/wizard/__init__.py
Python
agpl-3.0
964
0
# -*- coding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the L...
GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################
######## import wizard_sell_check # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Pierre-Sassoulas/django-survey
example_project/example_project/urls.py
Python
agpl-3.0
1,020
0.00098
"""example_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/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') ...
.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: url(r'^blog/', include('blog.urls')) """ fro
m django.conf.urls import include try: from django.conf.urls import url except ImportError: # Django 4.0 replaced url by something else # See https://stackoverflow.com/a/70319607/2519059 from django.urls import re_path as url from django.contrib import admin urlpatterns = [url(r"^admin/", admin.site.u...
pgarridounican/ns-3.20-NC
src/network-coding/bindings/callbacks_list.py
Python
gpl-2.0
2,905
0.005852
callback_classes = [ ['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::Packet>', 'unsigned char', 'unsigned int', 'ns3::Ipv4Address', 'ns3::Ipv4Address', 'unsigned char', 'unsigned char', 'bool', 'ns3::...
, 'ns3::empty', 'ns3::empty', 'ns3::empt
y', 'ns3::empty'], ['void', 'unsigned char*', 'long', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'std::string', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ]
citrix-openstack-build/swift
test/unit/common/middleware/test_list_endpoints.py
Python
apache-2.0
8,008
0
# Copyright (c) 2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
_endpoints) self.assertEquals(resp.sta
tus_int, 200) self.assertEquals(resp.status, '200 OK') self.assertEquals(resp.body, 'FakeApp') # test custom path with trailing slash custom_path_le = list_endpoints.filter_factory({ 'swift_dir': self.testdir, 'list_endpoints_path': '/some/another/path/' ...
nicanorgarcia/kaldi-ivectors-for-python
kaldi_ivector.py
Python
apache-2.0
4,538
0.015866
import os from kaldi_io import kaldi_io import numpy as np def gen_feats_file(data_feats,ids,feat_filename): """ This function goes through the contents of a Kaldi script file (.scp) and selects the lines that match each element in ids and then stores this subset in feat_filename. This could be used to...
by taking the mean of all the
i-vectors with keys that match certain pattern (e. g., the id of a speaker). Each pattern in ids is searched for. If there are no matches for a pattern, a null (zeros) i-vector is used as replacement. Inputs: ivectors: numpy array with the extracted i-vectors keys: numpy array with the ...
brianrodri/oppia
core/controllers/recent_commits_test.py
Python
apache-2.0
6,058
0
# coding: utf-8 # # Copyright 2018 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
, 'public', True) commit_i
.exploration_id = exp_id commit_i.update_timestamps() commit_i.put() response_dict = self.get_json( feconf.RECENT_COMMITS_DATA_URL, params={'query_type': 'all_non_private_commits'}) self.assertEqual( len(response_dict['results']), feconf.COMMI...
pierrelb/RMG-Py
rmgpy/reduction/rates.py
Python
mit
6,711
0.006705
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2010 Prof. William H. Green ([email protected]) and the # RMG Team ([email protected]) # # Permission is hereby granted, free of c...
####################### import numpy as np from rmgpy.scoop_framework.util import logger as logging CLOSE_TO_ZERO = 1E-20 def computeReactionRate(rxn, forward, T, P, coreSpeciesConcentrations): """ Computes reaction rate r as follows: r = k * Product(Ci^nuij, for all j) with: k = rate coeffic...
. """ speciesList = rxn.reactants if forward == 'reactants' else rxn.products totconc = 1.0 for spc in speciesList: ci = coreSpeciesConcentrations[spc.label] if abs(ci) < CLOSE_TO_ZERO: return 0. nui = rxn.getStoichiometricCoefficient(spc, forward) conc = ci...
tenko/gltools
gltools/@docs/conf.py
Python
gpl-2.0
267
0.007491
source_suffix = '.rst' master_doc = 'index' project = 'gltools' copyright = '2012
, Runar Tenfjord' extensions = ['sphinx.ext.autodoc'] autodoc_docstring_signature = True autodoc_member_order
= 'groupwise' html_style = 'default.css' htmlhelp_basename = 'gltoolsdoc'
Morgan-Stanley/treadmill
lib/python/treadmill/tests/appcfg/configure_test.py
Python
apache-2.0
7,613
0
"""Unit test for treadmill.appcfg.configure. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import shutil import sys import tempfile import unittest import mock import treadmill from treadmill.appcfg...
treadmill.fs.write_safe.assert_called_with( os.path.join(app_dir, 'data', 'app.json'), mock.ANY,
mode='w', permission=0o644 ) shutil.copyfile.assert_called_with( '/some/event', os.path.join(app_dir, 'data', 'manifest.yml') ) treadmill.trace.post.assert_called_with( mock.ANY, events.ConfiguredTraceEvent( i...
avsaj/rtpmidi
rtpmidi/engines/midi/recovery_journal_chapters.py
Python
gpl-3.0
27,204
0.008969
#utils from struct import pack from struct import unpack def timestamp_compare(x, y): if x[1]>y[1]: return 1 elif x[1]==y[1]: return 0 else: # x[1]<y[1] return -1 def reverse_timestamp(x, y): return y[1]-x[1] class Note(object): def note_on(self, note_num, velocity, recom...
r_s = first >> 7 note_num = first&127 marker_y = second >> 7 velocity = second&127 return (marker_s, note_num, marker_y, velocity) def note_off(self, notes, low, high): """OFFBITS of 1 octet, each OFFBITS code NoteOff informations for 8 consecutive MIDI note...
#trick to encode in a simple way for i in range(len(notes)): notes[i] += 1 #getting number of offbits nb_offbits = high - low + 1 pack_algo = '!' #determine render form for i in range(nb_offbits): pack_algo += 'B' #writting offbit...
jiadaizhao/LeetCode
0301-0400/0327-Count of Range Sum/0327-Count of Range Sum.py
Python
mit
1,404
0.003561
class Solution: def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: presum = [0] * (1 + len(nums)) for i in range(len(nums)): presum[i + 1] = presum[i] + nums[i] temp = [0] * (1 + len(nums)) def mergeSort(start, end): count = 0 ...
count += mergeSort(start, mid) count += mergeSort(mid + 1, end) i, j = start, mid + 1 p, q = mid + 1, mid + 1
k = start while i <= mid: while p <= end and presum[p] - presum[i] < lower: p += 1 while q <= end and presum[q] - presum[i] <= upper: q += 1 count += q - p ...
Azure/azure-sdk-for-python
sdk/purview/azure-purview-administration/azure/purview/administration/_version.py
Python
mit
347
0
# 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. # -------------------------------------------------------------------------- V
ERSION = "1.0.0b2"
suutari/shoop
shuup/importer/__init__.py
Python
agpl-3.0
304
0
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is license
d under the AGPLv3 license found in the # LICENSE fi
le in the root directory of this source tree. default_app_config = __name__ + ".apps.AppConfig"
paulopinda/eventex
eventex/core/migrations/0002_auto_20160124_2350.py
Python
gpl-2.0
1,299
0.000771
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-24 23:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
ield(verbose_name='slug'), ), migrations.AlterFiel
d( model_name='speaker', name='website', field=models.URLField(blank=True, verbose_name='website'), ), ]
lamby/buildinfo.debian.net
bidb/packages/migrations/0002_drop-orphaned-binary-instances.py
Python
agpl-3.0
424
0.004717
# -*- coding: utf-8 -*- from __futur
e__ import unicode_literals from django.db import migrations def forward(apps, schema_editor): Binary = apps.get_model('packages', 'Binary') Binary.objects.filter(generated_binaries__isnull=True).delete() class Migration(migrations.Migration): dependencies = [ ('packages', '0001_initial'), ]...
migrations.RunPython(forward), ]
wolfiex/RopaJL
treecluster/ncdata.py
Python
mit
1,008
0.021825
''' conda create -n py2711xr python=2.7 conda config --add channels conda-forge source activate py2711xr conda install xarray dask netCDF4 bottleneck conda update --all ''' import netCDF4,re from netCDF4 import Dataset def get(filename): nc = Dataset(filename,'r') print nc.date, '\n', nc.description,'\n' ...
tes = nc.groups[group].variables['Rate'][:] rates_columns = nc.groups[group].variable
s['Rate'].head.split(',') nc.close() di= dict([[specs_columns[i],i] for i in xrange(len(specs_columns))]) print 'returning' return {'spec':specs,'rate':rates, 'sc':specs_columns,'rc':rates_columns, 'dict': di }
aschmied/keyzer
ui/assetmanager.py
Python
bsd-2-clause
1,180
0.000847
# Copyright (c) 2015, Anthony Schmieder # Use of this source code is governed by the 2-clause BSD license that # can be found in the LICENSE.txt file. """Loads and manages art assets""" import pyglet import os _ASSET_PATHS = ["res"] _ASSET_FILE_NAMES = [ "black_key_down.png", "black_key_u
p.png", "white_key_down.png", "white_key_up.png", "staff_line.png", ] class Assets(object): _loadedAssets = None @staticmethod def loadAssets(): Assets._loadedAssets = dict() Assets._updateResourcePath() for f in _ASSET_FILE_NAMES: Assets.loadAsset(f) ...
me): Assets._loadedAssets[filename] = pyglet.resource.image(filename) @staticmethod def _updateResourcePath(): for p in _ASSET_PATHS: pyglet.resource.path.append(os.path.join(os.getcwd(), p)) pyglet.resource.reindex() @staticmethod def get(filename): if Asse...
jkyeung/XlsxWriter
xlsxwriter/test/comparison/test_chart_bar10.py
Python
bsd-2-clause
1,580
0.000633
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, [email protected] # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """...
chart = workbook.add_chart({'type': 'bar', 'subtype': 'percent_stacked'}) chart.axis_ids = [40274560, 40295040] data = [ [1, 2, 3, 4, 5],
[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({'values': '=Sheet1!$A$1:$A$5'}) chart.add_series({'values': '=Sheet1!$B$1:$B$5'}) ...
pulsar-chem/Pulsar-Core
scripts/data/format_CIAAW.py
Python
bsd-3-clause
2,449
0.0147
#!/usr/bin/env python3 import sys import re import mpmath as mp mp.dps=250 mp.mp.dps = 250 if len(sys.argv) != 2: print("Usage: format_CIAAW.py ciaawfile") quit(1) path = sys.argv[1] atomre = re.compile(r'^(\d+) +(\w\w*) +(\w+) +\[?(\d+)\]?\*? +(.*) *$') isore = re.compile(r'^(\d+)\*? +(\[?\d.*.*\]?) *$'...
isore.match(line)
matommass = atommassline.match(line) if matomre: curatom = "{:<5} {:<5}".format(matomre.group(1), matomre.group(2)) print("{} {:<6} {:<25}".format(curatom, matomre.group(4), NumberStr(matomre.group(5)))) elif misore: print("{} {:<6} {:<25}".format(curatom, misore.group(1),...
stefanklug/mapnik
scons/scons-local-2.3.6/SCons/Options/PackageOption.py
Python
lgpl-2.1
1,995
0.001504
# # Copyright (c) 2001 - 2015 The SCons Foundation # # 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 use, copy, modify, merge...
new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False def PackageOption(*args, **kw): global warned if not warned: msg = "The PackageOptio...
ned = True return SCons.Variables.PackageVariable(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
diablo-rewriter/diablo
obfuscation/diversity_engine/iterative_diablo/function_classification_evaluation.py
Python
gpl-2.0
5,609
0.029952
#!/usr/bin/python # This research is supported by the European Union Seventh Framework Programme (FP7/2007-2013), project ASPIRE (Advanced Software Protection: Integration, Research, and Exploitation), under grant agreement no. 609734; on-line at https://aspire-fp7.eu/. */ # The development of portions of the code co...
) for c in clusters: n_c = float(len(clusters[c])) p += purity_of_cluster(clusters[c], ref_map) * n_c / n retur
n p def entropy_of_cluster(cluster, ref_map): classes = classes_for_cluster(cluster, ref_map) e = float(0) n_c = len(cluster) for c in classes: c_count = float(0) for i in cluster: if i in ref_map and ref_map[i] == c: # TODO: not in ref_map? c_count+=1 #e += c_count / c_ e = e...
public0821/libpcapy
libpcapy/tcpdump.py
Python
apache-2.0
1,512
0.009259
from libpcapy import pcap import signal import argparse import sys import threading counter = 0 def handler
(signum, frame): print('Signal handler called with signal ', signum, counter) sys.exit(0) def callback(pkthdr, data, user_data): global counter counter += 1 print('%d.%d(%d/%d) '%(pkthdr.ts.tv_sec, pkthdr.ts.tv_usec, pkthdr.caplen, pkthdr.len), data) signal.signal(signal.SIGINT, handler) def tcpd...
i', metavar='interface', dest='interface', required=True, type=str, help="Specifies the interface listen on") args = parser.parse_args() try: index = int(args.interface) except ValueError: device = args.interface else: dev_names = [] alldevs = pcap.pcap_findalldev...
Wuguanping/Server_Manage_Plugin
Zenoss_Plugin/ZenPacks/community/HuaweiServer/modeler/plugins/community/snmp/HMMPowerSupplyMap.py
Python
apache-2.0
4,621
0.000216
''' HMMPowerSupplyMap ''' from Products.DataCollector.plugins.CollectorPlugin import ( SnmpPlugin, GetTableMap, GetMap ) from DeviceDefine import HMMSTATUS, HMMPRESENCE, HMMPOWERMODE, HMMLOCATION class HMMPowerSupplyMap(SnmpPlugin): ''' HMMPowerSupplyMap ''' relname = 'hmmpowerSup...
'.4': 'powerRatingPower', '.5': 'powerMode', '.8': 'powerRuntimePower', }
), GetTableMap( 'hmmPSUTable', '1.3.6.1.4.1.2011.2.82.1.82.100.4.2001.1', { '.1': 'psuIndex', '.2': 'psuLocation', '.3': 'psuHealth', } ), ) snmpGetMap = GetMap({ '.1.3.6.1.4.1.2011.2.82.1.8...
Aghosh993/QuadcopterCodebase
targets/f3discovery/calibration/imucal.py
Python
gpl-3.0
6,676
0.033853
#!/usr/bin/python3 from sympy import * from sympy.utilities.codegen import codegen import argparse import numpy as np import matplotlib as mp import matplotlib.pyplot as plt from matplotlib import cm, colors from mpl_toolkits.mplot3d import Axes3D # A simple script that invokes Sympy to implement a Newton-Gauss least-...
ED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEM
PLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY ...
ingenioustechie/zamboni
mkt/feed/models.py
Python
bsd-3-clause
17,621
0.000057
""" The feed is an assembly of items of different content types. For ease of querying, each different content type is housed in the FeedItem model, which also houses metadata indicating the conditions under which it should be included. So a feed is actually just a listing of FeedItem instances that match the user's reg...
egate = qs.aggregate(models.Max('order')
)['order__max'] order = aggregate + 1 if aggregate is not None else 0 rval = self.membership_class.objects.create(obj_id=self.id, app_id=app, group=group, order=order) index_webapps.delay([app]) return rval def set_apps_groupe...
emanuelschuetze/OpenSlides
tests/integration/agenda/test_models.py
Python
mit
473
0
from openslides.ag
enda.models import Item from openslides.topics.models import Topic from openslides.utils.test import TestCase class TestItemManager(TestCase): def test_get_root_and_children_db_queries(self): """ Test that get_root_and_children needs only one db query. """ for i in range(10): ...
tNumQueries(1): Item.objects.get_root_and_children()
lauhuiyik/same-page
src/handlers/front.py
Python
mit
1,011
0.011869
########## import web import hmac from time import strftime from datetime import datetime from hashlib import sha256 from lib.utils import db from lib.utils import render from lib.utils import etherpad from lib.validate import valid_user, valid_pw, make_salt ########## class FrontPage: def GET(self): r...
w if valid_user(uid) and valid_pw(pw): # Makes random 16-character alphabet # Stored in the db salt = make_salt() # Specifies that hmac uses sha256 instead of md5 # hmac complicates the hash hashed_pw = hmac.new(salt, pw, sha256)...
raise web.seeother('/home') else: raise web.seeother('/')
marcobra/opencatamap
cgi-bin/genera_html_su_urbano.py
Python
gpl-3.0
3,614
0.015495
#!/usr/bin/python # -*- coding: utf-8 -*- import cgi import sqlite3, re, string, codecs, os def cercaurbano(cNominativo): c = sqlite3.connect('./data/catasto.db') cur = c.cursor() cSele = "select distinct (id_i.foglio || '-' || id_i.numero ||'-'|| id_i.subalterno), \ '<a href=\"http://nominatim.openstreetmap.o...
nt-size: 14px;color: #000000;}'
print 'table {border-collapse: collapse;}' print 'table, th, td { border: 1px solid gray; }' print '</style>' print '</head>' print '<body>' glofile='./data/catasto.db' mess='' if not os.path.exists(glofile): mess+="Manca il file -- " + glofile + '<br>' glofile='./data/cat...
standage/AEGeAn
data/scripts/version.py
Python
isc
1,633
0.002449
#!/usr/bin/env python # Copyright (c) 2010-2016, Daniel S. Standage and CONTRIBUTORS # # The AEGeAn Toolkit
is distributed under the ISC License. See # the 'LICENSE' file in the AEGeAn source code distribution or # online at https://github.com/standage/AEGeAn/blob/master/LICENSE. from __future__ import print_function import re import subprocess import sys with open('VERSION', 'r') as vfile:
semverstr = vfile.read().replace('\n', '') semver, stability = semverstr.split(' ') try: logproc = subprocess.Popen(['git', 'log'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) logout, logerr = logproc.communicate() except: logerr = True if ...
Jorge-Rodriguez/ansible
lib/ansible/modules/network/panos/panos_security_rule.py
Python
gpl-3.0
19,861
0.001762
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, techbizdev <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version':...
cription: - Whether to log at session start. type: bool log_end: description: - Wh
ether to log at session end. default: true type: bool action: description: - Action to apply once rules maches. default: "allow" group_profile: description: > - Security profile group that is already defined in the system. This property supersedes ...
Shrews/PyGerrit
webapp/django/contrib/admin/options.py
Python
apache-2.0
34,944
0.005094
from django import forms, template from django.forms.formsets import all_valid from django.forms.models import modelform_factory, inlineformset_factory from django.forms.models import BaseInlineFormSet from django.contrib.contenttypes.models import ContentType from django.contrib.admin import widgets from django.contri...
t'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = db_field.blank and _('None') or None else: if isinstance(db_field, models
.ManyToManyField): # If it uses an intermediary model, don't show field in admin. if db_field.rel.through is not None: return None elif db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRa...