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
bikeNomad/mbed
workspace_tools/synch.py
Python
apache-2.0
11,453
0.005413
""" mbed SDK Copyright (c) 2011-2013 ARM Limited 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...
Interface", # RTOS Examples "rtos_basic", "rtos_isr", "rtos_mail", "rtos_mutex", "rtos_queue", "rtos_semaphore", "rtos_signals", "rtos_timer",
# Net Examples "TCPEchoClient", "TCPEchoServer", "TCPSocket_HelloWorld", "UDPSocket_HelloWorld", "UDPEchoClient", "UDPEchoServer", "BroadcastReceive", "BroadcastSend", # mbed sources "mbed-src-program", ) # A list of regular expressions that will be checked against each dire...
gary-dalton/Twenty47
twenty47/logging.py
Python
mit
3,990
0.003509
#!/usr/bin/env python # # """Test harness for the logging module. Tests BufferingSMTPHandler, an alternative implementation of SMTPHandler. Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved. Modified to handle SMTP_SSL connections """ import string, logging, logging.handlers from logging import Formatter cl...
y granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name o
f Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL #...
cfpb/porchlight
porchlightapi/tests.py
Python
cc0-1.0
12,039
0.004902
# -*- coding: utf-8 -*- from django.test import TestCase import mock import datetime from dateutil import tz ## Repository Test from porchlightapi.models import Repository # Constant values used for testing UNDEPLOYED_VALUE_TUPLE = ('c9d2d5b79edd7d4acaf7172a98203bf3aee2586a', datetime.dat...
.assertEqual(undeployed_value_tuple[2], UNDEPLOYED_VALUE_TUPLE[2]) @mock.patch("porchlightapi.sources.random_source") def test_deployed_value_source(self, ran
dom_source): """ Test that the model's undeployed_value() function correctly uses the lookup function to get and run the mock data source function. """ random_source.return_value = DEPLOYED_VALUE_TUPLE test_repo = Repository.objects.get(url='https://github.com/cf...
AnythingTechPro/curionet
curionet/io.py
Python
apache-2.0
3,368
0.001485
""" * Copyright (C) Caleb Marshall and others... - All Rights Reserved * Written by Caleb Marshall <anythingtechpro@gmail.com>, May 27th, 2017 * Licensing information can foun
d in 'LICENSE', which is part of this source code package. """ import struct class Endianness(object): """ A enum that stores network endianess formats """ NATIVE = '=' LITTLE_ENDIAN = '<' BIG_ENDIAN = '>' NETWORK = '!' class DataBufferError(IOError): """ A data buffer specific i...
""" BYTE_ORDER = Endianness.NETWORK def __init__(self, data=bytes(), offset=0): self.data = data self.offset = offset @property def byte_order(self): return self.BYTE_ORDER @property def remaining(self): return self.data[self.offset:] def read(self, l...
GoogleCloudPlatform/datacatalog-connectors-bi
google-datacatalog-sisense-connector/tests/google/datacatalog_connectors/sisense/prepare/assembled_entry_factory_test.py
Python
apache-2.0
13,804
0
#!/usr/bin/python # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
fake_tag.template = 'tagTemplates/sisense_folder_metadata' tag_factory = self.__mock_tag_factory tag_factory.make_tag_for_folder.return_value = fake_tag assembled_entry = self.__factory\ ._AssembledEntryFactory__make_assembled_entry_for_folder( folder, tag_templ...
ssert_called_once_with(folder) tags = assembled_entry.tags self.assertEqual(1, len(tags)) self.assertEqual('tagTemplates/sisense_folder_metadata', tags[0].template) tag_factory.make_tag_for_folder.assert_called_once_with( tag_template, folder) @...
Titulacion-Sistemas/PracticasDjango
usuarios_logueados/usuarios/models.py
Python
gpl-2.0
791
0.011378
from django import forms from django.contrib.auth.models import User from django.forms import ModelForm from django.db import models # Create your models here. #EDICION DE MODELO USER User.add_to_class('usuario_sico', models.CharField(max_length=10, null=False, blank=False)) User.add_to_class('contrasenia_sico', mode...
nk=True)) #FORMULARIOS class SignUpForm(ModelForm): class Meta: model = User
fields = ['username', 'password', 'email', 'first_name', 'last_name', 'usuario_sico', 'contrasenia_sico'] widgets = { 'password': forms.PasswordInput(), 'contrasenia_sico': forms.PasswordInput(), }
jlane9/pytest-needle
pytest_needle/driver.py
Python
mit
13,087
0.00214
"""pytest_needle.driver .. codeauthor:: John Lane <jlane@fanthreesixty.com> """ import base64 from errno import EEXIST import math import os import re import sys import pytest from needle.cases import import_from_string from needle.engines.pil_engine import ImageDiff from PIL import Image, ImageDraw, ImageColor from...
return: """ return import_from_string(self.engine_class)() @property def engine_class(self): """Return image processing engine name :return: :rtype: str """ return self.ENGINES.get(self.options.get('needle_engine', 'pil').lower(), DEFAULT_ENGINE) ...
et image processing engine name :param str value: Image processing engine name (pil, imagemagick, perceptualdiff) :return: """ assert value.lower() in self.ENGINES self.options['needle_engine'] = value.lower() def get_screenshot(self, element=None): """Returns scre...
codevan/codevan
BitcoinPlay/multisig_address.py
Python
apache-2.0
911
0.004391
#!/usr/bin/env/ python ''' Title - Create multi-signature address ''' # Import bitcoin from bitcoin import * my_private_key1
= random_key() my_private_key2 = random_key() my_private_key3 = random_key() print("Private Key1: %s\n" % my_private_key1) print("Private Key2: %s\n" % my_private_key2) print("Private Key3: %s\n" % my_private_key3) print('\n'); # Generate Public Key: my_public_key1 = privtopub(my_privat
e_key1) my_public_key2 = privtopub(my_private_key2) my_public_key3 = privtopub(my_private_key3) print("Public Key1: %s\n" % my_public_key1) print("Public Key2: %s\n" % my_public_key2) print("Public Key3: %s\n" % my_public_key3) print('\n'); # Create Multi-Sig Address: my_multi_sig = mk_multisig_script(my_publ...
ThermoNuclearPanda/Project_Automail
Python Files/utilities.py
Python
mit
358
0.022346
""" @Author: Kiran Gurajala & Alex Lee @Project: P
roject Automail @Version: 1.0 """ # Required imports import struct # Utils def pack(fmt, *args): return struct.pa
ck('<' + fmt, *args) def unpack(fmt, *args): return struct.unpack('<' + fmt, *args) def multichr(values): return ''.join(map(chr, values)) def multiord(values): return map(ord, values)
whardier/jabberhooky
jabberhooky/__init__.py
Python
mit
263
0.003802
#!/usr/bin/env python # -*- coding: UTF-8 -*- """
JabberHooky""" __name__ = "j
abberhooky" __author__ = 'Shane R. Spencer' __email__ = "shane@bogomip.com" __license__ = 'MIT' __copyright__ = '2012 Shane R. Spencer' __version__ = '0.0.1' __status__ = "Prototype"
kxgames/vecrec
docs/conf.py
Python
mit
857
0.007001
import sys, os import vecrec ## General project = u'vecrec' copyright = u'2015, Kale Kundert' version = vecrec.__version__ release = vecrec.__version__ master_doc = 'index' source_suffix = '.rst' templates_path = ['templates'] exclude_patterns = ['build'] default_role = 'any' pygments_style = 'sphinx' ## Extensions...
odoc', 'sphinx.ext.au
tosummary', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx_rtd_theme', ] intersphinx_mapping = { # 'pyglet': ('http://pyglet.readthedocs.io/en/latest', None), 'pygame': ('https://www.pygame.org/docs', None), } autosummary_generate = True autodoc_default_options = { ...
punchagan/zulip
zerver/tests/test_signup.py
Python
apache-2.0
225,136
0.002394
import datetime import re import time import urllib from typing import Any, Dict, List, Optional, Sequence from unittest.mock import MagicMock, patch from urllib.parse import urlencode import orjson from django.conf import settings from django.contrib.auth.views import PasswordResetConfirmView from django.contrib.cont...
_bot, get_user, get_user_by_delivery_email, ) from zerver.views.auth import redirect_and_log_into_subdomain, start_two_factor_auth from zerver.views.development.registration import confirmation_key from zerver.views.invite import get_invitee_emails_set from zproje
ct.backends import ExternalAuthDataDict, ExternalAuthResult class RedirectAndLogIntoSubdomainTestCase(ZulipTestCase): def test_data(self) -> None: realm = get_realm("zulip") user_profile = self.example_user("hamlet") name = user_profile.full_name email = user_profile.delivery_email...
serefimov/billboards
billboards/billboards/wsgi.py
Python
mit
1,568
0.001276
""" WSGI config for billboards project. This module contains the
WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Dja
ngo WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from os.path impo...
ChantyTaguan/zds-site
zds/gallery/managers.py
Python
gpl-3.0
1,665
0.003003
from django.db import models from django.db.models import OuterRef, Subquery, Count from django.db.models.functions import Coalesce class GalleryManager(models.Manager): def annotated_gallery(self): """Annotate gallery with - ``linked_content``, which contains the pk of the associated content if ...
mport PublishableContent from zds.gallery.models import Image linked_content = PublishableContent.objects.filter(gallery__pk=OuterRef("pk")).values("pk") images = ( Image.objects.filter(gallery__pk=OuterRef("pk")) .values("gallery") .annotate(count=Count("pk...
mages), 0) ) def galleries_of_user(self, user): """Get galleries of user, and annotate with an extra field ``user_mode`` (which contains R or W) :param user: the user :type user: zds.member.models.User :rtype: QuerySet """ from zds.gallery.models import Us...
rduivenvoorde/QGIS
tests/src/python/test_qgsrulebasedrenderer.py
Python
gpl-2.0
23,130
0.002335
# -*- coding: utf-8 -*- """ *************************************************************************** test_qgsrulebasedrenderer.py --------------------- Date : September 2015 Copyright : (C) 2015 by Matthias Kuhn Email : matthias at opengis dot ch *******...
QgsProject, QgsRectangle, QgsMultiRenderChecker, QgsRuleBasedRenderer, QgsFillSymbol, QgsMarkerSymbol, QgsRendererCategory, QgsCategorizedSymbolRendere...
QgsRenderContext, QgsSymbolLayer, QgsSimpleMarkerSymbolLayer, QgsProperty, QgsFeature, QgsGeometry, QgsEmbeddedSymbolRenderer ) from qgis.testing imp...
klpdotorg/dubdubdub
apps/users/migrations/0020_auto_20140925_1129.py
Python
mit
905
0.00221
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0019_auto_20140909_1253'), ] operations = [ migrations.AlterModelOptions( name='donationitemcategory', ...
dels.CharField(default='red', max_length=64, choices=[(b'red', b'Red'), (b'green', b'Green'), (b'pur
ple', b'Purple')]), preserve_default=False, ), migrations.AlterField( model_name='donationitem', name='requirement', field=models.ForeignKey(related_name=b'items', to='users.DonationRequirement'), ), ]
huggingface/pytorch-transformers
utils/get_modified_files.py
Python
apache-2.0
1,484
0.003369
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0
(the "License"); # you may not use this file except in compliance with the License. # You m
ay obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License f...
JensTimmerman/radical.pilot
docs/architecture/api_draft/attributes.py
Python
mit
430
0.011628
# ------------------------------------------------------------------------------ # class Attributes (object) : # FIXME: add method sigs # ------------------------------------------------------
-------------------- # def __init__ (self, vals={}) : raise Exception ("%s is not implemented" % self.__class__
.__name__) # ------------------------------------------------------------------------------ #
hroumani/genericStorletStore
storletDeploy/sys_test_params.py
Python
apache-2.0
1,153
0
'''------------------------------------------------------------------------- Copyright IBM Corp. 2015, 2015 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/...
der the License. -------------------------------------------------------------------------''' ''' IMPORTANT: Make sure the variables AUTH_PI and KEYSTONE_IP point to the system you are testing!!! ''' '''------------------------------------------------------------------------''' # Establishing Swift connection, user ID,...
UTH_IP = DEV_AUTH_IP PROXY_PORT = '80' AUTH_PORT = '5000' ACCOUNT = 'service' USER_NAME = 'swift' PASSWORD = 'passw0rd'
morelab/labman_ud
labman_ud/labman_setup/migrations/0004_labmandeploygeneralsettings_background_color.py
Python
gpl-3.0
494
0
# -*- coding: utf-8 -*- from __
future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('labman_setup'
, '0003_googlesearchscript'), ] operations = [ migrations.AddField( model_name='labmandeploygeneralsettings', name='background_color', field=models.CharField(max_length=25, null=True, blank=True), preserve_default=True, ), ]
fogbow/fogbow-dashboard
horizon/templatetags/horizon.py
Python
apache-2.0
4,349
0.00046
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, 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 # # ...
ntext['request']} @register.filter def quota(val, units=None): if val == float("inf"): return _("No Limit") elif units is not None: return "%s %s %s" % (val, units, force_unicode(_("Available"))) else: return "%s %s" % (val, force_unicode(_("Available"))) class JSTemplate
Node(template.Node): """ Helper node for the ``jstemplate`` template tag. """ def __init__(self, nodelist): self.nodelist = nodelist def render(self, context, ): output = self.nodelist.render(context) output = output.replace('[[[', '{{{').replace(']]]', '}}}') output = outpu...
rmasters/inbox
inbox/transactions/actions.py
Python
agpl-3.0
3,454
0
"""Monitor the transaction log for changes that should be synced back to the account backend. TODO(emfree): * Track syncback failure/success state, and implement retries (syncback actions may be lost if the service restarts while actions are still pending). * Add better logging. """ import gevent from sqlalche...
CTION_FUNCTION_MAP = { 'archive': archive, 'unarchive': unarchive, 'mark_read': mark_read, 'mark_unread': mark_unread, 'star': star, 'unstar': unstar, 'mark_spam': mark_spam, 'unmark_spam': unmark_spam, 'mark_trash': mark_trash, 'unmark_trash': unmark_trash, 'send_draft': sen...
cutes syncback actions.""" def __init__(self, poll_interval=1, chunk_size=22, max_pool_size=22): self.log = get_logger() self.worker_pool = gevent.pool.Pool(max_pool_size) self.poll_interval = poll_interval self.chunk_size = chunk_size with session_scope() as db_session: ...
GoogleCloudPlatform/python-docs-samples
datastore/cloud-ndb/flask_app.py
Python
apache-2.0
1,175
0
# Copyright 2019 Google LLC 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 a
t # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governin...
iddleware(wsgi_app): def middleware(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware app = Flask(__name__) app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app) # Wrap the app in middleware. class Book(ndb.Model): title = ndb.St...
Sunhick/design-patterns
Behavioral/Command/Command.py
Python
gpl-3.0
230
0.008696
""" Command.py """ from abc import ABCMeta, abstractmeth
od class Command(object): __metaclass__ = ABCMeta @abstractmethod def
execute(self): pass @abstractmethod def unexecute(self): pass
kawamon/hue
desktop/core/ext-py/celery-4.2.1/t/unit/worker/test_heartbeat.py
Python
apache-2.0
1,829
0
from __future__ import absolute_import, unicode_literals from case import Mock from celery.worker.heartbeat import Heart class MockDispatcher(object): heart = None next_iter = 0 def __init__(self): self.sent = [] self.on_enabled = set() self.on_disabled = set()
self.enabled = True def send(self, msg, **_fields): self.sent.append(msg) if self.heart: if self.next_iter > 10: self.heart._shutdown.set() self.next_iter += 1 class MockTimer(object): def call_repeatedly(self, secs, fun, args=(), kwargs={}): ...
eled = True return entry((secs, fun, args, kwargs)) def cancel(self, entry): entry.cancel() class test_Heart: def test_start_stop(self): timer = MockTimer() eventer = MockDispatcher() h = Heart(timer, eventer, interval=1) h.start() assert h.tref ...
whyDK37/py_bootstrap
samples/commonlib/use_sax.py
Python
apache-2.0
739
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from xml.parsers.expat import ParserCreate class DefaultSaxHandler(object): def start_element(self, name, attrs): print('sax:start_element: %s, attrs: %s' % (name, str(attrs))) def end_element(self, name): print('sax:end_element: %s' %
name) def char_data(self, text): print('sax:cha
r_data: %s' % text) xml = r'''<?xml version="1.0"?> <ol> <li><a href="/python">Python</a></li> <li><a href="/ruby">Ruby</a></li> </ol> ''' handler = DefaultSaxHandler() parser = ParserCreate() parser.StartElementHandler = handler.start_element parser.EndElementHandler = handler.end_element parser.CharacterDa...
shakamunyi/docker-py
docker/unixconn/unixconn.py
Python
apache-2.0
3,189
0
# Copyright 2013 dotCloud 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 Lic
ense at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import si...
CitrineInformatics/pypif
pypif/obj/common/instrument.py
Python
apache-2.0
2,048
0.000977
from six import string_types from pypif.obj.common.pio import Pio class Instrument(Pio): """ Information about an instrument used to take a measurement. """ def __init__(self, name=None, model=None, producer=None, url=None, tags=None, **kwargs): """ Constructor. :param name: ...
roducer @producer.deleter def producer(self): self._producer = None @property def url(self): return self._url @url.setter
def url(self, url): self._validate_type('url', url, string_types) self._url = url @url.deleter def url(self): self._url = None
stvstnfrd/edx-platform
openedx/core/djangoapps/programs/migrations/0013_customprogramsconfig.py
Python
agpl-3.0
1,294
0.003864
# -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2019-12-13 07:44 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('programs', '0012_auto_20170419_0018'), ] operations = [ migrations.CreateModel( name='CustomProgramsConfig', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('change_date', model...
', models.BooleanField(default=False, verbose_name='Enabled')), ('arguments', models.TextField(blank=True, default='', help_text='Useful for manually running a Jenkins job. Specify like "--usernames A B --program-uuids X Y".')), ('changed_by', models.ForeignKey(editable=False, null=True,...
USGSDenverPychron/pychron
docs/user_guide/operation/scripts/examples/argus/measurement/jan_unknown_air_for_38Ar_600_180.py
Python
apache-2.0
2,496
0.014824
#!Measurement ''' baseline: after: true before: false counts: 180 detector: H1 mass: 34.2 settling_time: 20.0 default_fits: nominal equilibration: eqtime: 1.0 inlet: R inlet_delay: 3 outlet: O use_extraction_eqtime: true post_equilibration_delay: 5 multicollect: counts: 600 detector: H1 is...
let_delay) set_
time_zero() sniff(eqt) set_fits() set_baseline_fits() # delay to migitate 39Ar spike from inlet valve close sleep(mx.equilibration.post_equilibration_delay) #multicollect on active detectors multicollect(ncounts=mx.multicollect.counts, integration_time=1) if mx.baseline.a...
cosminbasca/rdftools
rdftools/tools/jvmrdftools/__init__.py
Python
apache-2.0
3,224
0.001861
# # author: Cosmin Basca # # Copyright 2010 University of Zurich # # 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 a...
xms, xmx, "--source", source, "--dataset_id", dataset_id, "--output_path", output_path) def run_rdf2rdf_converter(source, destination, xms=XMS, xmx=XMX): run_tool("com.rdftoo
ls.Rdf2RdfConverter", xms, xmx, source, destination)
RedMadRobot/rmr_django
rmr/middleware/json.py
Python
mit
1,109
0
import json from django import http from django.conf import settings from rmr.types import JsonDict class RequestDecoder: content_type = 'application/json' allowed_methods = { 'POST', 'PUT', 'PATCH', } def process_request(self, request): if request.method not in self.allowed_metho...
t.encoding or settings.DEFAULT_CHARSET try: body = request.body.decode(encoding=encoding) except UnicodeDecodeError: return http.HttpResponseBadRequest('bad unicode') try: request.POST = self.json_decode(body) except ValueError: return http...
data = json.loads(body) if not isinstance(data, dict): # all data of type other then dict will be returned as is return data return JsonDict(data)
synthomat/irc_topology_drawer
irc_topology_drawer.py
Python
apache-2.0
2,147
0.01211
#!/usr/bin/python """ Copyright 2012 Anton Zering <synth@lostprofile.de> 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 applicabl...
[] def on_welcome(self, connection, event): print "connected, fetching links" connection.links() def on_links(self, connection, event): print event.arguments() self.links.append(event.arguments()) def on_endoflinks(self, connection, event): print "rendering" ge...
nect() def on_disconnect(self, connection, event): sys.exit(0) def main(): c = IRCCat() try: print "connecting" c.connect(SERVER[0], SERVER[1], NICK) except irclib.ServerConnectionError, x: print x sys.exit(1) c.start() if __name__ == "__main__": main()
kbsymanz/gnuhealth_mmc
mmc.py
Python
mit
35,273
0.003714
# ------------------------------------------------------------------------------- # mmc.py # # Customization of GnuHealth for the needs of Mercy Maternity Clinic, Inc. # ------------------------------------------------------------------------------- from trytond.model import ModelView, ModelSingleton, ModelSQL, fields ...
('c', 'Concubinage'), ('w', 'Widowed'), ('d', 'Divorced'), ('x', 'Separated'), ], 'Marital Status', sort=False), 'get_patient_marital_status') rh = fields.Selection([ ('u', 'Unknown'), ('+', '+'), ('-', '-'), ], 'Rh') # -------...
jejimenez/django
tests/handlers/tests_custom_error_handlers.py
Python
bsd-3-clause
888
0
from django.conf.urls import url from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.test import SimpleTestCase, override_settings def template_response_error_handler(request, exception=None): return TemplateResponse(request, 'test_handler.html', s...
quest): raise PermissionDenied urlpatterns = [ url(r'^$', permission_denied_view), ] handler403 = template_response_error_handler @override_settings(ROOT_URLCONF='handlers.tests_custom_error_handlers') class CustomErrorHandlerTests(SimpleTestCase): def test_handler_renders_template_response(self): ...
response = self.client.get('/') self.assertContains(response, 'Error handler content', status_code=403)
andrebellafronte/stoq
stoqlib/gui/base/slaves.py
Python
gpl-2.0
1,749
0.007433
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2005, 2006 Async Open Source ## ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public License ## as published by the Free Software Foundation; either version 2 ## of the Licen...
BaseEditorSlave): """ Slave store general notes. The model must have an attribute 'notes' to work. """ gladefile = 'NoteSlave' proxy_widgets = ('notes', ) def __
init__(self, store, model, visual_mode=False): self.model = model self.model_type = self.model_type or type(model) BaseEditorSlave.__init__(self, store, self.model, visual_mode=visual_mode) self.notes.set_accepts_tab(False) def setup_proxies(self): ...
emesene/papyon
papyon/service/description/OIM/Store2.py
Python
gpl-2.0
3,213
0.009648
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) an...
s the SOAP
xml header""" # FIXME : escape the parameters return """<From memberName="%(from_member_name)s" friendlyName="%(friendly_name)s" xml:lang="en-US" proxy="%(proxy)s" xmlns="http://messenger.msn.com/ws/2004/09/oim/" msnpVer="%(msnp_ver)s" buildVer="%(build_ver)s"/> <To memberName="%(to_member_name)s...
jwinzer/OpenSlides
server/openslides/users/models.py
Python
mit
12,597
0.001111
import smtplib from decimal import Decimal from django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group as DjangoGroup, GroupManager as _GroupManager, Permission, PermissionsMixin, ) from...
ue=True, blank=True) auth_type = models.CharField(max_length=64, default="default") first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) gender =
models.CharField(max_length=255, blank=True) email = models.EmailField(blank=True) last_email_send = models.DateTimeField(blank=True, null=True) # TODO: Try to remove the default argument in the following fields. structure_level = models.CharField(max_length=255, blank=True, default="") title =...
jeremiah-c-leary/vhdl-style-guide
vsg/rules/signal/rule_008.py
Python
gpl-3.0
705
0.001418
from vsg.rules import token_prefix from vsg import token lTokens = [] lTokens.append(token.signal_declaration.identifier) class rule_008(token_prefix): ''' This rule checks for valid prefixes on signal identifiers. Default signal prefix is *s\_*. |configuring_prefix_and_suffix_rules_link| **V...
std_logic; **Fix** .. code-block:: vhdl signal s_wr_en : std_logic; signal s_rd_en : std_logic; ''' def __init__(self): token_prefix.__init__(self, 'signal', '
008', lTokens) self.prefixes = ['s_'] self.solution = 'Signal identifiers'
xorpaul/shinken
test/test_parse_perfdata.py
Python
agpl-3.0
4,222
0.002842
#!/usr/bin/env python # Copyright (C) 2009-2010: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # # This file is part of Shinken. # # Shinken 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 F...
f setUp(self): # self.setup_with_file('etc/nagios_parse_perfdata.cfg') def test_parsing_perfdata(self): s = 'ramused=1009MB;;;0;1982 swapused=540MB;;;0;3827 memused=1550MB;2973;3964;0;5810' s = 'ramused=1009MB;;;0;1982' m = Metric(s) self.assert_(m.name == 'ramused') ...
self.assert_(m.min == 0) self.assert_(m.max == 1982) s = 'ramused=90%;85;95;;' m = Metric(s) self.assert_(m.name == 'ramused') self.assert_(m.value == 90) self.assert_(m.uom == '%') self.assert_(m.warning == 85) self.assert_(m.critical == 95) s...
mraue/pyfact
pyfact/map.py
Python
bsd-3-clause
11,616
0.008351
#=========================================================================== # Copyright (c) 2011-2012, the PyFACT developers # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributio...
to camera center fit : bool, optional
Fit acceptance histogram (default=False). """ if not nbins : nbins = int(rmax / .1) # Create camera distance histogram n, bins = np.histogram(camdist, bins=nbins, range=[0., rmax]) nerr = np.sqrt(n) # Bin center array r = (bins[1:] + bins[:-1]) / 2. # Bin area (ring) array r_...
scampion/pimpy
pimpy/video/features/surf.py
Python
agpl-3.0
2,428
0.011532
""" pimpy.video.features.surf : enab
le to compute a video signature .. module:: surf :synopsis: Tools for video :platform: Unix, Mac, Windows .. moduleauthor:: Sebastien Campion <sebastien.campion@inria.fr> """ # pimpy # Copyright (C) 2010 Sebastien Campion <sebastien.campion@inria.fr> # #
pimpy 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. # # pimpy is distributed in the hope that it will be useful, # but WITHOUT ANY W...
wintermind/pypedal
PyPedal/examples/new_graphics3.py
Python
gpl-2.0
1,123
0.007124
#!/usr/bin/python ######################################################
######################### # NAME: new_graphics3.py # VERSION: 2.0.0b15 (18SEPTEMBER2006) # AUTHOR: John B. Cole, PhD (jcole@aipl.arsusda.gov) # LICENSE: LGPL ##############
################################################################# from PyPedal import pyp_demog from PyPedal import pyp_graphics from PyPedal import pyp_jbc from PyPedal import pyp_newclasses from PyPedal import pyp_nrm from PyPedal import pyp_metrics from PyPedal.pyp_utils import pyp_nice_time if __name__ == '__main...
davrv93/creed-en-sus-profetas-backend
django_rv_apps/apps/believe_his_prophets_api/views/spirit_prophecy_chapter_language/filters.py
Python
apache-2.0
1,155
0.013853
import django_filters from django_filters import rest_framework as filters from django_rv_apps.apps.believe_his_prophets.models.spirit_prophecy_chapter import SpiritProphecyChapter, SpiritProphecyChapterLanguage from django_rv_apps.apps.believe_his_prophets.models.spirit_prophecy import SpiritProphecy from django_rv_...
MultipleChoiceFilter( queryset=Language.objects.all(), field_name='language__code_iso', to_field_name='code_iso' ) start_date = filters.CharFilter(method='filter_date') class Meta: model = SpiritProphecyChapterLanguage fields = ('id' ,'code_iso','start_date') ...
return queryset.filter( spirit_prophecy_chapter__start_date__year = t.year, spirit_prophecy_chapter__start_date__month = t.month, spirit_prophecy_chapter__start_date__day = t.day, )
icyflame/batman
pywikibot/userinterfaces/win32_unicode.py
Python
mit
12,438
0.001769
# -*- coding: utf-8 -*- """Stdout, stderr and argv support for unicode.""" ############################################## # Support for unicode in windows cmd.exe # Posted on Stack Overflow [1], available under CC-BY-SA 3.0 [2] # # Question: "Windows cmd encoding change causes Python crash" [3] by Alex [4], # Answered...
e: return True return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or GetConsoleMode(handle, byref(DWORD())) == 0) def old_fileno(std_name): """Return the fileno or None if that doesn't work.""" # some environments like IDL...
, 'std{0}'.format(std_name)) if hasattr(std, 'fileno'): try: return std.fileno() except UnsupportedOperation: pass old_stdin_fileno = old_fileno('in') old_stdout_fileno = old_fileno('out') old_stderr_fileno = ol...
hprid/creoleparser
creoleparser/test_cheat_sheet_plus.py
Python
mit
2,923
0.021895
"""The macros below aren't reliable (e.g., some fail if ``arg_string`` is `None`) or safe (``include`` doesn't guard against circular reference). For a more complete example, see `the code used in the sandbox <http://code.google.com/p/urlminer/source/browse/examples/wiki/macros.py>`_. """ import genshi.builder as...
def source(arg_string,body,isblock): return bldr.tag.pre(text2html.render(body)) def pre(arg_string,body,isblock): return bldr.tag.pre(body) ## End of macros macros = {'include':include, 'include-raw':include_raw, 'include-source':include_source, 'source':source, ...
'pre':pre } def macro_dispatcher(macro_name,arg_string,body,isblock,environ): if macro_name in macros: return macros[macro_name](arg_string,body,isblock) dialect = dialects.create_dialect(dialects.creole11_base, wiki_links_base_url='', wiki_links_space_char='', # use_...
Nic30/hwtLib
hwtLib/tests/synthesizer/astNodeIoReplacing_test.py
Python
mit
2,912
0.008242
import unittest from hwt.code import If, Switch from hwt.synthesizer.rtlLevel.netlist import RtlNetlist class AstNodeIoReplacingTC(unittest.TestCase): def sigs_by_n(self, n): nl = RtlNetlist() sigs = [nl.sig(chr(ord("a") + i)) for i in range(n)] for s in sigs: s.hidden = Fals...
n(3) stm = \ If(a, b(1) ).Else( b(0) ) stm._replace_input(a, c) stm_ref = If(c, b(1) ).Else( b(0) ) self.ass
ertTrue(stm.isSame(stm_ref), [stm, stm_ref]) self.assertEqual(a.endpoints, []) self.assertEqual(c.endpoints, [stm, stm_ref]) def test_If_elif_replace_input(self): _, (a, b, c, d) = self.sigs_by_n(4) stm = \ If(a, b(1) ).Elif(c & a, b(0) ...
severus21/LiPyc
src/Album.py
Python
apache-2.0
4,909
0.020371
from PIL import Image import os.path,os #import pickle #import sqlite3 import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Ver...
e(time.gmtime()) self.subalbums = set() self.thumbnail = None self.files = set() #order by id self.inner_keys = [] #use for inner albums def __deepcopy__(self, memo): new = Album(self.id, self.scheduler, self.name
, self.datetime) new.subalbums = deepcopy(self.subalbums) new.thumbnail = deepcopy(self.thumbnail) new.files = deepcopy(self.files) new.inner_keys = deepcopy(self.inner_keys) return new #for copy_to,add_to,move_to def clone(self, new_id): alb = s...
billzorn/fpunreal
titanfp/vec_sweep.py
Python
mit
11,896
0.00269
import math import random import operator import traceback from .titanic import ndarray from .fpbench import fpcparser from .arithmetic import mpmf, ieee754, posit, fixed, evalctx, analysis from .arithmetic.mpmf import Interpreter from .sweep import search from .sweep.utils import * dotprod_naive_template = '''(FPCo...
largest = largest_representable(ctx) largest_squared = largest.mul(largest, ctx=mul_ctx) smallest = smallest_representable(ctx) smallest_squared = smallest.mul(smallest, ctx=mul_ctx) # check assert largest_squared.inexact is False and smallest_squared.inexact is False left = largest_square...
1 + log_carries right = smallest_squared.e quire_type = fixed.fixed_ctx(right, left - right) # check assert not fixed.Fixed._round_to_context(largest_squared, ctx=quire_type).isinf assert not fixed.Fixed._round_to_context(smallest_squared, ctx=quire_type).is_zero() return quire_type def rou...
mdavid/cherokee-webserver-svnclone
admin/plugins/wildcard.py
Python
gpl-2.0
3,364
0.012485
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2009-2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free So...
# List else: table = CTK.Table() submit = CTK.Submitter(url_apply) submit += table self += CTK.Indenter(submit) table.set_header(1) table += [CTK.RawHTML(_('Domain pattern'))] for i in entries: e1 = CTK...
rm = None if len(entries) >= 2: rm = CTK.ImageStock('del') rm.bind('click', CTK.JS.Ajax (url_apply, data = {"%s!%s"%(key,i): ''}, complete = refreshable...
837468220/python-for-android
python3-alpha/python3-src/Lib/test/test_bufio.py
Python
apache-2.0
2,654
0.002638
import unittest from test import support import io # C implementation. import _pyio as pyio # Python implementation. # Simple test to ensure that optimizations in the IO library deliver the # expected results. For best testing, run this under a debug-build Python too # (to exercise asserts in the C code). lengths =...
to avoid simple re
lationships with # stdio buffer sizes. self.drive_one(b"1234567890\00\01\02\03\04\05\06") def test_nullpat(self): self.drive_one(bytes(1000)) class CBufferSizeTest(BufferSizeTest): open = io.open class PyBufferSizeTest(BufferSizeTest): open = staticmethod(pyio.open) def test_ma...
bram85/topydo
topydo/lib/Todo.py
Python
gpl-3.0
3,165
0
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topyd
o.org> # # This
program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITH...
gpanda/abrisk
fundlist.py
Python
gpl-2.0
8,887
0.000788
#!/usr/bin/env python # -*- coding: utf8 -*- from __future__ import print_function __author__ = 'gpanda' """References: [1] easy thread-safe queque, http://pymotw.com/2/Queue/ """ import argparse import collections import fileinput import os import pprint import re
import string import sys import threading import time import Queue from libs import driver from libs.common import LOG, is_sec_id, AbriskError config =
{} class Fund(object): """Fund data structure pbr = price / book value (nav), an important index to sort funds """ def __init__(self, secId, name=None, time=None, price=float(0), volume=float(0), nav=float(1)): """Initialize Fund object :param secId: security id ...
dreibh/planetlab-lxc-plcapi
PLC/NetworkTypes.py
Python
bsd-3-clause
1,417
0.008469
# # Functions for interacting with the network_types table in the database # # Mark Huang <mlhuang@cs.princeton.edu> # Copyright (C) 2006 The Trustees of Princeton University # from PLC.Faults import * from PLC.Parameter import Parameter from PLC.Table import Row, Table class NetworkType(Row): """ Representat...
'network_types' primary_key = 'type' join_tables = ['interfaces'] fields = { 'type': Parameter(str, "Network type", max = 20), } def validate_type(self, name): # Make sure name i
s not blank if not len(name): raise PLCInvalidArgument("Network type must be specified") # Make sure network type does not alredy exist conflicts = NetworkTypes(self.api, [name]) if conflicts: raise PLCInvalidArgument("Network type name already in use") ...
hipnusleo/laserjet
resource/pypi/cffi-1.9.1/demo/readdir_setup.py
Python
apache-2.0
260
0
from setuptools import setup setup( name="example", version="0.1", py_modules=["readdir"], setup_requires=["cffi>=1.0.dev0"],
cffi_modules=["readdir_build.py:ffi"], install_requires=["cffi>=1.0.dev0"],
zip_safe=False, )
jazzband/django-axes
tests/test_attempts.py
Python
mit
5,846
0
from unittest.mock import patch from django.http import HttpRequest from django.test import override_settings from django.utils.timezone import now from axes.attempts import get_cool_off_threshold from axes.models import AccessAttempt from axes.utils import reset, reset_request from tests.base import AxesTestCase c...
attempts.now", return_value=timestamp): attempt_time = timestamp threshold_now = get_cool_off_threshold(attempt_time) attempt_time = None threshold_none = get_cool_off_threshold(attempt_time) self.assertEqual(threshold_now, threshold_none) @override_setting...
self.assertRaises(TypeError): get_cool_off_threshold() class ResetTestCase(AxesTestCase): def test_reset(self): self.create_attempt() reset() self.assertFalse(AccessAttempt.objects.count()) def test_reset_ip(self): self.create_attempt(ip_address=self.ip_address) ...
rdevost/pymixup
common/settings.py
Python
mit
4,238
0
from os.path import expanduser ###################### # Common project files ###################### # These are files, packages, and folders that will be copied from the # development folder to the destination obfuscated project. ###################### # Python packages to obfusca
te. obfuscated_packages = [ 'controller', 'db', 'dbdata', 'logic', 'migrations', 'platform_api', 'tests', 'view' ] # Non-python folders and Python packages that are not obfuscated. # Note: Tests are a special case: both obfuscated and
unobfuscated versions # are desired. unobfuscated_folders = [ 'csvlite', 'fonts', 'help', 'images', 'initial_data', 'international', 'kivygraph', 'tests', ] # Required files or types in the project directory (that is, the base # directory in which all the common packages exist in) th...
CKboss/TheBauble
Tensorflow/CNN/ResNet/imgaug/augmenters.py
Python
gpl-3.0
129,266
0.003458
from __future__ import print_function, division, absolute_import from . import imgaug as ia from .parameters import StochasticParameter, Deterministic, Binomial, Choice, DiscreteUniform, Normal, Uniform from abc import ABCMeta, abstractmethod import random import numpy as np import copy as copy_module import re import ...
if ia.is_np_array(images): assert len(images.shape) == 4, "Expected 4d
array of form (N, height, width, channels), got shape %s." % (str(images.shape),) assert images.dtype == np.uint8, "Expected dtype uint8 (with value range 0 to 255), got dtype %s." % (str(images.dtype),) images_tf = images elif ia.is_iterable(images): if len(images) > 0: ...
alfanugraha/LUMENS-repo
processing/DockableMirrorMap/dockableMirrorMapPlugin.py
Python
gpl-2.0
8,306
0.032145
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : Dockable MirrorMap Description : Creates a dockable map canvas Date : February 1, 2011 copyright : (C) 2011 by Giuseppe Sucameli (Faunalia) email ...
kableMirrorMapPlugin: def __init__(self, iface): # Save a reference to the QGIS iface self.iface = iface def initGui(self): self.dockableMirrors = [] self.lastDockableMirror = 0 self.dockableAction = QAction(QIcon(":/plugins/DockableMirrorMap/icons/dockablemirrormap.png"), "Dockable MirrorMap", self.i
face.mainWindow()) QObject.connect(self.dockableAction, SIGNAL("triggered()"), self.runDockableMirror) self.aboutAction = QAction(QIcon(":/plugins/DockableMirrorMap/icons/about.png"), "About", self.iface.mainWindow()) QObject.connect(self.aboutAction, SIGNAL("triggered()"), self.about) # Add to the plugin me...
emergebtc/muddery
evennia/evennia/commands/default/muxcommand.py
Python
bsd-3-clause
8,473
0.002124
""" The command template for the default MUX-style command set. There is also an Player/OOC version that makes sure caller is a Player object. """ from evennia.utils import utils from evennia.commands.command import Command # limit symbol import for API __all__ = ("MuxCommand", "MuxPlayerCommand") class MuxCommand(C...
string += "space-separated arg list (self.arglist): {w%s{n\n" % self.ar
glist string += "lhs, left-hand side of '=' (self.lhs): {w%s{n\n" % self.lhs string += "lhs, comma separated (self.lhslist): {w%s{n\n" % self.lhslist string += "rhs, right-hand side of '=' (self.rhs): {w%s{n\n" % self.rhs string += "rhs, comma separated (self.rhslist): {w%s{n\n" % self.r...
tinloaf/home-assistant
homeassistant/helpers/entity_component.py
Python
apache-2.0
10,538
0
"""Helpers for components that manage entities.""" import asyncio from datetime import timedelta from itertools import chain import logging from homeassistant import config as conf_util from homeassistant.setup import async_prepare_setup_platform from homeassistant.const import ( ATTR_ENTITY_ID, CONF_SCAN_INTERVAL...
self.add_entities = self._platforms[domain].add_entities hass.data.setdefault(DATA_INSTANCES, {})[domain] = self @property def entities(self): """Return an iterable that returns all entities.""" return chain.from_iterable(platform.entities.values() for platform ...
n self._platforms.values()) def get_entity(self, entity_id): """Get an entity.""" for platform in self._platforms.values(): entity = platform.entities.get(entity_id) if entity is not None: return entity return None def setup(self, config): ...
tiagoprn/devops
shellscripts/kvm/restore_kvm_backup.py
Python
mit
3,178
0.002203
""" Given a KVM machine description file, parse its XML and change the contents of the nodes "name" and "disk/source.file". Usage: python restore_kvm_backup.py \ -x '/kvm/backups/centos7-06/kvm/backups/centos7-06/20180924.0850.23/config.xml' \ -b '/kvm/backups/centos7-06/kvm/backups/centos7-06/20180924.0850.23/centos...
child.attrib['file'] = IMAGE_FILE break tree.write(XML_RESTORATION_FILE) print('DONE. The new XML file you must use to restore your VM ' 'is at {}.'.format(XML_RESTORATION_FILE)) if __name__ == "__main__": print('Shutting down vm if it is active...') subprocess.run([...
'virsh', 'undefine', VM_NAME]) print('Removing disk for the existing vm...') if os.path.exists(IMAGE_FILE): os.unlink(IMAGE_FILE) print('Changing backup kvm config to restoration...') change_backup_xml_configuration_to_restore_vm() print('Copying the backup disk as the vm disk...') subp...
Jakeable/Ralybot
plugins/admin_channel.py
Python
gpl-3.0
5,871
0.002555
from ralybot import hook def mode_cmd(mode, text, text_inp, chan, conn, notice): """ generic mode setting function """ split = text_inp.split(" ") if split[0].startswith("#"): channel = split[0] target = split[1] notice("Attempting to {} {} in {}...".format(text, target, channel)) ...
message = " ".join(split) conn.send("TOPIC
{} :{}".format(chan, message)) @hook.command(permissions=["op_kick", "op"]) def kick(text, chan, conn, notice): """[channel] <user> - kicks <user> from [channel], or from the caller's channel if no channel is specified""" split = text.split(" ") if split[0].startswith("#"): channel = split[0] ...
benschulz/servo
tests/wpt/mozilla/tests/mozilla/resources/no_mime_type.py
Python
mpl-2.0
443
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the M
PL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. def main(request, response): headers = [] if 'Content-Type' in request.GET: headers += [('Content-Type', request.GET['Content-Type'])] with open('./resources/ahem/AHEM____.TTF') as f: r
eturn 200, headers, f.read()
onnovalkering/sparql-over-sms
sos-service/src/persistence/models/message.py
Python
mit
1,021
0.000979
from persistence.models import Agent, BaseModel from peewee import * class Message(BaseModel): """description of class""" correlationid = CharField() category = IntegerField() body = CharField(null=True) sender = ForeignKeyField(
Agent, related_name='send_messages') receiver = ForeignKeyField(Agent, related_name='received_messages') # flags complete = BooleanField(defaul
t=False) processed = BooleanField(default=False) # computed def get_body(self): if self.body is not None: return self.body if not self.complete: return None messageparts = sorted(self.parts, key=lambda x: x.position) body = ''.join([part.body for pa...
jolyonb/edx-platform
common/lib/xmodule/xmodule/lti_module.py
Python
agpl-3.0
37,872
0.002905
""" THIS MODULE IS DEPRECATED IN FAVOR OF https://github.com/edx/xblock-lti-consumer Learning Tools Interoperability (LTI) module. Resources --------- Theoretical background and detailed specifications of LTI can be found on: http://www.imsglobal.org/LTI/v1p1p1/ltiIMGv1p1p1.html This module is based on the ve...
s_wsdlBindv1p0.html A resource to test the LTI pr
otocol (PHP realization): http://www.imsglobal.org/developers/LTI/test/v1p1/lms.php We have also begun to add support for LTI 1.2/2.0. We will keep this docstring in synch with what support is available. The first LTI 2.0 feature to be supported is the REST API results service, see specification at http://www.i...
rolandkakonyi/poker-player-objc
player_service.py
Python
mit
1,447
0.002073
import time import cgi import json import os import BaseHTTPServer HOST_NAME = 'localhost' PORT_NUMBER = 9400 class PlayerService(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() ...
w.write(game_
state) w.close() response = r.read() self.wfile.write(response) if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class((HOST_NAME, PORT_NUMBER), PlayerService) print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER) try: ...
cbrafter/TRB18_GPSVA
codes/sumoAPI/HybridVAControl.py
Python
mit
15,253
0.005704
#!/usr/bin/env python """ @file HybridVAControl.py @author Craig Rafter @date 19/08/2016 class for fixed time signal control """ import signalControl, readJunctionData, traci from math import atan2, degrees, hypot import numpy as np from collections import defaultdict class HybridVAControl(signalControl.signa...
nInfo = self._getIncomingLaneInfo() self.stageTime = 0.0 self.minGreenTime = minGreenTime self.maxGreenTime = maxGreenTime self.secondsPerMeterTraffic = 0.45 self.nearVehicleCatchDistance = 25 self.extendTime = 1.0 # 5 m in 10 m/s (acceptable journey 1.3
33) self.laneInductors = self._getLaneInductors() self.TIME_MS = self.firstCalled self.TIME_SEC = 0.001 * self.TIME_MS '''def minmax(x, lower, upper): return min(max(x, lower), upper) ''' def process(self): self.TIME_MS = traci.simulation.getCurrentTime() s...
alfredoavanzosc/odoo-addons
partner_contact_birthdate_age/__openerp__.py
Python
agpl-3.0
640
0
# -*- coding: utf-8
-*- # (c) 2016 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Partner Contact Birthdate Age", 'version': '8.0.1.1.0', 'license': "AGPL-3", 'author': "AvanzOSC", 'website': "http://www.avanzosc.es", 'contributors': [ "Ana Juaris...
'partner_contact_birthdate', ], "data": [ 'views/res_partner_view.xml', ], "installable": True, }
jbenden/ansible
lib/ansible/modules/monitoring/sensu_client.py
Python
gpl-3.0
9,506
0.002525
#!/usr/bin/python # (c) 2017, Red Hat Inc. # 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': '1.0', 'status': ['preview'], 'supported_b...
uired=False), subscriptions=dict(type='list', required=False), safe_mode=dict(type='bool', required=False, default=False), redact=dict(type='list', required=False), socket=dict(type='dict', required=False), keepalives=dict(type='bool', required=False, default=...
='dict', required=False), registration=dict(type='dict', required=False), deregister=dict(type='bool', required=False), deregistration=dict(type='dict', required=False), ec2=dict(type='dict', required=False), chef=dict(type='dict', required=False), ...
carabri/carabri
test_script/open_gallery.py
Python
apache-2.0
123
0
import subprocess subprocess.call(""" adb -d shell am start -n co
m.android.gallery/com.android.ca
mera.GalleryPicker """)
kylef/lithium
lithium/wiki/migrations/0001_initial.py
Python
bsd-2-clause
7,245
0.008144
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Page' db.create_table('wiki_page', ( ('id', self.gf('django.db.models.fields.A...
arField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'wiki.page': { 'Meta': {'object_name'...
noironetworks/neutron
neutron/db/migration/alembic_migrations/versions/liberty/expand/45f955889773_quota_usage.py
Python
apache-2.0
1,496
0
# Copyright 2015 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
missions and limitations # under the License. # from alembic import op import sqlalchemy as sa from sqlalchemy import sql """quota_usage Revision ID: 45f955889773 Revises: 8675309a5c4f Create Date: 2015-04-17 08:09:37.611546 """ # revision identifiers, used by Alembic. revision = '45f955889773' down_revision = ...
'quotausages', sa.Column('tenant_id', sa.String(length=255), nullable=False, primary_key=True, index=True), sa.Column('resource', sa.String(length=255), nullable=False, primary_key=True, index=True), sa.Column('dirty', sa.Boolean(), nullable=False, ...
kickstandproject/ripcord
ripcord/db/sqlalchemy/migrate_repo/versions/006_add_quota_support.py
Python
apache-2.0
2,465
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2013 PolyBeacon, 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...
ard_limit', Integer), Column('project_id', String(length=255)), Column('resource', String(length=255), nullable=False), Column('updated_at', DateTime), UniqueConstraint( 'project_id', 'resource', name='uniq_quotas0project_id0resource'), mysql_engine='InnoD...
True, autoincrement=True), Column('class_name', String(length=255)), Column('created_at', DateTime), Column('hard_limit', Integer), Column('resource', String(length=255)), Column('updated_at', DateTime), mysql_engine='InnoDB', mysql_charset='utf8', ) tabl...
SitiBanc/1061_NCTU_IOMDS
1018/Course Material/1018_2.py
Python
apache-2.0
2,416
0.003714
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 18 20:53:35 2017 @author: sitibanc """ import numpy as np import random from sklearn import datasets from scipy import stats def kmeans(sample, K, max_iter): N = sample.shape[0] # N筆資料 D = sample.shape[1] # ...
d # Practice 3 : Iris Dataset Clustering Using K-Means data = datasets.load_iris() feature = data.data center, label, wicd = kmeans(feature, 3, 1000) # Calculate Error Rate error = 0 for i in range(len(label)): if i < 50: mode = stats.mode(label[:50]) if label[i] != mode[0][0]: error +=...
ode(label[50:100]) if label[i] != mode[0][0]: error += 1 else: mode = stats.mode(label[100:]) if label[i] != mode[0][0]: error += 1 print('Error rate :', error / len(label))
Intelworks/OpenTAXII
opentaxii/exceptions.py
Python
bsd-3-clause
157
0
from .taxii
.exceptions import UnauthorizedStatus class UnauthorizedException(UnauthorizedStatus): pass
class InvalidAuthHeader(Exception): pass
Ouranosinc/Magpie
magpie/api/__init__.py
Python
apache-2.0
329
0
from magpie.utils import get_logger LOGGER = get_logger(__name__) def includeme(config): LOGGER.info("Adding API routes...") # Add all the admin ui routes config.include("magp
ie.api.home") config.include("magpie.api.login") config.include("magpie.api.management") config.include("mag
pie.api.swagger")
syncloud/platform
src/syncloud_platform/rest/model/user.py
Python
gpl-3.0
67
0
class Use
r: def __init__(self, name): self.name = n
ame
dsm054/pandas
pandas/core/indexes/accessors.py
Python
bsd-3-clause
14,627
0.001641
""" datetimelike delegation """ from __future__ import annotations from typing import TYPE_CHECKING import warnings import numpy as np from pandas.core.dtypes.common import ( is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_integer_dtype, is_list_like, is_period_dtype, ...
>> s 0 2018-03-10 00:00:00.000000000 1 2018-03-10 00:00:00.000000001 dtype: datetime64[ns] >>> s.dt.to_pydatetime() array([datetime.datetime(2018, 3, 10, 0, 0), datetime.datetime(2018, 3, 10, 0, 0)], dtype=object) """ return self._get_values()....
et_values().inferred_freq def isocalendar(self): """ Returns a DataFrame with the year, week, and day calculated according to the ISO 8601 standard. .. versionadded:: 1.1.0 Returns ------- DataFrame with columns year, week and day See A...
PavlosMelissinos/enet-keras
src/models/enet_unpooling/encoder.py
Python
mit
4,098
0.00366
# coding=utf-8 from keras.layers.advanced_activations import PReLU from keras.layers.convolutional import Conv2D, ZeroPadding2D from keras.layers.core import SpatialDropout2D, Permute from keras.layers.merge import add, concatenate from keras.layers.normalization import BatchNormalization from ..layers.pooling import M...
eck 2.x and 3.x for _ in range(2): enet = bottleneck(enet, 128) # bottleneck 2.1 enet = bottleneck(enet, 128, dilated=2) # bottleneck 2.2 enet = bottleneck(enet, 128, asymmetric=5) # bottleneck 2.3 enet = bottleneck(enet, 128, dilated=4) # bottleneck 2.4 enet = bottleneck...
eneck(enet, 128, dilated=8) # bottleneck 2.6 enet = bottleneck(enet, 128, asymmetric=5) # bottleneck 2.7 enet = bottleneck(enet, 128, dilated=16) # bottleneck 2.8 return enet, pooling_indices
saeki-masaki/cinder
cinder/common/config.py
Python
apache-2.0
9,037
0
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright 2012 Red Hat, Inc. # Copyright 2013 NTT corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file exc...
ators to monkey patch'), cfg.IntOpt('service_down_time', default=60, help='Maximum time since last check-in for a service to be ' 'considered up'), cfg.StrOpt('volume_api_class', default='cinder.volume.api.API', help='The full class...
ume API class to use'), cfg.StrOpt('backup_api_class', default='cinder.backup.api.API', help='The full class name of the volume backup API class'), cfg.StrOpt('auth_strategy', default='keystone', choices=['noauth', 'keystone', 'deprecated'], ...
robertsj/poropy
pyqtgraph/dockarea/__main__.py
Python
mit
1,587
0.018904
import sys ## Make sure pyqtgraph is importable p = os.path.dirname(os.path.abspath(__file__)) p = os.path.join(p, '..', '..') sys.path.insert(0, p) from pyqtgraph.Qt import QtCore, QtGui from DockArea import * from Dock import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() area = DockArea() win.setCentra...
l.addWidget(btns[-1]) d.w = (w, l, btns) d.addWidget(w) import pyqtgraph as pg p = pg.PlotWidget() d6.addWidget(p) print "===widgets added===" #s = area.saveState() #print "\n\n-------restore----------\n\n" #area.restoreState(s) s = None def save(): global s s = area.saveState() def...
#win2.setCentralWidget(area2) #win2.resize(800,800) win.show() #win2.show()
7senses/shaka
shaka.py
Python
gpl-2.0
15,841
0.003283
import socket import json import sys, traceback import redis class http_parser: def __init__(self, sfhttp, is_client = True): self.__METHOD = 0 self.__RESP = 1 self.__HEADER = 2 self.__BODY = 3 self.__TRAILER = 4 self.__CHUNK_LEN = 5 self.__CHUNK_BOD...
tate = sel
f.__CHUNK_END return True else: return False def _parse_trailer(self): (result, line) = self._read_line() if result: if len(line) == 0: if self._is_client: self._state = self.__METHOD else: ...
valmynd/MediaFetcher
src/plugins/youtube_dl/youtube_dl/extractor/drbonanza.py
Python
gpl-3.0
1,678
0.026222
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( js_to_json, parse_duration, unescapeHTML, ) class DRBonanzaIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?dr\.dk/bonanza/[^/]+/\d+/[^/]+/(?P<id>\d+)/(?P<display_id>[^/?#&]+)' _TEST = { 'url': 'http...
, 'description': 'md5:77b4c1ac4d4c1b9d610ab4395212ff84', 'thumbnail': r're:^https?://.*\.(?:gif|jpg)$', 'duration': 4613, }, } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id, display_id = mobj.group('id', 'display_id') webpage = self._download_webpage(url, display_id) ...
media_entries( url, webpage, display_id, m3u8_id='hls', m3u8_entry_protocol='m3u8_native')[0] self._sort_formats(info['formats']) asset = self._parse_json( self._search_regex( r'(?s)currentAsset\s*=\s*({.+?})\s*</script', webpage, 'asset'), display_id, transform_source=js_to_json) title = unesca...
free-electrons/custom_tests_tool
tests/test_writers.py
Python
gpl-2.0
4,332
0.000462
from nose.tools import assert_equal, assert_raises import mock import xmlrpc from src.writers import FileWriter, LavaWriter from src.writers import UnavailableError class TestFileWriter(object): OUTPUT_DIR = 'foo' CONTENT = 'test' NAME = 'test-job-name' def test_fail_open(self): cfg = { ...
builtins.open', mo, create=True) as mocked: path = '%s/%s.yaml' % (self.OUTPUT_DIR, self.NAME) mocked_file = mocked.return_value writer = FileWriter(cfg) results = writer.write(dict(), self.NAME, self.CONTENT) mocked.assert_called_once_with(path, 'w') ...
.write.assert_called_with(self.CONTENT) assert_equal(results, [path]) class TestLavaWriter(object): DEVICE_TYPE = 'foo_bar' CONTENT = 'test' NAME = 'test-job-name' UI_ADDRESS = 'http://webui.example.org' @mock.patch('xmlrpc.client.ServerProxy') def test_connection_error(self, mock...
ghost9023/DeepLearningPythonStudy
DeepLearning/DeepLearning/02_Deep_ChoTH/tensorflow_prac.py
Python
mit
18,788
0.011447
##### 텐서 딥러닝 1장 import tensorflow as tf hello = tf.constant('Hello, Tensorflow') sess = tf.Session() print(sess.run(hello)) # 'b'는 bytes literals라는 뜻이다. node1 = tf.constant(3.0, tf.float32) # 숫자, 데이터타입 node2 = tf.constant(4.0) # 숫자, 데이터타입 node3 = tf.add(node1, node2) # 숫자, 데이터타입 # node3 = node1 + node2 # 이렇게도 사용가...
) if step%100 == 0: print(step, sess.run(cost, feed_dict={X:x_data, Y:y_data})) # Accuracy report h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X:x_data, Y:y_data}) print("\nHypothesis:", h,
"\nCorrect:", c, "\nAccuracy:", a) # Accuracy: 0.75 # 층이 많다고 무조건 정확도가 올라가는 것이 아니다. # 왜냐하면 오차역전파를 하면서 시그모이드에 의해 항상 1보다 작은 숫자가 계속 곱해지면서 최종적인 값이 점점 작아지게 된다. # 뒤로 갈 수록, 즉 입력값에 가까울 수록 영향력이 작아지면서 기울기가 사라지게 된다. vanishing gradient # 그래서 렐루를 사용한다. 마지막만 시그모이드를 사용한다. 0~1 사이의 값을 가져야하기 때문에 # 초기값을 줄 때 유의사항 # 1. 0을 주면 안된다. # 2. RBM...
blancltd/glitter-news
glitter_news/urls.py
Python
bsd-2-clause
849
0.002356
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import url from . import feeds, views urlpatterns = [ url(r'^$', views.PostListView.as_view(), name='list'), url( r'^category/(?P<slug>[-\w]+)/$', views.PostListCategoryView....
/$', views.PostDetailView.as_view(), name='post-detail' ), url(r'^feed/$', feeds.NewsFeed(), name='feed'), url(r'^feed/(?P<slug>[-\w]+)/$', feeds.NewsCategoryFeed(), name='category-feed'), ] if getattr(settings, 'GLITTER_NEWS_TAGS', Fals
e): urlpatterns += [ url(r'^tag/(?P<slug>[-\w]+)/$', views.PostListTagView.as_view(), name='post-list-tag'), ]
djaodjin/djaodjin-survey
survey/api/campaigns.py
Python
bsd-2-clause
3,013
0.000332
# Copyright (c) 2020, DjaoDjin 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
count": "envconnect", "title": "Assessment on Best Practices", "active": true, "quizz_mode": false, "que
stions": [ { "path": "/product-design", "title": "Product Design", "unit": "assessment-choices", }, { "path": "/packaging-design", "title": "Packaging Design", ...
MartinPaulo/resplat
storage/migrations/0015_auto_20170914_0154.py
Python
lgpl-3.0
1,300
0.000769
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-14 01:54 from __futu
re__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import storage.models.labels class Migration(migrations.Migration): dependencies = [ ('storage', '0014_auto_20170914_0146'), ] operations = [ migrations
.RemoveField( model_name='accesslayer', name='active_flag', ), migrations.RemoveField( model_name='accesslayer', name='created_by', ), migrations.RemoveField( model_name='accesslayer', name='creation_date', )...
alvcarmona/efficiencycalculatorweb
effcalculator/effcalculator/urls.py
Python
gpl-3.0
915
0.001093
"""effcalculator 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') 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...
ngo.contrib import admin from django.conf.urls import url, include from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('api.urls')), url(r'^', include('frontend.urls')) ]
zenefits/sentry
src/sentry/south_migrations/0104_auto__add_groupseen__add_unique_groupseen_group_user.py
Python
bsd-3-clause
28,081
0.008048
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'GroupSeen' db.create_table(u'sentry_groupseen', ( ('id', self.gf('sentry.db.mode...
e': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'sentry.accessgroup': { 'Meta': {'unique_together': "(('team', 'name'),)", 'object_name': 'AccessGroup'}, 'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'da...
entry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'managed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['sentry.User']", 'symmetrical': 'False'}), ...
rickerc/cinder_audit
cinder/openstack/common/scheduler/weights/__init__.py
Python
apache-2.0
1,305
0
# Copyright (c) 2011 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...
NTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the Lice
nse. """ Scheduler host weights """ from cinder.openstack.common.scheduler import weight class WeighedHost(weight.WeighedObject): def to_dict(self): return { 'weight': self.weight, 'host': self.obj.host, } def __repr__(self): return ("WeighedHost [host: %s, ...
kidaa/kythe
third_party/grpc/src/python/src/grpc/framework/foundation/_timer_future.py
Python
apache-2.0
6,903
0.01101
# Copyright 2015, 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 list of conditions and the f...
return else: self._computing = True try: return_value = self._computation() except
ion = None traceback = None except Exception as e: # pylint: disable=broad-except return_value = None exception = e traceback = sys.exc_info()[2] with self._lock: self._computing = False self._computed = True self._return_value = return_value self._exception = e...
CloudServer/cinder
cinder/tests/unit/api/test_common.py
Python
apache-2.0
24,477
0
# Copyright 2010 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under...
om cinder.api import common from cinder import test NS = "{http://docs.openstack.org/compute/api/v1.1}" ATOMNS = "{http://www.w3.org/2005/Atom}" class LimiterTest(test.TestCase): """Unit tests for the `cinder.api.common.limited` method. This method takes in a list of items and, depending on the 'offset' ...
EthanGuo/regular-ticket-task
worker.py
Python
mit
325
0.003077
# -*-coding: utf-8-*- from
celery import Celery from op import utils import celeryconfig worker = Celery('Regular-Ticket-Task') worker.config_from_object(celeryconfig) worker.conf.BROKER_URL = utils.get_config('celery', 'BROKER_URL') worker.conf.CELERY_RESULT_BACKEND = utils.get_config('celery', 'CELERY_RE
SULT_BACKEND')
TLemur/freq-bot
src/plugins/help/help_handler.py
Python
gpl-3.0
2,586
0.023975
#!/usr/bin/env python # -*- coding: utf8 -*- #~####################################################################### #~ Copyright (c) 2008 Burdakov Daniel <kreved@kreved.org> # #~ # #~ This file is part of FreQ-bot. ...
d_help_content(p, rlang) categories = ', '.join([w fo
r w in HELP_CATEGORIES.keys() if p in HELP_CATEGORIES[w]]) s.lmsg(t, 'help_show', categories, content) else: languages = HELP_LANGS[p] languages = ["'.help -%s %s'" % (w, p) for w in languages] s.lmsg(t, 'help_other_languages', p, rlang, ', '.join(languages)) else: s.lmsg(t, 'help_not_found',...
ChrisTruncer/PenTestScripts
HostScripts/DNSInject.py
Python
gpl-3.0
4,615
0.002384
#!/usr/bin/env python # by Chris Truncer # Script to attempt to forge a packet that will inject a new value # for a dns record. Check nessus plugin #35372 # Some great documentation and sample code came from: # http://bb.secdev.org/scapy/src/46e0b3e619547631d704c133a0247cf4683c0784/scapy/layers/dns.py import argpar...
_packet = sr1(IP(dst=name_server)/UDP()/DNS( opcode=5, qd=[DNSQR(qname=dns_zone, qtype="SOA")], ns=[DNSRR(rrname=new_dns_record, type="A", ttl=120, rdata=ip_value)])) print add_packet[DNS].summary() print "\n[*] Packet created and sent!" def cli_parser(): # Command l...
dd_argument( "--add", action='store_true', help="Add \"A\" record to the vulnerable name server.") parser.add_argument( "--delete", action='store_true', help="Delete \"A\" record from the vulnerable name server.") parser.add_argument( "-ns", metavar="ns1.test.com", ...
mateusportal/portalconta
empresas/forms.py
Python
gpl-2.0
537
0.007449
from django import forms from empresas.models import Usuario, Pessoa, Empresa class LoginForm(forms.Form): username = forms.CharField(max_length='200', required=True) password = forms.CharField(widget=forms.PasswordInput, required=True) class UsuarioForm(forms.ModelForm): password = forms.
CharField(widget=forms.PasswordInput) class Meta: model = Usuario class PessoaForm(forms.ModelForm): class Meta: model = Pessoa class EmpresaForm(forms.ModelForm): cl
ass Meta: model = Empresa
JulyKikuAkita/PythonPrac
cs15211/ConvertANumberToHexadecimal.py
Python
apache-2.0
4,592
0.004138
__source__ = '' # https://github.com/kamyu104/LeetCode/blob/master/Python/convert-a-number-to-hexadecimal.py # Time: O(logn) # Space: O(1) # # Description: # # Given an integer, write an algorithm to convert it to hexadecimal. # For negative integer, two's complement method is used. # # IMPORTANT: # You must not use a...
turally deal with negative number. StringBuilder is used due to its efficiently in inserting character to existing StringBuilder object. If normal St
ring is used then each insertion by + operation will have to copy over the immutable String object which is highly inefficient. For Integer.MAX_VALUE or Integer.MIN_VALUE or any input with 8 Hexadecimal characters where the iterations would last the longest. For Integer.MAX_VALUE the algorithm will run for at most log ...
bblacey/FreeCAD-MacOS-CI
src/Mod/Fem/PyGui/_CommandFemMeshNetgenFromShape.py
Python
lgpl-2.1
3,519
0.002273
# *************************************************************************** # * * # * Copyright (c) 2013-2015 - Juergen Riegel <FreeCAD@juergen-riegel.net> * # * * # * Th...
super(_CommandFemMeshNetgenFromShape, self).__init__() self.resources = {'Pixmap': 'fem-femmesh-netgen-from-shape', 'MenuText': QtCore.QT_TRANSLATE_NOOP("FEM_MeshFromShape", "FEM mesh from shape by Netgen"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("FEM_Me...
_active = 'with_part_feature' def Activated(self): FreeCAD.ActiveDocument.openTransaction("Create FEM mesh Netgen") FreeCADGui.addModule("FemGui") sel = FreeCADGui.Selection.getSelection() if (len(sel) == 1): if(sel[0].isDerivedFrom("Part::Feature")): Fre...