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
ncclient/ncclient
examples/vendor/juniper/unknown-rpc.py
Python
apache-2.0
861
0.002323
#!/usr/bin/env python import logging from ncclient
import manager from ncclient.xml_ import * def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=60, dev...
rmation('brief', test='me') logging.info(result) result = conn.get_chassis_inventory('extensive') logging.info(result) if __name__ == '__main__': LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORM...
tannishk/airmozilla
airmozilla/manage/urls.py
Python
bsd-3-clause
12,711
0
from django.conf.urls import patterns, url from .views import ( picturegallery, dashboard, events, approvals, suggestions, vidly_media, comments, loggedsearches, users, groups, channels, locations, regions, templates, topics, tags, recruitmentmessages...
ates/new/$', templates.template_new, name='template_new'), url(r'^templates/(?P<id>\d+)/$', templates.template_edit, name='template_edit'), url(r'^templates/(?P<id>\d+)/migrate/$', templ
ates.template_migrate, name='template_migrate'), url(r'^templates/remove/(?P<id>\d+)/$', templates.template_remove, name='template_remove'), url(r'^templates/$', templates.templates, name='templates'), url(r'^tags/$', tags.tags, name='tags'), url(r'^tags/data/$', tags.tags_data, name='ta...
starrify/scrapy
scrapy/downloadermiddlewares/httpcache.py
Python
bsd-3-clause
5,481
0.001642
from email.utils import formatdate from typing import Optional, Type, TypeVar from twisted.internet import defer from twisted.internet.error import ( ConnectError, ConnectionDone, ConnectionLost, ConnectionRefusedError, DNSLookupError, TCPTimedOutError, TimeoutError, ) from twisted.web.clie...
return None def process_response(self, request: Request, response: Response, spider: Spider) -> Response: if request.meta.get('dont_cache', False): return response # Skip cached responses and uncacheable requests
if 'cached' in response.flags or '_dont_cache' in request.meta: request.meta.pop('_dont_cache', None) return response # RFC2616 requires origin server to set Date header, # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18 if 'Date' not in response.h...
CDHgit/cs3240-labdemo
helper.py
Python
mit
137
0.043796
def greeting(msg): print(msg) def valedi
ction(msg): for char in reversed(msg): print(char, e
nd = "" ) print("\n")
IMIO/django-fixmystreet
django_fixmystreet/webhooks/inbound.py
Python
agpl-3.0
6,983
0.003007
# -*- coding: utf-8 -*- # pylint: disable=C0321,E1120,E1123,W0223 """ Inbound webhook handlers. """ from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django_fixmystreet.fixmystreet.models import FMSUser, Report, ReportAttachment, ReportComment, ReportEvent...
, user=None): super(AbstractReportInWebhook, self).__init__(meta, data, user=user) self._report = Report.objects.get(pk=meta["id"]) self._third_party = None def _add_comment(self, context): context["action_msg"] = context["action_msg"].format(third_party=self._third_party.name) ...
pk=self._user.id) comment = ReportComment( report=self._report, text=formatted_comment, type=ReportAttachment.DOCUMENTATION, created_by=fms_user ) comment.save() def _user_has_permission(self): raise NotImplementedError() def _validate(self): if self._third_...
aranjan7/contrail-controller-aranjan
src/config/utils/provision_encap.py
Python
apache-2.0
5,187
0.006748
#!/usr/bin/python # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # import sys import argparse import ConfigParser from vnc_api.vnc_api import * class EncapsulationProvision(object): def __init__(self, args_str=None): self._args = None if not args_str: args_str = '...
Type(encapsulation=self._args.encap_priority.split(",")) try: current_config=self._vnc_lib.global_vrouter_config_read(
fq_name=['default-global-system-config', 'default-global-vrouter-config']) except Exception as e: if self._args.oper == "add": conf_obj=GlobalVrouterConfig(encapsulation_priorities=encap_obj,vxlan_network_identifier_mode=self._args.vxl...
harshilasu/GraphicMelon
y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/integration/ec2/test_connection.py
Python
gpl-3.0
8,892
0.000225
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2009, Eucalyptus Systems, 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 res...
group2.name, group2.owner_id) assert status # now try specifying a specific port status = c.authorize_security_group(group1.name, group2.name, group...
status = c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status # now delete the second security group status = c.delete_securit...
hortonworks/hortonworks-sandbox
apps/oozie/src/oozie/management/commands/oozie_setup.py
Python
apache-2.0
3,188
0.006589
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
remote_home_dir = Hdfs.join('/user', "hdfs") if directory.startswith(remote_home_dir): # Home is 755 fs.do_as_user("hdfs", fs.create
_home_dir, remote_home_dir) # Shared by all the users fs.do_as_user("hdfs", fs.mkdir, directory, 511) fs.do_as_user("hdfs", fs.chmod, directory, 511) # To remove after https://issues.apache.org/jira/browse/HDFS-3491 return REMOTE_SAMPLE_DIR.get()
t3dev/odoo
addons/hw_drivers/__manifest__.py
Python
gpl-3.0
592
0.001689
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Hardware Proxy', 'category': 'IOT', 'sequence': 6, 'summary': 'Connect the Web Client to Hardware Peripherals', 'websi
te': 'https://www.odoo.com/page/iot', 'description': """ Hardware Poxy ============= This module allows you to remotely use peripherals connected to this se
rver. This modules only contains the enabling framework. The actual devices drivers are found in other modules that must be installed separately. """, 'installable': False, }
bokeh/bokeh
sphinx/source/docs/first_steps/examples/first_steps_1_simple_line.py
Python
bsd-3-clause
358
0
from bokeh.plotting import figure, show # prepare some data x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] # create a new plot with a title
and axis labels p = figure(title="Simple line example", x_axis_label="x", y_axis_label="y") # add a line renderer with l
egend and line thickness p.line(x, y, legend_label="Temp.", line_width=2) # show the results show(p)
google-research/google-research
non_semantic_speech_benchmark/data_prep/beam_dofns_test.py
Python
apache-2.0
16,889
0.004855
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# Establish required key names. audio_key = 'audio_key' custom_call_shape = (5, 25) # Custom call function for embedding generation. def test_call_fn(audio_samples, sample_rate, module_location, output_key, name): """Mock waveform-to-embedding computation.""" del au...
ple test data. ex = tf.train.Example() ex.features.feature[audio_key].float_list.value.extend( np.zeros(2000, np.float32)) if sample_rate_key: ex.features.feature[sample_rate_key].int64_list.value.append(8000) old_k = 'oldkey' do_fn = beam_dofns.ComputeEmbeddingMapFn( name='m...
ChantyTaguan/zds-site
zds/mp/validators.py
Python
gpl-3.0
3,768
0.002132
from django.http import Http404 from django.shortcuts import get_object_or_404 from django.utils.translation import gettext_lazy as _ from zds.api.validators import Validator from zds.member.models import Profile class ParticipantsUserValidator(Validator): can_be_empty = False def validate_participants(self,...
lf): raise NotImplementedError("`get_current_user()` must be implemented.") class ParticipantsStringValidator(Validator): """ Validates participants field of a MP. """ def validate_participants(self, value, username): """ Checks about participants. :param value: parti...
if value: participants = value.strip() if participants != "": if len(participants) == 1 and participants[0].strip() == ",": msg = _("Vous devez spécfier des participants valides.") for participant in participants.split(","): ...
pbabik/OGCServer
tests/testWsgi.py
Python
bsd-3-clause
1,893
0.005811
import nose def start_response_111(status, headers): for header in headers: if header[0] == 'Content-Type': assert header[1] == 'application/vnd.ogc.wms_xml' assert status == '200 OK' def start_response_130(status, headers): for header in headers: if header[0] == 'Con...
n['QUERY_STRING'] = "EXCEPTION=application/vnd.ogc.se_xml&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities&" response = wsgi_app.__call__(environ, start_response_111) content = ''.join(response) environ['QUERY_STRING'] = "EXCEPTION=application/vnd.ogc.se_xml&VERSION=1.3.0&SERVICE=WMS&REQUEST=GetCapabi...
t() environ['QUERY_STRING'] = "EXCEPTION=application/vnd.ogc.se_xml&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&" response = wsgi_app.__call__(environ, start_response_check_404) environ['QUERY_STRING'] = "EXCEPTION=application/vnd.ogc.se_xml&VERSION=1.3.0&SERVICE=WMS&REQUEST=GetMap&" response = wsgi_ap...
hzlf/openbroadcast.ch
app/routing.py
Python
gpl-3.0
606
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.staticfiles import StaticFilesWrapper, StaticFilesHandler from chat.consumers import ChatJSONConsumer...
URLRouter([ url('^ws/chat/$', ChatJSONConsumer), url('^ws/rating/$', RatingJSO
NConsumer), ]) ), }))
psiq/gdsfactory
pp/mask/merge_metadata.py
Python
mit
914
0.003282
import pp from pp.mask.merge_json import merge_json from pp.mask.merge_markdown import merge_markdown from pp.mask.merge_test_metadata import merge_test_metadata from pp.mask.write_labels import write_labels def merge_metadata(gdspath, labels_prefix="opt", label_layer=pp.LAYER.LABEL, **kwargs): mdpath = gdspath.w...
(doe_directory=doe_directory, jsonpath=jsonpath, **kwargs) merge_markdown(reports_directory=doe_directory, mdpath=mdpath) merge_test_metadata(gdspath, labels_prefix=labels_prefix) if __name__ == "__main__": gdspath = pp.CONFIG["samples_path"] / "mask" / "build" / "mask" / "mask.gds"
print(gdspath) merge_metadata(gdspath)
dleicht/PSB
PyZenity.py
Python
mit
15,175
0.005074
################################################################################ # Name: PyZenity.py # Author: Brian Ramos # Created: 10/17/2005 # Revision Information: # $Date: $ # $Revision: $ # $Author: bramos $ # # Licence: MIT Licence # # Copyright (c) 2010 Brian Ramos # Permission is hereby g...
ANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 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 ...
m datetime import date from subprocess import Popen, PIPE from itertools import chain from os import path __all__ = ['GetDate', 'GetFilename', 'GetDirectory', 'GetSavename', 'GetText', 'InfoMessage', 'Question', 'Warning', 'ErrorMessage', 'Notification', 'TextInfo', 'Progress','List' ] __doc__ ...
janusnic/shoop
shoop/front/apps/customer_information/urls.py
Python
agpl-3.0
432
0
# -*- coding:
utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.conf.urls import patterns, url from . import views urlpatterns = patterns( ...
name='customer_edit'), )
jakevdp/bokeh
sphinx/source/tutorial/solutions/olympics.py
Python
bsd-3-clause
3,262
0.003679
import json import numpy as np from bokeh.plotting import * from bokeh.sampledata.olympics2014 import data from bokeh.objects import ColumnDataSource data = { d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0} # pull out just the data we care about countries = sorted( data.ke...
r_label_orientation = np.pi/3 xaxis().major_label_standoff =
6 xaxis().major_tick_out = 0 # EXERCISE: create a new figure figure() # Categorical percentage coordinates can be used for positioning/grouping countries_bronze = [c+":0.3" for c in countries] countries_silver = [c+":0.5" for c in countries] countries_gold = [c+":0.7" for c in countries] # EXERCISE: re create the m...
jessamynsmith/boards-backend
blimp_boards/cards/urls.py
Python
agpl-3.0
471
0
from django
.conf.urls import patterns, url from rest_framework.routers import DefaultRouter from ..boards.views import BoardHTMLView from . import views router = DefaultRouter() router.register(r'cards', views.CardViewSet) api_urlpatterns = router.urls urlpatterns = patterns( # Prefix '', url(r'^$', Bo...
d_download'), )
Microsoft/pxt
tests/pyconverter-test/cases/empty_array_declaration.py
Python
mit
40
0.025
def f1():
while True:
x = []
tidepool-org/dfaker
tests/test_common_fields.py
Python
bsd-2-clause
1,297
0.000771
from chai import Chai import unittest import dfaker.common_fields as common_fields import dfaker.tools as tools class Test_Common_Fields(Chai): def test_common_fields(self): """ Test that common fields populate properly""" name = "bolus" datatype = {} timestamp = tools.convert_IS...
} result_dict = common_fields.add_common_fields(name, datatype, timestamp, zonename) for key in expected.keys(): self.assertEqual(result_dict[key], expected[key]) def
suite(): """ Gather all the tests from this module in a test suite """ test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(Test_Common_Fields)) return test_suite mySuit = suite() runner = unittest.TextTestRunner() runner.run(mySuit)
luisalves05/shortener-url
src/apps/miudo/views.py
Python
mit
1,890
0.013757
import uuid from random import randint from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Url def index(request): if request.session.has_key("has_url"): url = request.session.get("has_url") del request.session['has_url'] return render(req...
make_url(request): if reques
t.method == "POST": url = None # initial url url_site = request.POST['url'] url_id = generate_key() try: url = Url.objects.get(url_id = url_id) while url: url_id = generate_key() url = Url.objects.get(url_id = url_id) ...
iksaif/euscan
euscanwww/euscan_captcha/urls.py
Python
gpl-2.0
236
0
from django
.conf.urls import patterns, url from views import RecaptchaRegistrationView urlpatterns = patterns( '', url( r'^register/$', RecaptchaRegistrationView.as_view(), name='registration_regi
ster'), )
TOC-Shard/moul-scripts
Python/tldnShroomieGate.py
Python
gpl-3.0
4,105
0.005359
# -*- coding: utf-8 -*- """ *==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3...
SDL["tldnShroomieGateUp"][0]: print "tldnShroomieGate:\tInit---Shroomie Gate Up" respGateUp.run(self.key,fastforward=1) else: print "tldnShroomieGate:\tInit---Shroomie Gate Down" respGateDown.run(self.key,fastforwar
d=1)
paera/django-static-precompiler
static_precompiler/tests/test_management.py
Python
mit
1,188
0.001684
from django.core.management import call_command from static_precompiler.management.commands.compilestatic import get_scanned_dirs from static_precompiler.settings import STATIC_ROOT, ROOT, OUTPUT_DIR import pytest import os def test_get_scanned_dirs(): assert get_scanned_dirs() == sorted([ os.path.join(o...
name(__file__), "staticfiles_dir"), os.path.join(o
s.path.dirname(__file__), "staticfiles_dir_with_prefix"), STATIC_ROOT ]) @pytest.mark.django_db def test_compilestatic_command(): call_command("compilestatic") output_path = os.path.join(ROOT, OUTPUT_DIR) compiled_files = [] for root, dirs, files in os.walk(output_path): for fil...
jeroenseegers/git-history
git_history.py
Python
mit
1,296
0
import os import subprocess import sys __version__ = '0.0.1' __author__ = 'Jeroen Seegers' __license__ = 'MIT' HOME_DIR = os.path.expanduser('~') HISTORY_FILE = HOME_DIR + '/.git-history.log' def ensure_history_file(): """Ensure the history file exists""" if not os.path.isfile(HISTORY_FILE) and os.access(...
ents = sys.argv[1:] arguments.insert(0, 'git') if arguments == ['git', 'history']: # Show the history so far with open(HISTORY_FILE, 'r') as f: print f.read() f.close() elif len(arguments) > 1: # Store command in history if ensure_history_file(): ...
t(' '.join(sys.argv[1:]))) f.close() # Execute given command subprocess.call(arguments) else: # Show default help text subprocess.call('git') if __name__ == '__main__': track_history()
fnp/wolnelektury
src/club/migrations/0011_fix_notification_body.py
Python
agpl-3.0
585
0
# Generated
by Django 2.2.5 on 2019-09-30 13:02 from django.db import migrations def fix_notification_body(apps, schema_editor): PayUNotification = apps.get_model('club', 'PayUNotification') for n in PayUNotifica
tion.objects.filter(body__startswith='b'): n.body = n.body[2:-1] n.save() class Migration(migrations.Migration): dependencies = [ ('club', '0010_auto_20190529_0946'), ] operations = [ migrations.RunPython( fix_notification_body, migrations.RunPytho...
bittner/django-media-tree
media_tree/contrib/cms_plugins/media_tree_slideshow/__init__.py
Python
bsd-3-clause
903
0.007752
""" Plugin: Slideshow ***************** This plugin allows you to put a slideshow on a page, automatically displaying the selected image files with customizable transitions and intervals. Installation ============ To use this plugin, put ``media_tree.contrib.cms_plugins.media_tree_slideshow`` in your installed app...
ault, images are rendered to the output using the template ``media_tree/filenode/includes
/figure.html``, which includes captions. .. Note:: The default template requires you to include `jQuery <http://jquery.com/>`_ in your pages, since it uses the `jQuery Cycle Plugin <http://jquery.malsup.com/cycle/>`_ (bundled) for image transitions. """
brosner/nip
setup.py
Python
mit
461
0.043384
from distutils.core import setup setup( name
= "nip", version = "0.1a1", py_modules = [ "nip", ], scripts = [ "bin/nip", ], author = "Brian Rosner", author_email = "brosner@gmail.com", description = "nip is environment isolation and installation for Node.js", long_description = open("README.rst").read(), li...
Alpha", ], )
rwl/PyCIM
CIM15/IEC61970/Informative/InfGMLSupport/GmlFill.py
Python
mit
6,721
0.002381
# Copyright (C) 2010-2011 Richard Lincoln # # 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, publish...
self._GmlMarks def setGmlMarks(self, value): for p in self._GmlMarks: filtered = [q
for q in p.GmlFIlls if q != self] self._GmlMarks._GmlFIlls = filtered for r in value: if self not in r._GmlFIlls: r._GmlFIlls.append(self) self._GmlMarks = value GmlMarks = property(getGmlMarks, setGmlMarks) def addGmlMarks(self, *GmlMarks): for...
wbolster/whip
whip/db.py
Python
bsd-3-clause
12,080
0
""" Whip database storage module. All IP ranges with associated information are stored in a LevelDB database. Some remarks about the construction of database records: * The most recent version of a record is stored in full, and older dicts are stored in a history structure of (reverse) diffs. This saves a lot of...
msgpack_loads_utf8
(self.history_msgpack), inplace=inplace) class Database(object): """ Database access class for loading and looking up data. """ def __init__(self, database_dir, create_if_missing=False): logger.debug("Opening database %s", database_dir) self.db = plyvel.DB( dat...
jamslevy/gsoc
app/soc/models/ranker_root.py
Python
apache-2.0
1,077
0.0065
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the RankerRoot model """ __authors__ = [ '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from google.appengine.ext import db import soc.models.linkable class RankerRoot(soc.m...
.Linkable): """Links the Root of a RankList tree to an owner and also gives it an unique ID. """ #: A required reference property to the root of the RankList tree root = db.ReferenceProperty(required=True, collection_name='roots')
mattsch/Sickbeard
cherrypy/test/test_auth_basic.py
Python
gpl-3.0
2,949
0.004747
# This file is part of CherryPy <http://www.cherrypy.org/> # -*- coding: utf-8 -*- # vim:ts=4:sw=4:expandtab:fileencoding=utf-8 from cherrypy.test import test test.prefer_parent_path() try: from hashlib import md5 except ImportError: # Python 2.4 and earlier from md5 import new as md5 import...
self.assertBody('This is public.') def testBasic(self): self.getPage("/basic/") self.assertStatus(401) self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"') self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')]) self.as
sertStatus(401) self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')]) self.assertStatus('200 OK') self.assertBody("Hello xuser, you've been authorized.") def testBasic2(self): self.getPage("/basic2/") self.assertStatus(401) self.assertH...
cjaymes/pyscap
src/scap/model/oval_5/defs/windows/EntityStatePeSubsystemType.py
Python
gpl-3.0
1,004
0.000996
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP.
If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5 import PE_SUBSYSTEM_ENUMERATION from scap.model.oval_5.defs.EntityStateType import EntityStateType logger = logging.getLogger(__name__) class EntityStatePeSubsystemType(EntityStateType): MODEL_MAP = { } def get_value_en...
nick6918/ThingCloud
ThingCloud/ThingCloud/urls.py
Python
mit
2,763
0.001448
"""ThingCloud URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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-...
System.views import index from AccountSystem.views import loginByPhone, register, sendCode, address, addressList, deleteAddress, changePassword, changeNickname, updateAvatar from CloudList.views import addNewItem, getItemList, modifyNotes from OrderSystem.views import generateOrder, modifyOrder, con
firmOrder, getOrderList, cancel, complain, update, orderCallback, getOrder, delete, vipCallback from AssistSystem.views import feedback, checkDiscount, activityList, versionInfo, communityList,getFeeList, joinUs from VIPSystem.views import vip, vipOrder, vipConfirm urlpatterns = [ url(r'^admin/', include(admin.sit...
chrisforrette/django-social-content
social_content/conf.py
Python
mit
814
0
from django.conf import settings DEFAULTS = { 'SOCIAL_CONTENT_TYPES': ( 'Facebook', 'Twitter',
'Instagram', ), 'SOCIAL_CONTENT_MAX_POSTS': None, # Facebook 'FACEBOOK_APP_ID': None, 'FACEBOOK_APP_SECRET': None, # Twitter 'TWITTER_CONSUMER_KEY': None, 'TWITTER_CONSUMER_SECRET': None, 'TWITTER_ACCESS_TOKEN_KEY': None, 'TWITTER_ACCESS_TOKEN_SECRET': None, # Ins...
GRAM_CLIENT_SECRET': None, 'INSTAGRAM_ACCESS_TOKEN': None, # YouTube 'YOUTUBE_APP_API_KEY': None, # Tumblr 'TUMBLR_API_CONSUMER_KEY': None } for setting in DEFAULTS.keys(): try: getattr(settings, setting) except AttributeError: setattr(settings, setting, DEFAULTS[settin...
vlegoff/tsunami
src/secondaires/magie/editeurs/spedit/__init__.py
Python
bsd-3-clause
9,326
0.002161
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 # ...
ut", 1) tribut.parent = self tribut.prompt = "Points de tribut nécessaire pour apprendre le sort : " tribut.apercu = "{objet.points_tribut}" tribut.aide_courte = \ "Entrez le |ent|nombre de points de tribut|ff| nécessaires "\ "pour apprendre le sort\nou |cmd|/|ff|...
elements = self.ajouter_choix("eléments", "e", Selection, sort, "elements", ELEMENTS) elements.parent = self elements.apercu = "{objet.str_elements}" elements.aide_courte = \ "Entrez un |ent|élément|ff| pour l'ajouter " \ "ou le retirer\nou |cmd|/|f...
AdrianGaudebert/socorro-crashstats
crashstats/crashstats/tests/test_forms.py
Python
mpl-2.0
12,838
0
import datetime from nose.tools import eq_, ok_ from django.conf import settings from django.test import TestCase from crashstats.crashstats import forms class TestForms(TestCase): def setUp(self): # Mocking models needed for form validation self.current_products = { 'Firefox': [], ...
release": "Beta", }, { 'product': 'SeaMonkey', 'version': '9.5', "release": "Beta" } ] self.current_platforms = [ { 'code': 'windows', 'name': 'Windows'
}, { 'code': 'mac', 'name': 'Mac OS X' }, { 'code': 'linux', 'name': 'Linux' } ] def test_report_list(self): def get_new_form(data): return forms.ReportListForm( ...
ondoheer/GOT-Platform
app/houses/views.py
Python
gpl-2.0
723
0
from
flask import Blueprint, request, render_template, jsonify from housesGenerator import House from holdings import Holdings houses = Blueprint('houses', __name__, url_prefix='/houses') @houses.route('/') def index(): return render_template('houses.html') @houses.route('/houseGenerator', methods=['GET', 'POST'])...
on') name = request.args.get('name') house = House.startingResources(realm, size, foundation, name) from holdings import holdingsData generatedHouse = Holdings(holdingsData).generateAllHoldings(house, realm) return jsonify(generatedHouse)
magosil86/ruffus
ruffus/drmaa_wrapper.py
Python
mit
18,668
0.013285
#!/usr/bin/env python from __future__ import print_function ################################################################################ # # # drmaa_wrapper.py # # Copyright (C) 2013 Leo Goodstadt # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associa...
time_stmp_str = "_".join(map(str, datetime.datetime.now().timetuple()[0:6])) # create script directory if necessary # Ignore errors rather than test for existence to avo
id race conditions try: os.makedirs(job_script_directory) except: pass tmpfile = tempfile.NamedTemporaryFile(mode='w', prefix='drmaa_script_' + time_stmp_str + "__", dir = job_script_directory, delete = False) # # hopefully #!/bin/sh is universally portable among unix-like operat...
pivotal-partner-solution-architecture/pcf-gcp-python
pcfgcp/pcfgcp.py
Python
apache-2.0
5,039
0.004366
# # Copyright (c) 2017-Present Pivotal Software, 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 req...
mplements the authentication part. Here are the various service names, as defined in https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/master/brokerapi/brokers/models/service_broker.go const StorageName = "google-storage" const BigqueryName = "google-bigquery" const BigtableName = "google-bigtable" co...
ame = "google-ml-apis" """ class PcfGcp: def __init__(self): self.VCAP_SERVICES = None self.clients = { 'storage': None , 'google-bigquery': None , 'google-bigtable': None , 'google-cloudsql': None , 'google-pubsub': None , 'l...
912/M-new
virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/base.py
Python
gpl-2.0
1,002
0.001996
from django.db.backends.creation import NO_DB_ALIAS from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from dj...
chema_editor(self, *args, **kwargs): "Returns a new instance of this backend's SchemaEditor" return PostGISSchemaEditor(self, *args, **kwar
gs)
cpfair/pyScss
scss/calculator.py
Python
mit
6,935
0.000433
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys import logging from warnings import warn import six from scss.ast import Literal from scss.cssdefs import _expr_glob_re, _interpolate_re from scss.errors import SassError, SassEvaluationErr...
, undefined_variables_fatal=True, ): if namespace is None: self.namespace = Namespace() else: self.namespace = namespace self.ignore_parse_err
ors = ignore_parse_errors self.undefined_variables_fatal = undefined_variables_fatal def _pound_substitute(self, result): expr = result.group(1) value = self.evaluate_expression(expr) if value is None: return self.apply_vars(expr) elif value.is_null: ...
Riizade/Magic-the-Gathering-Analysis
card.py
Python
mit
71
0.014085
class Card: count = 0 url = "" na
me = "" s
ideboard = -1
harshilasu/LinkurApp
y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/resultset.py
Python
gpl-3.0
6,557
0.00122
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # 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, modi...
e elif name == 'KeyMarker': self.key_marker = value elif name == 'NextMarker': self.next_marker = value elif name == 'NextKeyMarker': self.next_key_marker = value elif name == 'VersionIdMarker': self.version_id_marker = value elif n...
elif name == 'NextGenerationMarker': self.next_generation_marker = value elif name == 'UploadIdMarker': self.upload_id_marker = value elif name == 'NextUploadIdMarker': self.next_upload_id_marker = value elif name == 'Bucket': self.bucket = value ...
zhimin711/nova
nova/api/openstack/compute/schemas/migrate_server.py
Python
apache-2.0
1,742
0
# Copyright 2014 NEC Corporation. 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 ...
s.boolean, 'disk_over_commit': parameter_types.boolean, 'host': host }, 'required': ['block_migration', 'disk_over_commit', 'host'], 'additionalProperties': False, }, }, 'required': ['os-migrateLive'], 'additionalProperties': False,...
perties']['os-migrateLive']['properties'][ 'disk_over_commit'] migrate_live_v2_25['properties']['os-migrateLive']['properties'][ 'block_migration'] = block_migration migrate_live_v2_25['properties']['os-migrateLive']['required'] = ( ['block_migration', 'host'])
NeuromorphicProcessorProject/snn_toolbox
snntoolbox/simulation/backends/inisim/temporal_mean_rate_tensorflow.py
Python
mit
28,900
0
# -*- coding: utf-8 -*- """INI temporal mean rate simulator with Tensorflow backend. This module defines the layer objects used to create a spiking neural network for our built-in INI simulator :py:mod:`~snntoolbox.simulation.target_simulators.INI_temporal_mean_rate_target_sim`. The coding scheme underlying this conv...
_str == 'softmax': output_spikes = self.softmax_activation(new_mem) elif self.activation_str == 'binary_sigmoid': output_spikes = self.binary_sigmoid_activation(new_mem) elif self.activation_str == 'binary_tanh': output_spikes = self.binary_tanh_ac...
ion_str: m, f = map(int, self.activation_str[ self.activation_str.index('_Q') + 2:].split('.')) output_spikes = self.quantized_activation(new_mem, m, f) else: output_spikes = self.linear_activation(new_mem) else: ...
botify-labs/python-simple-workflow
swf/models/history/base.py
Python
mit
7,957
0.000628
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. from itertools import groupby from swf.models.event import EventFactory, CompiledEventFactory from swf.models.event.workflow import WorkflowExecutionEvent from swf.utils impor...
entId': 1, 'eventType': 'WorkflowExecutionStarted', 'workflowExecutionStartedEventAttributes': { 'taskList': { 'name': 'test' },
'parentInitiatedEventId': 0, 'taskStartToCloseTimeout': '300', 'childPolicy': 'TERMINATE', 'executionStartToCloseTimeout': '6000', 'workflowType': { 'version': '0.1', ...
kyleabeauchamp/EnsemblePaper
code/figures/plot_MCMC_traces.py
Python
gpl-3.0
1,098
0.004554
from fitensemble import belt import itertools import pandas as pd import numpy as np import matplotlib.pyplot as plt import ALA3 import experiment_loader grid = itertools.product(ALA3.ff_list, ALA3.prior_list) bayesian_bootstrap_run = 0 for k, (ff, prior) in enumerate(grid): print(ff, prior) regulari
zation_strength = ALA3.regularization_strength_dict[prior][ff] predictions, measurements, uncertainties = experiment_loader.load(ff) pymc_filename = ALA3.data_directory + "/models/model_%s_%s_reg-%.1f-BB%d.h5" % (ff, prior, regularization_strength, bayesian_bootstrap_run) belt_model = belt.BELT....
len(y)) * ALA3.thin plt.plot(x, y) plt.xlabel("MCMC steps") #plt.ylabel(r"$\alpha$:" + str(predictions.columns[0])) plt.ylabel(predictions.columns[0]) plt.savefig(ALA3.outdir+"/%s-%s-MCMC_Trace.png" % (prior, ff), bbox_inches='tight')
brianseltzer1738/Platformer
platformer.py
Python
mit
4,532
0.007061
""" platformer.py Author: Brian S Credit: Finn H Assignment:
Write and submit a program that implements the sandbox platformer game: https://github.com/HHS-IntroProgramming/Platformer """ from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset, ImageAsset, Frame SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 800 blue = Color(0x2EFE
C8, 1.0) black = Color(0x000000, 1.0) pink = Color(0xFF00FF, 1.0) red = Color(0xFF5733, 1.0) white = Color(0xFFFFFF, 1.0) red = Color(0xff0000, 1.0) green = Color(0x00ff00, 1.0) blue = Color(0x0000ff, 1.0) black = Color(0x000000, 1.0) white = Color(0xffffff, 1.0) grey = Color(0xC0C0C0, 1.0) thinline = LineStyle(2, bla...
fflewddur/python-phash
docs/conf.py
Python
cc0-1.0
8,370
0.007407
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # au...
URL addresses after external links. #latex_show_urls = False # Documents
to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual...
guyromm/greencouriers
greencouriers/tests/functional/test_courier.py
Python
gpl-3.0
209
0.004785
from greencouriers.tests import * class TestCourierController(TestController): def test_index(self): response = self.app.get(url(controller='courier', a
ction='index')) # Test
response...
caseydunham/tweet-dump
tweet-dump.py
Python
mit
5,740
0.005401
""" Copyright (c) 2012 Casey Dunham <casey.dunham@gmail.com> 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, merg...
URL % encoded_params resp = fetch_url(query) ratelimit_limit = resp.headers["X-RateLimit-Limit"] ratelimit_remaining = resp.headers["X-RateLimit-Remaining"] ratelimit_reset = re
sp.headers["X-RateLimit-Reset"] tweets = json.loads(resp.read()) return ratelimit_remaining, tweets def get_initial_rate_info(): resp = fetch_url(RATE_LIMIT_API_URL) rate_info = json.loads(resp.read()) return rate_info["remaining_hits"], rate_info["reset_time_in_seconds"], rate_info["reset_time"] ...
enthought/etsproxy
enthought/envisage/resource/resource_manager.py
Python
bsd-3-clause
103
0
# proxy
module from __future__ import absolute_import from envisage.resource.resource_manager
import *
mhrivnak/pulp
client_consumer/pulp/client/consumer/config.py
Python
gpl-2.0
4,554
0.001976
# Copyright (c) 2014 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the impl...
ng': { 'scheme': 'amqp', 'host': None, 'port': '5672', 'transport': 'qpid',
'cacert': None, 'clientcert': None, }, 'profile': { 'minutes': '240', } } SCHEMA = ( ('server', REQUIRED, ( ('host', REQUIRED, ANY), ('port', REQUIRED, NUMBER), ('api_prefix', REQUIRED, ANY), ('verify_ssl', REQUIRED, BOOL), ...
8l/beri
cheritest/trunk/tests/cp2/test_cp2_x_cincoffset_sealed.py
Python
apache-2.0
2,058
0.003887
#- # Copyright (c) 2014 Michael Roe # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BER...
. BERI licenses this # file to you under the BERI Hardware-Software License, Version 1.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.beri-open-systems.org/legal/license-1-0.txt # # Unless required by applicable law or agreed to in writing, Work distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF AN...
jezdez/django-constance
tests/settings.py
Python
bsd-3-clause
3,003
0
from datetime import datetime, date, time, timedelta from decimal import Decimal SECRET_KEY = 'cheese' MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.Authe...
rib.auth', 'django.contrib.contenttypes', 'django
.contrib.sessions', 'django.contrib.messages', 'constance', 'constance.backends.database', ) ROOT_URLCONF = 'tests.urls' CONSTANCE_REDIS_CONNECTION_CLASS = 'tests.redis_mockup.Connection' CONSTANCE_ADDITIONAL_FIELDS = { 'yes_no_null_select': [ 'django.forms.fields.ChoiceField', { ...
unomena/django-1.8-registration
registration/backends/default/urls.py
Python
bsd-3-clause
2,086
0.000959
""" URLconf for registration and activation, using django-registration's default backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('registration.backends.default.urls')), ...
using 404. url( r'^activate/(?P<activation_key>\w+)/$', activate, {'backend': 'registration.backends.default.DefaultBackend'}, name='registration_activate' ), url( r'^register/$', register, {'backend': 'registration.backends.default.DefaultBackend'}, ...
template_name='registration/registration_complete.html' ), name='registration_complete' ), url( r'^register/closed/$', generic_views.TemplateView.as_view( template_name='registration/registration_closed.html' ), name='registration_disallowed' ...
scottkirkwood/mm2s5
build_all.py
Python
apache-2.0
556
0.01259
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2009 Scott Kirkwood. All Rights Reserved. """ Build everything for mm2s5. You'll need: sudo apt-get install alien help2man fakeroot lintian Also python-bdist """ from pybdist import pybdist import opt
parse import setup def main(): parser = optparse.OptionParser() pybdist.add_standard_options(parser) (options, unused_args) = parser.parse_args() if not pybdist.handle_standard_options(options, setup): print 'Doing nothing. --help for commands.' if __name__ == '__main__':
main()
mahabuber/erpnext
erpnext/accounts/doctype/cost_center/test_cost_center.py
Python
agpl-3.0
236
0.004237
# C
opyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe test_records = frappe.get_test_records('Cost Ce
nter')
tomgross/pp-site
src/itc.pptheme/itc/pptheme/browser/view.py
Python
apache-2.0
4,725
0.001058
# -*- coding: utf-8 -*- __author__ = 'itconsense@gmail.com' from collections import OrderedDict from math import pi from Products.Five import BrowserView from plone import api import base64 import logging import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import six LOG = logging.getLogger('eva...
result[group_title].details[title] = element.get('default') u_group_title = unicode(group_title, 'utf-8') if u_group_title not in df: df[u_group_title] = 0 df[u_group_title] += self.pie_factors[val] if good_values: ...
_title].good = ', '.join(good_values) if not result[group_title].details: LOG.warn('Details of group {0} are empty!'.format(group)) summary_elements = self.get_summary_elements() if summary < 75: result['summary'] = summary_elements['bad'] elif 75 >= summa...
mishravikas/geonode-cas
geonode/base/admin.py
Python
gpl-3.0
4,283
0.008872
from django.contrib import admin from django.conf import settings from geonode.base.m
odels import (TopicCategory, SpatialRepresentationType, Region, RestrictionCodeType, ContactRole, ResourceBase, Link, License, Thumbnail) class LicenseAdmin(admin.ModelAdmin): model = License list_display = ('id', 'name') list_display_links
= ('name',) class ResourceBaseAdmin(admin.ModelAdmin): list_display = ('id','title', 'date', 'category') list_display_links = ('id',) class TopicCategoryAdmin(admin.ModelAdmin): model = TopicCategory list_display_links = ('identifier',) list_display = ('identifier', 'description', 'gn_description...
Nikea/VisTrails
contrib/cdat/scripts/init_inc.py
Python
bsd-3-clause
1,823
0.012068
############################################################################ ## ## Copyright (C) 2006-2008 University of Utah. All rights reserved. ## ## This file is part of VisTrails. ## ## This file may be used under the terms of the GNU General Public ## License version 2.0 as published by the Free Software Foundat...
# """ Do not edit this file! File automatically generated by scripts/gen_init.py Change History: version : description 0.2 : Integrated quickplot module that displays the CDAT plot widget inside the spreadsheet 0.1 : First automatically generated package based on xml descriptions """ from PyQt4 im...
i import sip import core.modules import core.modules.module_registry from core.modules.vistrails_module import (Module, NotCacheable, ModuleError, new_module) from core.bundles import py_import import os, sys #cdat specific packages vcs = py_import('vcs',{}) cdms2 = py_import...
newmediamedicine/indivo_server_1_0
indivo/tests/integration/test_modules/sharing.py
Python
gpl-3.0
7,841
0.01658
import data from utils import assert_403, assert_404, assert_200, parse_xml, xpath PRD = 'prd' def test_sharing(IndivoClient): DS = 'ds' def get_datastore(obj): if hasattr(obj, DS): return getattr(obj, DS).values() return False def set_datastore(obj, **kwargs): if hasattr(obj, DS): d...
yet implemented #bob_chrome_client.get_carenet_app_permissions(account_id=bob_account_id) return True d
ef admin_setup(bob_account_id): admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret) admin_client.set_app_id(data.app_email) # Create a record for Alice and set her at the owner record_id = admin_client.create_record(data=data.contact).response[PRD]['Record'][0] admin_clien...
paris-ci/CloudBot
plugins/youtube.py
Python
gpl-3.0
6,992
0.003581
import re import time import isodate import requests from cloudbot import hook from cloudbot.util import timeformat from cloudbot.util.formatting import pluralize from cloudbot.util.colors import parse youtube_re = re.compile(r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)', re.I) base_
url = 'https://www.googleapis.com/youtube/v3/' api_url = base_url + 'videos?part=contentDetails%2C+snippet%2C+statistics&id={}&key={}' search_api_url = base_url + 'search?part=id&maxResults=1' playlist_api_url = base_url + 'playlists?part=snippet%2CcontentDetails%2Cstatus' video_url = "http://youtu.be/%s" err_no_api = ...
The YouTube API is off in the Google Developers Console." time_last_request = time.time() def get_video_description(video_id): global time_last_request time_elapsed = time.time() - time_last_request if time_elapsed > 10: time_last_request = time.time() else: #return "This looks like a...
eusebioaguilera/scalablemachinelearning
Lab04/ML_lab4_ctr_student.py
Python
gpl-3.0
54,867
0.004903
# coding: utf-8 # ![ML Logo](http://spark-mooc.github.io/web-assets/images/CS190.1x_Banner_300.png) # # **Click-Through Rate Prediction Lab** # #### This lab covers the steps for creating a click-through rate (CTR) prediction pipeline. You will work with the [Criteo Labs](http://labs.criteo.com/) dataset that was us...
data point representing an animal. The first feature indicates the type of animal (bear, cat, mouse); the second feature describes the animal's color (black, tabby); and the third (optional) feature describes what the animal eats (mouse,
salmon). # #### In a one-hot-encoding (OHE) scheme, we want to represent each tuple of `(featureID, category)` via its own binary feature. We can do this in Python by creating a dictionary that maps each tuple to a distinct integer, where the integer corresponds to a binary feature. To start, manually enter the entri...
qbeenslee/Nepenthes-Server
config/param.py
Python
gpl-3.0
728
0.002747
# coding:utf-8 ''' Author : qbeenslee Created : 15/4/3 ''' UID = 'uid' TOKEN = 'token' CLIENT = 'cl
ient' DESCRIPTION = 'description' EMAIL = 'email' WHAT = 'what' IMEI = 'imei' USERNAME = 'nickname' PWD = 'pwd' IMAGE_FILES = 'imagefiles' MSG = 'msg' VERSION = 'version' URL = 'url' NICKNAME = 'nickname' MOTTO = 'motto' AVATAR = 'avatar' WALLPAPER = 'wallpaper' VERIFY_STATUS = 'verify_status' LATITUDE = 'latitude' LON...
ZE = 'page_size' TOTAL_COUNT = 'total_count' SORT_TYPE = 'sort_type' CONTENT = 'content' SID = 'sid' HEIGHT = "height" WIDTH = "width" OPERATE='operate'
berkmancenter/mediacloud
apps/extract-article-from-page/bin/extract_article_from_page_http_server.py
Python
agpl-3.0
5,416
0.000554
#!/usr/bin/env python3 """ Single-threaded HTTP server that extracts article's HTML from a full page HTML. Accepts POST requests to "/extract" endpoint with body JSON: { "html": "<html><title>Title</title><body><p>Paragraph.</p></html>" } On success, returns HTTP 200 and extracted HTML: { ...
e: { "error": "You're using it wrong." } """ import argparse
from http import HTTPStatus from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import urlparse from mediawords.util.parse_json import encode_json, decode_json from mediawords.util.log import create_logger from extract_article_from_page import extract_article_from_page, extractor_name log = c...
jarpy/lambkin
lambkin/version.py
Python
apache-2.0
18
0
VER
SION = '0.3
.4'
charukiewicz/beer-manager
venv/lib/python3.4/site-packages/passlib/ext/django/models.py
Python
mit
12,558
0.002787
"""passlib.ext.django.models -- monkeypatch django hashing framework""" #============================================================================= # imports #============================================================================= # core import logging; log = logging.getLogger(__name__) from warnings import wa...
check_password() with our own implementation # @_manager.monkeypatc
h(HASHERS_PATH, enable=has_hashers) @_manager.monkeypatch(MODELS_PATH) def check_password(password, encoded, setter=None, preferred="default"): "passlib replacement for check_password()" # XXX: this currently ignores "preferred" keyword, since it's purpose # was for hash migration, ...
jrg365/gpytorch
gpytorch/variational/batch_decoupled_variational_strategy.py
Python
mit
11,612
0.004134
#!/usr/bin/env python3 import torch from torch.distributions.kl import kl_divergence from ..distributions import Delta, MultivariateNormal from ..lazy import MatmulLazyTensor, SumLazyTensor from ..utils.errors import CachingError from ..utils.memoize import pop_from_cache_ignore_args from .delta_variational_distribut...
raise ValueError(f"mean_var_batch_dim should be negative indexed, got {mean_var_batch_dim}") self.mean_var_batch_dim = mean_var_batch_dim # Maybe unsqueeze inducing points if inducing_points.dim() == 1: inducing_points = inducing_points.unsqueeze(-1) # We're going to...
ean_var_batch_dim is not None: inducing_points = torch.stack([inducing_points, inducing_points], dim=(self.mean_var_batch_dim - 2)) else: inducing_points = torch.stack([inducing_points, inducing_points], dim=-3) super().__init__(model, inducing_points, variational_distribution, l...
knadir/Flask-Images
tests/test_template_use.py
Python
bsd-3-clause
780
0
from . import * class TestTemplateUse(TestCase): def test_resized_img_src(self): @self.app.route('/resized_img_src
') def use(): return render_template_string(''' <img src="{{ resized_img_src('cc.png') }}" /> '''.strip()) res = self.client.get('/resized_img_src') self.assert200(res) self.a
ssertIn('src="/imgsizer/cc.png?', res.data) def test_url_for(self): @self.app.route('/url_for') def use(): return render_template_string(''' <img src="{{ url_for('images', filename='cc.png') }}" /> '''.strip()) res = self.client.get('/url_for') ...
efce/voltPy
manager/operations/methods/MedianFilter.py
Python
gpl-3.0
1,485
0.00202
import numpy as np from scipy.signal import medfilt import manager.operations.method as method from manager.operations.methodsteps.confirmation import Confirmation from manager.exceptions import VoltPyNotAllowed class
MedianFilter(method.ProcessingMethod): can_be_applied = True _ste
ps = [ { 'class': Confirmation, 'title': 'Apply median filter', 'desc': 'Press Forward to apply Median Filter.', }, ] description = """ Median filter is smoothing algorithm similar to the Savitzky-Golay, however instead of fitting of the polynomial, th...
mc706/django-angular-scaffold
angular_scaffold/_docs.py
Python
mit
4,321
0.00648
docs = """django-angular-scaffold ======================= [![Build Status](https://travis-ci.org/mc706/django-angular-scaffold.svg?branch=master)](https://travis-ci.org/mc706/django-angular-scaffold) [![PyPI version](https://badge.fury.io/py/django-angular-scaffold.svg)](http://badge.fury.io/
py/django-angular-scaffold) [![Code Health](https://landscape.io/github/mc706/django-angular-scaffold/master/landscape.svg)](https://landscape.io/github/mc706/django-angular-scaffold/master) [![Coverage Status](https://img.shields.io/coveralls/mc706/django-angular-scaffold.svg)](https://coveralls.io/r/mc706/django-angu...
`` include in your INSTALLED_APPS ``` #settings.py ... INSTALLED_APPS = ( ... 'angular_scaffold', ... ) ``` ##Commands The following are commands that are made available through this package. ###scaffold ``` ./manage.py scaffold ``` Builds a assets folder structure in the following structure: ``` /a...
LuckehPickle/Comet
docs/categories.py
Python
apache-2.0
2,173
0.02347
""" Copyright (c) 2016 - Sean Bailey - 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 agree...
db_code = "DE", ) COMMUNITY = Category( title = "Community", description = "For the community, by the community.", url = "community", colour = "#F49336", db_co
de = "CO", ) OTHER = Category( title = "Other", description = "Miscellaneous articles.", url = "other", colour = "#F4A336", db_code = "OT", ) CATEGORIES = [NEWS, SUPPORT, DEVELOPER, COMMUNITY, OTHER]
jromang/retina-old
distinclude/spyderlib/widgets/sourcecode/terminal.py
Python
gpl-3.0
4,314
0.007651
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """Terminal emulation tools""" import os class ANSIEscapeCodeHandler(object): """ANSI Escape sequences handler""" if os.name == 'nt': #...
, # 2: green ('#CDCD00', '#ffff00'), # 3: yellow ('#0000EE', '#5C5CFF'), # 4: blue ('#CD00CD', '#ff00ff'), # 5: magenta ('#00CDCD', '#00ffff'), # 6: cyan ('#E5E5E5', '#ffffff'), # 7: w
hite ) def __init__(self): self.intensity = 0 self.italic = None self.bold = None self.underline = None self.foreground_color = None self.background_color = None self.default_foreground_color = 30 self.default_backgroun...
beeftornado/sentry
src/sentry/grouping/strategies/base.py
Python
bsd-3-clause
10,151
0.001084
from __future__ import absolute_import import six import inspect from sentry import projectoptions from sentry.grouping.component import GroupingComponent from sentry.grouping.enhancer import Enhancements STRATEGIES = {} RISK_LEVEL_LOW = 0 RISK_LEVEL_MEDIUM = 1 RISK_LEVEL_HIGH = 2 def strategy(id=None, ids=None...
self.variants =
[] for variant in variants: if variant[:1] == "!": self.mandatory_variants.append(variant[1:]) else: self.optional_variants.append(variant) self.variants.append(variant) self.score = score self.func = func self.variant_p...
nosix/PyCraft
src/pycraft/network/__init__.py
Python
lgpl-3.0
433
0.002309
# -*- coding: utf8 -*- from .interface import Reliability, Session, Handler from .logger import LogName from .server import Server from .protocol import Protocol, packet_classes from .packet import ApplicationPacket from .portscanner import PortScanner __all__ = [
'Rel
iability', 'Session', 'Handler', 'LogName', 'Server', 'Protocol', 'ApplicationPacket', 'PortScanner', 'packet_classes', ]
vrenkens/nabu
nabu/neuralnetworks/trainers/standard_trainer.py
Python
mit
844
0.001185
'''@file standard_trainer.py contains the StandardTrainer''' from nabu.neuralnetworks.trainers import
trainer class
StandardTrainer(trainer.Trainer): '''a trainer with no added functionality''' def aditional_loss(self): ''' add an aditional loss returns: the aditional loss or None ''' return None def chief_only_hooks(self, outputs): '''add hooks only for the...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/reportlab/lib/normalDate.py
Python
gpl-3.0
20,867
0.005367
#!/usr/bin/env python # normalDate.py - version 1.0 - 20000717 #hacked by Robin Becker 10/Apr/2001 #major changes include # using Types instead of type(0) etc # BusinessDate class # __radd__, __rsub__ methods # formatMS stuff # derived from an original version created # by Jeff Bauer of Rubicon Research and us...
initialize a NormalDate: 1. None - creates a NormalDate for the current day 2. integer in yyyymm
dd format 3. string in yyyymmdd format 4. tuple in (yyyy, mm, dd) - localtime/gmtime can also be used """ if normalDate is None: self.setNormalDate(time.localtime(time.time())) else: self.setNormalDate(normalDate) def add(self, days): ...
beaker-project/beaker
Common/bkr/common/__init__.py
Python
gpl-2.0
225
0
# Since bkr is a namespace package (and thus cannot have version specific # code in bkr.__init__), the version details are retrieved from here in # order to co
rrectly handle module shadowing on sys.path __version__ = '28.2'
schesis/fix
tests/decorators/test_with_fixture.py
Python
gpl-3.0
3,536
0
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): ...
text.temp_dir = temp
file.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """De...
silveregg/moto
moto/route53/urls.py
Python
apache-2.0
565
0.00177
from __future__ import unicode_literals from . import responses url_bases = [ "https://route5
3.amazonaws.com/201.-..-../", ] url_paths = { '{0}hostedzone$': responses.list_or_create_hostzone_response, '{0}hostedzone/[^/]+$': responses.get_or_delete_hostzone_response
, '{0}hostedzone/[^/]+/rrset/?$': responses.rrset_response, '{0}healthcheck': responses.health_check_response, '{0}tags/(healthcheck|hostedzone)/*': responses.list_or_change_tags_for_resource_request, '{0}trafficpolicyinstances/*': responses.not_implemented_response }
ccxt/ccxt
python/ccxt/bitget.py
Python
mit
117,797
0.003466
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors import Authenticati...
}, 'www': 'https://www.bitget.com',
'doc': [ 'https://bitgetlimited.github.io/apidoc/en/swap', 'https://bitgetlimited.github.io/apidoc/en/spot', ], 'fees': 'https://www.bitget.cc/zh-CN/rate?tab=1', 'test': { 'rest': 'https://testnet.bitget....
JulienDrecq/django-odoo-auth
odoo_auth/models.py
Python
bsd-3-clause
246
0
from django.db import models from django.contrib.auth.m
odels import User class OdooUser(models.Model): user = models.OneToOneField(User) odoo_id = models.BigIntegerField(primary_key=True)
username = models.CharField(max_length=256)
chubin/cheat.sh
lib/buttons.py
Python
mit
1,461
0.004791
TWITTER_BUTTON = """ <a href="https://twitter.com/igor_chubin" class="twitter-follow-button" data-show-count="false" data-button="grey">Follow @igor_chubin</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js....
button">cheat.sh</a> """ GITHUB_BUTTON_2 = """ <!-- Place this tag where you want the button to render. --> <a aria-label="Star chubin/cheat.sheets on GitHub" data-count-aria-label="# stargazers on GitHub" data-count-api="/repos/chubin/cheat.sheets#stargazers_count" data-count-href="/chubin/c
heat.sheets/stargazers" data-icon="octicon-star" href="https://github.com/chubin/cheat.sheets" class="github-button">cheat.sheets</a> """ GITHUB_BUTTON_FOOTER = """ <!-- Place this tag right after the last button or just before your close body tag. --> <script async defer id="github-bjs" src="https://buttons.github.io...
gnovak/overheard
overheard/test.py
Python
mit
12,458
0.004816
######### # Notes # ######### # # Run all tests from command line # python test.py # python -m test # # Run subset of tests from command line # python -m unittest ArchivTest # python -m unittest ArchivTest.test_old_arxiv_id # # Run all tests non-interactive
ly from REPL # import test; test.test() # # Run specific test interactively from REPL # test.ArchivTest('test_old_arxiv_id').debug() # from __future__ import with_statement import unitt
est, re, tempfile, os if not hasattr(unittest, 'skipIf'): try: import unittest2 as unittest except ImportError: raise NotImplementedError, \ """Tests require either the Python 2.7 or later version of the unittest module or the unittest2 module.""" import arxiv_...
andreoliw/clitoolkit
clit/git.py
Python
bsd-3-clause
899
0
# -*- coding: utf-8 -*- """Git tools.""" from shlex import split from plumbum import Pr
ocessExecutionError from plumbum.cmd import git DEVELOPMENT_BRANCH = "develop" def run_git(*args, dry_run=False, quiet=False): """Run a git command, print it before executing and capture the output.""" command = git[split(" ".join(args))] if not q
uiet: print("{}{}".format("[DRY-RUN] " if dry_run else "", command)) if dry_run: return "" rv = command() if not quiet and rv: print(rv) return rv def branch_exists(branch): """Return True if the branch exists.""" try: run_git("rev-parse --verify {}".format(bran...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractDevastatranslationsWordpressCom.py
Python
bsd-3-clause
578
0.032872
def extractDevastatranslatio
nsWordpressCom(item): ''' Parser for 'devastatranslations.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'L...
ame, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
pblottiere/QGIS
tests/src/python/test_qgstextblock.py
Python
gpl-2.0
2,937
0
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsTextBlock. Run with: ctest -V -R QgsTextBlock .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your...
Fragment('b') block.append(frag) self.assertEqual
(len(block), 2) self.assertEqual(block[0].text(), 'a') self.assertEqual(block[1].text(), 'b') self.assertEqual(block.toPlainText(), 'ab') def testAt(self): block = QgsTextBlock() block.append(QgsTextFragment('a')) block.append(QgsTextFragment('b')) self.asse...
ohaut/ohaut-core
ohaut/exceptions.py
Python
gpl-3.0
46
0
class InvalidDeviceType(E
xception): pas
s
willingc/portal
systers_portal/common/tests/test_templatetags.py
Python
gpl-2.0
328
0
from
django.test import TestCase from common.templatetags.verbose_name import verbose_name from users.models import SystersUser class TemplateTagsTestCase(TestCase): def test_verbose_names(self): """Test verbose_name template tag""" self.assertEqual(verbose_name(SystersUser, "homepage_url"), "Homepag...
")
pekrau/userman
userman/dump.py
Python
mit
3,017
0.000994
" Userman: Dump the database into a JSON file." import json import tarfile from cStringIO import StringIO from userman import utils from userman import constants def dump(db, filename): """Dump contents of the database to a tar file, optionally compressed. Return the number of items, and the number of attac...
for attname in doc.get('_attachments', dict()): info = tarfile.TarInfo("{0}_att/{1}".format(doc['_id'], attname)) attfile = db.get_attachment(doc, attname) data = attfile.read() attfile.close() info.size = len(data)
outfile.addfile(info, StringIO(data)) count_files += 1 outfile.close() return count_items, count_files def undump(db, filename): """Reverse of dump; load all items from a tar file. Items are just added to the database, ignoring existing items.""" count_items = 0 count_f...
googleinterns/e2e-convrec
trainer/preprocessing.py
Python
apache-2.0
5,116
0.007428
# 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, sof...
GFile(out_fname, "w") as outfile: for line in infile: ex = json.loads(line) conversation = fix_spacing(ex["conversation"]) response = fix_spacing(ex["response"]) # Write this line as <conversation>\t<response> outfile.w
rite("%s\t%s\n" % (conversation, response)) count += 1 tf.logging.log_every_n( tf.logging.INFO, "Wrote %d examples to %s." % (count, out_fname), 1000) return count def generic_dataset_fn(split, path, reverse=False, shuffle_files=False): """Returns a tf dataset of (conve...
modoboa/modoboa-amavis
modoboa_amavis/modo_extension.py
Python
mit
1,395
0
# -*- coding: utf-8 -*- """ Amavis management frontend. Provides: * SQL quarantine management * Per-domain settings """ from __future__ import unicode_literals from django.utils.translation import ugettext_lazy from modoboa.admin.models import Domain from modoboa.core.extensions import ModoExtension, exts_pool f...
s") param_tools.registry.add( "user", forms.UserSettings, ugettext_lazy("Quarantine")) def load_initial_data(self): """Create records for existing domains and co
.""" for dom in Domain.objects.all(): policy = create_user_and_policy("@{0}".format(dom.name)) for domalias in dom.domainalias_set.all(): domalias_pattern = "@{0}".format(domalias.name) create_user_and_use_policy(domalias_pattern, policy) exts_pool.regis...
mcxiaoke/python-labs
scripts/wechat_upload.py
Python
apache-2.0
8,692
0.00115
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-26 from __future__ import print_function, unicode_literals, absolute_import import json import sys import os import re import time import shutil import random import mimetypes import imghdr import traceback import json import redis im...
oding = 'utf-8' return response.json()['media_id'] except RequestException as e: logger.error('upload_image error=%s' % e) def upload_images(self, source_dir, type_name='', max_count=100): if not source_dir or not os.path.isdir(source_dir): return logger....
unt: names = random.sample(names, max_count) count = 0 mids = [] for name in names: filepath = os.path.join(source_dir, name) filepath = os.path.abspath(filepath) mime_type, _ = mimetypes.guess_type(name) if mime_type not in ['image/jpe...
mookrs/fanpy
tests/test_sanity.py
Python
mit
1,473
0.000679
# -*- coding: utf-8 -*- from __future__ import unicode_literals import random import pickle import json from fanpy import Fanfou, FanfouHTTPError, NoAuth from fanpy.api import FanfouDictRespo
nse, FanfouListResponse, POST_ACTIONS, method_for_uri noauth = NoAuth() fan
fou_na = Fanfou(auth=noauth) AZaz = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ' def get_random_str(): return ''.join(random.choice(AZaz) for _ in range(10)) def test_FanfouHTTPError_raised_for_invalid_oauth(): test_passed = False try: fanfou_na.statuses.mentions() excep...
particl/particl-core
test/functional/feature_part_smsgpaidfee_ext.py
Python
mit
4,260
0.003286
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Particl Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_particl import ( ParticlTestFramework, isclose, ) from test_framework.me...
es[0].getnewaddress() address1 = nodes[1].getnewaddress() nodes[0].smsgaddlocaladdress(address0) nodes[1].smsgaddaddress(address0, nodes[0].smsglocalkeys()['wallet_keys'][0]['public_key']) text = 'Some text to test' ro = nodes[1].smsgsend(address1, address0, text, True, 10, True...
assert(ro['result'] == 'Not Sent.') assert(isclose(ro['fee'], 0.00159000)) assert(nodes[0].smsggetfeerate() == 50000) assert(nodes[1].smsggetfeerate() == 50000) ro = nodes[0].walletsettings('stakingoptions', {'smsgfeeratetarget' : 0.001}) assert(float(ro['stakingoptions...
benob/chainer
chainer/functions/array/transpose_sequence.py
Python
mit
1,673
0.000598
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check def _transpose(xs, length): xp = cuda.get_array_module(*xs) lengths = numpy.zeros(length, dtype='i') for i, x in enumerate(xs): lengths[0:len(x)] = i + 1 dtype = xs[0].dtype unit = xs[0...
return _transpose(gs, len(xs)) def transpose_sequence(xs): """Transpose a list of Variables. This function transposes
a list of :class:`~chainer.Variable` s and returns a list of :class:`Variable` s. For exampe a user gives ``[(0, 1, 2, 3), (4, 5), (6)]``, the function returns ``[(0, 4, 6), (1, 5), (2), (3)]``. Note that a given list needs to be sorted by each length of :class:`~chainer.Variable`. Args: ...
hubblestack/hubble-salt
hubblestack_nova/win_pkg.py
Python
apache-2.0
8,165
0.003062
# -*- encoding: utf-8 -*- ''' :maintainer: HubbleStack :maturity: 2016.7.0 :platform: Windows :requires: SaltStack ''' from __future__ import absolute_import import copy import fnmatch import logging import salt.utils import salt.utils.platform from salt.exceptions import CommandExecutionError from distutils.version...
# each test case is a dictionary with just one key-val pair. key=test name, val=test data, description etc if isinstance(test_case, dict) and test_case: test_case_body = test_case.get(next(iter(test_case))) if set(labels).issubset(set(test_case...
ses.append(test_case) labelled_data[__virtualname__][topkey]=labelled_test_cases else: labelled_data = __data__ return labelled_data def audit(data_list, tags, labels, debug=False, **kwargs): ''' Runs auditpol on the local machine and audits the return data with the CIS yaml...