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
palankai/xadrpy
src/ckeditor/urls.py
Python
lgpl-3.0
229
0
f
rom django.conf.urls.defaults impor
t patterns, url urlpatterns = patterns( '', url(r'^upload/', 'ckeditor.views.upload', name='ckeditor_upload'), url(r'^browse/', 'ckeditor.views.browse', name='ckeditor_browse'), )
Puyb/inscriptions_roller
inscriptions/consumers.py
Python
gpl-3.0
1,896
0.003692
import logging import json import re import smtplib from channels.consumer import SyncConsumer from django.conf import settings from django.contrib.sites.models import Site from django.core.mail import EmailMessage from django.urls import reverse from .models import Mail logger = lo
gging.getLogger(__name__) class MailConsumer(SyncConsumer): def send_mail(self, message): try: logger.info('sending mail %s', message) message.pop('type') name = message.pop('n
ame', 'Enduroller') content_type = message.pop('content_type', 'html') message_id = message.pop('message_id') #to = json.loads(message.pop('to')) body = message.pop('body') if content_type == 'html': body = re.sub( r'(https?...
pengzhangdev/slackbot
slackbot/plugins/ibotcloud.py
Python
mit
6,471
0.001545
import datetime import hashlib import copy import httplib, urllib, urlparse import collections __author__ = '[email protected]' class AskParams: def __init__(self, platform="", user_id="", url="", response_format="json"): self.platform = platform self.user_id = user_id self.url = url ...
nonce = hashlib.sha1(time_str).hexdigest() HA1 = "{0}:{1}:{2}".format(self.app_key, self.realm, self.app_sec) HA1 = hashlib.sha1(HA1).hexdigest() HA2 = "{0}:{1}".format(self.http_method, self.uri) HA2 = hashlib.sha1(HA2).hexdigest() signature = "{0}:{1}:{2}".format(HA...
t_signature_reture", "signature nonce") ret.signature = signature ret.nonce = nonce return ret def get_http_header_xauth(self): ret_vals = self.get_signature() ret = {'X-Auth': "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format(self.app_key, ...
TeamEOS/external_chromium_org
tools/perf/measurements/no_op.py
Python
bsd-3-clause
373
0.008043
# Copyright
2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page_measurement class NoOp(page_measurement.PageMeasurement): def __init__(self): super(NoOp, self).__init__('RunNoOp') def Measur...
: pass
keras-team/keras
keras/engine/compile_utils_test.py
Python
apache-2.0
31,261
0.002399
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
sertEqual(output_2_metric.name, 'output_2_loss') self.assertEqual(output_2_metric.result().numpy(), 0.5) def test_missing_label_with_no_loss(self): # It's ok to exclude a
label if that label has no # losses or metrics associated with it. loss_container = compile_utils.LossesContainer({ 'output1': 'mse', 'output3': 'mae' }) y_p = { 'output1': tf.convert_to_tensor([[0], [1], [2]]), 'ou
screepers/screeps-stats
screeps_etl/settings.py
Python
mit
743
0.002692
import os from os.path import expanduser import sys import yaml def getSettings(): if not getSettings.settings: cwd = os.getcwd()
path = cwd + '/.settings.yaml' if not os.path.isfile(path): path = cwd + '/.screeps_settings.yaml' if not os.path.isfile(path): path = expanduser('~') + '/.screeps_settings.yaml' if not os.path.isfile(path): path = '/vagran
t/.screeps_settings.yaml' if not os.path.isfile(path): print 'no settings file found' sys.exit(-1) return False with open(path, 'r') as f: getSettings.settings = yaml.load(f) return getSettings.settings getSettings.settings = False
matikbird/matikbird.github.io
portfolio/quay/back_end/payments2/mercadopago/api-mercadopago-master/templates/code-examples-master/mp-checkout/shipping/python/ipn_merchant_order.py
Python
mit
824
0.009709
# coding: UTF-8 import os, sys import mercadopago def index(req, **kwargs): mp = mercadopago.MP("CLIENT_ID", "CLIENT_SECRET") topic = kwargs["topic"] merchant_order_info = None if topic == "payment" payment_info = mp.get("/collections/notifications/"+kwargs["id"]) merchant_order_info ...
ders/"+payment_info["response"]["collection"]["merchant_order_id"]) elif topic == "merchant_order" merchant_order_info = mp.get("/merchant_orders/"+kwargs["id"]) if merchant_order_info == None raise ValueError("Error obtaining the merchant_order") if merchant_order_info["status"] == 200 ...
"shipment": merchant_order_info["response"]["shipments"] }
harshilasu/LinkurApp
y/google-cloud-sdk/lib/googlecloudapis/apitools/base/py/cli.py
Python
gpl-3.0
432
0
"""Top-level import for all CLI-related functionality in apitools. Note that i
mporting this file will ultimately have side-effects, and may require imports not available in all environments (such as App Engine). In particular, picking up some readline-related imports can cause pain. """ # pylint:disable=wildcard-import from googlecloudapis.apitools.base.py.app2 import * from
googlecloudapis.apitools.base.py.base_cli import *
jesuscript/topo-mpi
topo/analysis/vision.py
Python
bsd-3-clause
11,628
0.020296
""" Vision-specific analysis functions. $Id: featureresponses.py 7714 2008-01-24 16:42:21Z antolikjan $ """ __version__='$Revision: 7714 $' from math import fmod,floor,pi,sin,cos,sqrt import numpy from numpy.oldnumeric import Float from numpy import zeros, array, size, empty, object_ #import scipy try: import p...
tay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360 if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360
f = pylab.figure() ax = f.add_subplot(111, aspect='equal') pylab.plot(datax,datay,'ro') pylab.plot([0,360],[-180,180]) pylab.plot([-180,180],[0,360]) pylab.plot([-180,-180],[360,360]) ax.axis([-180,360,-180,360]) pylab.xticks([-180,0,180,360], [-180,0,180,360]) pylab.yticks([-180...
pari685/AStream
dist/client/dash_client.py
Python
mit
23,767
0.00446
#!/usr/local/bin/python """ Author: Parikshit Juluri Contact: [email protected] Testing: import dash_client mpd_file = <MPD_FILE> dash_client.playback_duration(mpd_file, 'http://198.248.242.16:8005/') From commandline: python dash_client.py -m "http://198.248.242.16:8006/media/m...
nload MPD file HTTP Error: %s" % error.code) return None except urllib2.URLError: error_message = "URLError. Unable to reach Server.Check if Server active" config_dash.LOG.error(error_message) print error_message return None except IOError, httplib.HTTPException:
message = "Unable to , file_identifierdownload MPD file HTTP Error." config_dash.LOG.error(message) return None mpd_data = connection.read() connection.close() mpd_file = url.split('/')[-1] mpd_file_handle = open(mpd_file, 'w') mpd_file_handle.write(mpd_data) mpd_file_handl...
qspin/qtaste
doc/src/docbkx/scripts/config.py
Python
lgpl-3.0
281
0.003559
AppName = "Qtaste" GitHubRepositoryUrl = "qspin/q
taste" ReleaseNotesTemplate = "./qtaste_release_notes_template.xml" ReleaseNotesOutputFile = "../qtaste_release_notes.xml" # Version Info (generated by ma
ven) VersionFile = "../../../../Version.txt" VersionTag = "qtaste-version"
hoelsner/product-database
app/productdb/migrations/0025_auto_20170109_2017.py
Python
mit
579
0.001727
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-01-09 19:17 from __future__ import unicode_li
terals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('productdb', '0024_auto_20161227_1015'), ] operations = [ migrations.AlterFie
ld( model_name='productcheck', name='input_product_ids', field=models.CharField(help_text='unordered Product IDs, separated by line breaks or semicolon', max_length=65536, verbose_name='Product ID list'), ), ]
daanwierstra/pybrain
pybrain/rl/environments/serverInterface.py
Python
bsd-3-clause
1,099
0.009099
__author__ = 'Frank Sehnke, [email protected]' from environment import Environment class GraphicalEnvironment(Environment): """ Special type of environment that has graphical output and therefore needs a renderer. """ def __init__(self): self.
renderInterface = None def setRenderInterface(self, renderer): """ set the renderer, which is an object of or inherited from class Renderer. @param renderer: The renderer that should display the Environment @type renderer: L{Renderer} @see Renderer """ ...
@rtype: L{Renderer} """ return self.renderInterface def hasRenderInterface(self): """ tells you, if a Renderer has been set previously or not @return: True if a renderer was set, False otherwise @rtype: Boolean """ return (self.getRenderInt...
allan-simon/tatoSSO
tools/config.py
Python
mit
1,959
0.015314
# where the application code will be generated # relative to the "tools" directory APP_ROOT = "../app" # this represent the logical structure of your code # the script init will use this to generate a skeleton # of code ARCHITECTURE = { 'controllers' : { 'Users' : {
'description': 'module to centralize user related actions', 'methods' : { 'show_all': {} }, 'forms' : { 'register_new' : {}, 'login' : {} }, 'actions_only' : { 'logout': {}, ...
'description': 'module to centralize action related to token grated to user on services', 'methods' : { 'check_token': {} }, 'forms': { 'external_login' : {} }, 'actions_only' : { 'kick_user': {} ...
VirusTotal/content
Packs/MajorBreachesInvestigationandResponse/Scripts/RapidBreachResponseEradicationTasksCountWidget/RapidBreachResponseEradicationTasksCountWidget.py
Python
mit
978
0.003067
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 ORANGE_HTML_STYLE = "'color:#EF9700;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>" GREEN_HTML_STYLE = "'color:#1DB846;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>" GREY_
HTML_STYLE = "'color:#404142;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>" def main(): incident = demisto.incidents() query = incident[0].get('CustomFields', {}).get('eradicationtaskcount', 0) if not query: html = f"<div style={GREY_HTML_STYLE}{0}</div>" elif int(query...
}{str(query)}</div>" else: html = f"<div style={GREEN_HTML_STYLE}{str(query)}</div>" demisto.results({ 'ContentsFormat': formats['html'], 'Type': entryTypes['note'], 'Contents': html }) if __name__ in ["__main__", "builtin", "builtins"]: main()
jmesteve/saas3
openerp/addons/base/ir/__init__.py
Python
agpl-3.0
1,426
0.000701
# -*- coding: utf-8 -*- #######################################################################
####### # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This p
rogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be u...
tmaiwald/OSIM
OSIM/Modeling/Testbenches/DepletionCharge_TB.py
Python
bsd-2-clause
1,541
0.038287
import numpy as np from OSIM.Modeling.Components.NPN_Vertical_Bipolar_Intercompany_Model.VBIC_Charges.VBIC_DepletionCharge import VBIC_DepletionCharge from OSIM.Modeling.Components.Resistor import Resistor from OSIM.Modeling.Components.VoltageSource import VoltageSource from OSIM.Modeling.Components.Capacity import Cap...
n = '1' sigout = '2' ik = '3' vsource = VoltageSource([gnd,sigin],"V1",0,None,paramdict={'FUNC':'SIN','F':'1e11', 'DC':'0', 'AC':'1', 'P':'180'}) r1 = Resistor([sigin,sigout],"R1",0.00001,None) c = VBIC_DepletionCharge([sigout, ik],"QJ", CJx, None, paramdict= {'P':P,'M':M,'F':F,'AJ':AJ,'FAK':WBx}) cref = Capacity([sig...
ons([vsource,r1,c,r2,cref]) ca = CircuitAnalyser(TBSys) volts = [x/100 for x in range(-200,200)] res = np.zeros((2,len(volts)),dtype= np.float64) #for vidx,v in enumerate(volts): # vsource.changeMyVoltageInSys(v) # ca.calcDCOperatingPoint() # res[0][vidx] = v # res[1][vidx] = c.getCharge() #ca.plot_lin([...
fcwu/desktop-mirror
lib/common.py
Python
apache-2.0
123
0
#!/usr/bin/env python # -*- coding: utf-8 -*- APPNA
ME = 'desktop-mirror' DEF
AULT_PORT = 47767 VERSION = 'v0.8-7-g2038d52'
GhostshipSoftware/avaloria
contrib/menu_login.py
Python
bsd-3-clause
13,491
0.002224
""" Menu-driven login system Contribution - Griatch 2011 This is an alternative login system for Evennia, using the contrib.menusystem module. As opposed to the default syste
m it doesn't use emails for authentication and also don't auto-creates a Character with the same name as the Player (ins
tead assuming some sort of character-creation to come next). Install is simple: To your settings file, add/edit the line: CMDSET_UNLOGGEDIN = "contrib.menu_login.UnloggedInCmdSet" That's it. Reload the server and try to log in to see it. The initial login "graphic" is taken from strings in the module given by set...
onyb/mooca
Udacity/UD032_Data_Wrangling_with_MongoDB/Lesson_4/23-Using_$in_Operator/find_cars.py
Python
mit
1,151
0.008688
#!/usr/bin/env python """ Your task is to write a query that will return all cars manufactured by "Ford Motor Company" that are assembled in Germany, United Kingdom, or Japan. Please modify only 'in_query' function, as only that will be taken into account. Your code will be run against a MongoDB instance that we have ...
: from pymongo import MongoClient client = MongoClient('localhost:27017') db = client.examples return db def in_query(): # Write the query query = { "manufacturer" : "Ford Motor Company", "assembly": {"$in": ["Germany", "United Kingdom", "Japan"]} } ...
:0}) print "Found autos:", autos.count() import pprint for a in autos: pprint.pprint(a)
loafbaker/django_ecommerce2
orders/migrations/0002_useraddress.py
Python
mit
1,035
0.002899
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-29 17:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('orders', '0001_initial'), ] operations = [ ...
erAddress', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(choices=[('billing',
'Billing'), ('shipping', 'Shipping')], max_length=120)), ('street', models.CharField(max_length=120)), ('city', models.CharField(max_length=120)), ('state', models.CharField(max_length=120)), ('zipcode', models.CharField(max_length=120)), (...
makerbot/conveyor
src/test/python/client.py
Python
agpl-3.0
1,877
0.001599
# vim:ai:et:ff=unix:fileencoding=utf-8:sw=4:ts=4: # conveyor/src/test/python/client.py # # conveyor - Printing dispatch engine for 3D objects and their friends. # Copyright © 2012 Matthew W. Samsonoff <[email protected]
om> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License
as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the G...
echanna/EdxNotAFork
lms/lib/comment_client/comment.py
Python
agpl-3.0
3,282
0.002133
from .utils import CommentClientRequestError, perform_request from .thread import Thread, _url_for_flag_abuse_thread, _url_for_unflag_abuse_thread import models import settings class Comment(models.Model): accessible_fields = [ 'id', 'body', 'anonymous', 'anonymous_to_peers', 'course_id', 'endor...
, comment_id=c
omment_id)
ywcui1990/nupic
src/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin.py
Python
agpl-3.0
14,320
0.007402
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
f._mmTraces["predictiveCells"] def mmGetTraceNumSegments(self): """ @return (Trace) Trace of # segments """ return self._mmTraces["numSegments"] def mmGetTraceNumSynapses(self): """ @return (Trace) Trace of # synapses """ return self._mmTraces["numSynapses"] def mmGetTraceSeq...
def mmGetTraceResets(self): """ @return (Trace) Trace of resets """ return self._mmTraces["resets"] def mmGetTracePredictedActiveCells(self): """ @return (Trace) Trace of predicted => active cells """ self._mmComputeTransitionTraces() return self._mmTraces["predictedActiveCell...
nwaxiomatic/django-wpadmin
wpadmin/menu/utils.py
Python
mit
4,176
0.000718
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name (...
m if fnmatch(full_name(model), pattern) and item not in included: included.append(item) result = included[:] for pattern in exclude: for item in included: model, perms = item if fnmatch(full_name(model), pattern): try: ...
pass return result class UserTestElementMixin(object): """ Mixin which adds a method for checking if current user is allowed to see something (menu, menu item, etc.). """ def is_user_allowed(self, user): """ This method can be overwritten to check if current user ...
xshotD/lolbot
cogs/eval.py
Python
mit
4,708
0.003823
"""The following code is (c) sliceofcode 2017.""" """Source: https://github.com/sliceofcode/dogbot/blob/master/dog/core/ext/exec.py """ """ Handy exec (eval, debug) cog. Allows you to run code on the bot during runtime. This cog is a combination of the exec commands of other bot authors: Credit: - Rapptz (Danny) ...
urn await ctx.send(format_syntax_error(e)) func = env['func'] try: with redirect_s
tdout(stdout): ret = await func() except Exception as e: # something went wrong stream = stdout.getvalue() await ctx.send('```py\n{}{}\n```'.format(stream, traceback.format_exc())) else: # successful stream = stdout.getvalue() ...
kartikshah1/Test
courseware/permissions.py
Python
mit
7,593
0.000922
""" Handles permissions of the courseware API Permission Classes: IsInstructorOrReadOnly - safe methods allowed for all users. other only for instructor IsContentDeveloper - Checks whether he is a ContentDeveloper IsRegistered - Checks whether the student is enrolled in the course """ from r...
if customuser.is_instructor: return True return False # return true if he is the owner of the course try: CourseHistory.objects.get( course=obj, user=request.user, is_owner=T
rue ) except: return False return True return False class IsOwner(permissions.BasePermission): """ Allows complete permission to the owner and none to others """ def has_permission(self, request, view): if request.user.is_authenti...
tensorflow/ranking
tensorflow_ranking/python/feature.py
Python
apache-2.0
10,055
0.004774
# Copyright 2021 The TensorFlow Ranking Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
context feature names to dense 2-D tensors of shape [batch_size, ...]. example_features: (dict) A mapping from ex
ample feature names to dense 3-D tensors of shape [batch_size, input_size, ...]. Raises: ValueError: If `input size` is not equal to 2nd dimension of example tensors. """ context_features = {} if context_feature_columns: context_cols_to_tensors = encode_features( features, context_featu...
evelynmitchell/pdq
examples/Linux Magazine/spamcan1.py
Python
mit
1,994
0.004012
#!/usr/bin/env python ############################################################################### # Copyright (C) 1994 - 2013, Performance Dynamics Company # # # # This software is licensed as described in the file COPY...
# # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # # KIND, either express or implied. # ############################################################################### # $Id: spamcan1.py,v 1.3 2012/11/13 03:12:04 earl-lang Exp $ # Creat...
Wed, Apr 18, 2007 # # Queueing model of an email-spam analyzer system comprising a # battery of SMP servers essentially running in batch mode. # Each node was a 4-way SMP server. # The performance metric of interest was the mean queue length. # # This simple M/M/4 model gave results that were in surprisingly # good...
edx/edx-analytics-dashboard
analytics_dashboard/courses/serializers.py
Python
agpl-3.0
531
0.001883
from django.core.serializers.json import DjangoJSONEncoder from django.utils.encoding import force_text from django.utils.f
unctional import Promise class LazyEncoder(DjangoJSONEncoder): """ Force the conversion of lazy translations so that they can be serialized to JSON. via https://docs.djangoproject.com/en/dev/topics/serializatio
n/ """ # pylint: disable=method-hidden def default(self, obj): if isinstance(obj, Promise): return force_text(obj) return super().default(obj)
dbrgn/django-tabination
tabination/tests/multilevel/tests.py
Python
lgpl-3.0
2,204
0.001361
from django.core.exceptions import ImproperlyConfigured from django.test.client import RequestFactory from django.utils import unittest from .views import (ParentTab, EmptyTab, FirstChildTab, SecondChildTab, BrokenChildTab) class MultilevelTest(unittest.TestCase): rf = RequestFactory() def test_parent(self)...
text.""" request = self.rf.get('/') response = ParentTab.as_view()(request) with self.assertRaises(KeyError): res
ponse.context_data['parent_tabs'] def test_parent_not__is_tab(self): """Using a TabView as parent which has not _is_tab = True fails.""" request = self.rf.get('/') with self.assertRaises(ImproperlyConfigured): BrokenChildTab.as_view()(request)
USGSDenverPychron/pychron
pychron/user/tasks/panes.py
Python
apache-2.0
1,974
0
# =============================================================================== # Copyright 2014 Jake Ross # # 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...
ew( HGroup( UItem("filter_attribute"), UItem("filter_str"), show_border=True, label="Filter", ), UItem("users", editor=TableEditor(columns=cols)), ) return v # ============= EOF ========================...
=============
daggaz/python-pyptables
pyptables/base.py
Python
gpl-2.0
806
0.001241
import inspect class DebugObject(object): """Base class f
or most iptables classes. Allows objects to determine the source line they were created from, which is used to insert debugging information into the generated output """ def __init__(self, *args, **kwargs): super(DebugObject, self).__init__(*args, **kwargs) frame = inspect.currentframe()...
ack self.filename, self.lineno, self.function, __, __ = info def debug_info(self): """Returns a string of debug info about the creation of this object""" return "%s:%s %s" % (self.filename, self.lineno, self.function)
sankroh/satchmo
satchmo/feeds/views.py
Python
bsd-3-clause
1,945
0.010797
import datetime from django.contrib.auth.decorators import user_passes_test from django.core import urlresolvers from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response from satchmo.payment.config import credit_choices from satchmo.product.models import Product, Category from ...
ml", mimetype="application/atom+xml"): """Build a feed of all active products. """ shop_config = Config.objects.get_current() if category: try: cat = Category.objects.get(slug=category) products = cat.active_products() except Category.DoesNotExist: ra...
cat = None products = Product.objects.active_by_site() products = filter(lambda product:"ConfigurableProduct" not in product.get_subtypes(), products) params = {} view = 'satchmo_atom_feed' if category: params['category'] = category view = 'satchmo_atom_cate...
igrlas/CentralHub
CHPackage/src/centralhub/server/home_endpoints.py
Python
gpl-2.0
1,856
0.002694
# Endpoints for user to control the home. from datetime import datetime from flask import Blueprint, jsonify, request from services import elements_services, home_services home_api = Blueprint('/home_api', __name__) elem
ents_services = elements_services.ElementsServices() home_services = home_services.HomeServices() @home_api.route('/profiles') def profiles(): """Gets all profiles for all elements for user application to display and manipulate e
lements""" return jsonify(home_services.get_profiles()) @home_api.route('/element', methods=['POST']) def update_element(): """Updates single element with all new values received from the user application""" received_element = request.get_json() home_services.update_element(received_element) retur...
skylines-project/skylines
tests/model/test_user.py
Python
agpl-3.0
1,765
0.000567
# -*- coding: utf-8 -*- import os import pytest from skylines.lib import files from skylines.lib.types import is_unicode from skylines.model import User, IGCFile from tests.data import users, igcs def test_user_delete_deletes_user(db_session): john = users.john() db_session.add(john) db_session.commit()...
User._hash_password(u"secret123", salt=b"abcdef") assert ( hash == "bef57ec7f53a6d40beb640a780a639c83bc29ac8a9816f1fc6c5c6dcd93c4721272b82aa344691fb4037f20617b1d19212042e7e
6cb39f4ba0dad95d8137104a" ) assert is_unicode(hash)
OpenGenus/cosmos
tree/master/code/string_algorithms/sum_of_numbers_string/sum_of_numbers_string.py
Python
gpl-3.0
258
0
# ADDING A
LL NUMBERS IN A STRING. st = input("Enter a string: ") a = "" total = 0 for i in st: if i.isdigit(): a += i else: total += int(a) a = "0" print(total + int(a)) # INPUT: # Enter a string: 567hdon2 # O
UTPUT: # 569
Geonovum/sospilot
src/fiware/client/python/UL20/SimulateCommand.py
Python
gpl-3.0
3,074
0.016591
#!/usr/bin/env python # Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U # # This file is part of FIGWAY software (a set of tools for FIWARE Orion ContextBroker and IDAS2.6). # # FIGWAY is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as #...
20_PORT=config.get('idas', 'ul20port') FIWARE_SERVICE=config.get('idas', 'fiware-service') FIWARE_SERVICE_PATH=config.get('idas', 'fiware-service-path') IDAS_AAA=config.get('idas', 'OAuth')
if IDAS_AAA == "yes": TOKEN=config.get('user', 'token') TOKEN_SHOW=TOKEN[1:5]+"**********************************************************************"+TOKEN[-5:] else: TOKEN="NULL" TOKEN_SHOW="NULL" HOST_ID=config.get('local', 'host_id') f.close() URL = "http://"+IDAS_HOST+":"+IDAS_ADMIN_PORT+'/iot/ngsi/d...
puttarajubr/commcare-hq
corehq/apps/app_manager/migrations/0004_add_detail_filter_unreleased_builds.py
Python
bsd-3-clause
250
0
# encoding: utf-8
from south.v2 import DataMigration from corehq.apps.app_manager.migrations import AppFilterMigrat
ionMixIn class Migration(AppFilterMigrationMixIn, DataMigration): def get_app_ids(self): return self._get_all_app_ids()
wanghe4096/WangBlog
src/wangblog/migrations/0005_auto_20160417_0152.py
Python
bsd-2-clause
802
0.001247
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-17 01:52 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wangblog', '0004_auto_20160416_1039'), ] operations = [
migrations.RemoveField( model_name='user', name='is_staff', ), migrations.AddField( model_name='user', name=
'is_admin', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='user', name='date_joined', field=models.DateTimeField(default=datetime.datetime(2016, 4, 17, 1, 52, 6, 276869), verbose_name='date joined'), ), ]
evgeny-boger/rus-elections-stats
plot_results.py
Python
unlicense
7,993
0.017015
#!/usr/bin/python # -*- coding: UTF-8 -*- import csv, sys, array import ROOT import math def make_plots(title, input_files, close = True, party_num = 14, party_name = "ruling party"): ROOT.gStyle.SetOptFit(1) turnout_arr = array.array('d') rp_arr = array.array('d') h2 = ROOT.TH2D("h2", "weighte...
bins)", 220,0, 110) rp_votes_hist = ROOT.TH1D("rp_votes_hist", "Distribution of electoral commissions by " + party_name + " votes (" + title + ");" + party_name + " votes;Number of electoral commissions (--)", 10001,0, 10000) rp_votes_lastdigit_h
ist = ROOT.TH1D("rp_votes_lastdigit_hist", "Distribution of electoral commissions by last digit of " + party_name + " votes (" + title + ");last digit of rp votes;Number of electoral commissions (--)", 10,-0.5, 9.5) rp_weighted_hist = ROOT.TH1D("rp_weighted_hist", "Distribution of electoral commissions by " + p...
strongswan/strongTNC
config/wsgi.py
Python
agpl-3.0
1,414
0.000707
""" WSGI config for strongTNC. 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 Django WSGI application here, but it also might make sense to replace the whole Django WS...
ine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.enviro...
creditbit/electrum-creditbit
gui/qt/network_dialog.py
Python
gpl-3.0
9,292
0.007211
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@gitorious # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
_port, self.ssl_cb, self.servers_list_widget]: w.setEnabled(False) s
elf.autocycle_cb.clicked.connect(enable_set_server) enable_set_server() # proxy setting self.proxy_mode = QComboBox() self.proxy_host = QLineEdit() self.proxy_host.setFixedWidth(200) self.proxy_port = QLineEdit() self.proxy_port.setFixedWidth(60) self.pro...
DBrianKimmel/PyHouse
Project/src/Modules/Computer/Web/ipyhouse.py
Python
mit
113
0
"""
Created on Jul 11, 2013 @author: briank """ # from zope.interface import Interface, Attribute #
## END DBK
jamlamberti/bogo_probe
tests/classifier/test_surrogate_model.py
Python
gpl-3.0
445
0
""
"Collection of tests for classifier.surrogate_model""" from classifier import surrogate_model from learner import svm def test_surrogate_regression(): """Test case for running a classifier based Surrogate Model""" surrogate = svm.SVM() black_box = svm.SVM() surrogate_model.main( black_box, ...
ions=100)
frc2423/2015
recycle_rush/custom/kwarqs_drive_mech.py
Python
gpl-2.0
3,114
0.007707
import wpilib import hal from wpilib import RobotDrive class KwarqsDriveMech(RobotDrive): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.weight_multiplier = 1 def set_multiplier(self, in_multi = None): if in_multi != None :
self.weight_multiplier = in_multi else: self.weight_multiplier = 1 def mecanumDrive_C
artesian(self, x, y, rotation, gyroAngle): """Drive method for Mecanum wheeled robots. A method for driving with Mecanum wheeled robots. There are 4 wheels on the robot, arranged so that the front and back wheels are toed in 45 degrees. When looking at the wheels from the top, the roll...
to266/hyperspy
hyperspy/_components/eels_cl_edge.py
Python
gpl-3.0
14,359
0.00007
# -*- coding: utf-8 -*- # Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
f.__fine_structure_width def _set_fine_structure_width(self, arg): self.__fine_structure_width = arg self._set_fine_structure_coeff() fine_structure_width = property(_get_fine_structure_width, _set_fine_structure_width) # E0 def _get_E0(self): ...
_get_collection_angle(self): return self.__collection_angle def _set_collection_angle(self, arg): self.__collection_angle = arg self._calculate_effective_angle() collection_angle = property(_get_collection_angle, _set_collection_angle) # Convergence s...
lxylinki/medCC
src/main/resources/output/evalresults2014/calcuImp.py
Python
gpl-3.0
1,644
0.011557
#!/usr/bin/python3 # import concurrent.futures import os # produce an imp file def calcuImp(mods, edges, index): # med results filedir = './{}_{}/'.format(mods, edges) filename = 'workflow_{}_{}_{}.txt'.format(mods, edges, index) filename = os.path.join(filedir,filename) results = open(filename, '...
items = line.split() budlevel = int(items[0]) # med measurements cg
= float(items[1]) hbcs = float(items[2]) ss = float(items[3]) # print percentage impoverhbcs = (hbcs - cg)*100/hbcs impoverss = (ss-cg)*100/ss impline = '%d %.2f %.2f\n' % (budlevel, impoverhbcs, impoverss) impfile.write(impline) ...
janusnic/21v-python
unit_02/calc/1.py
Python
mit
991
0.035318
# Program make a simple calculator that can add, subtract, multiply and divide using functions # define functi
ons def add(x, y):
"""This function adds two numbers""" return x + y def subtract(x, y): """This function subtracts two numbers""" return x - y def multiply(x, y): """This function multiplies two numbers""" return x * y def divide(x, y): """This function divides two numbers""" return x / y # take input fr...
x2Ident/x2Ident_test
mitmproxy/test/pathod/test_language_actions.py
Python
gpl-3.0
3,653
0.000821
from six import BytesIO from pathod.language import actions, parse_pathoc, parse_pathod, serve def parse_request(s): return next(parse_pathoc(s)) def test_unique_name(): assert not actions.PauseAt(0, "f").unique_name assert actions.DisconnectAt(0).unique_name class TestDisconnects: ...
t v.offset == 100 e = actions.DisconnectAt.expr() v = e.parseString("dr")[0] assert v.offset == "r" def test_spec(self): assert actions.DisconnectAt("r").spec() == "dr" assert actions.DisconnectAt(10).spec() == "d10" class TestInject: def test_parse_path...
es" assert a.value.usize == 100 a = next(parse_pathod("400:ia,@100")).actions[0] assert a.offset == "a" def test_at(self): e = actions.InjectAt.expr() v = e.parseString("i0,'foo'")[0] assert v.value.val == b"foo" assert v.offset == 0 asser...
pyro-ppl/numpyro
numpyro/distributions/mixtures.py
Python
apache-2.0
8,387
0.002146
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import jax from jax import lax import jax.numpy as jnp from numpyro.distributions import Distribution, constraints from numpyro.distributions.discrete import CategoricalLogits, CategoricalProbs from numpyro.distributions.util import i...
""" return self._mixture_size @property def mixing_distribution(self): """ Returns th
e mixing distribution :return: Categorical distribution :rtype: Categorical """ return self._mixing_distribution @property def mixture_dim(self): return -self.event_dim - 1 @property def component_distribution(self): """ Return the vectorized di...
ptsg/AtamaTracker
atamatracker/data.py
Python
mit
2,081
0
"""data structure module """ import csv # setup csv format csv.register_dialect('result', delimiter='\t', lineterminator='\n') class Track(object): """Tracked point data struct. Public properties: point -- [Point] Tracked/
clicked point position label -- [int] Index number
time -- [float] Clicked time is_manual -- [bool] Whether the point was clicked manually """ __slots__ = ['time', 'label', 'point', 'is_manual'] def __init__(self, point, label, time, is_manual=False): self.point = point self.time = time self.label = label self.is_man...
oinopion/django
tests/admin_ordering/models.py
Python
bsd-3-clause
899
0
# -*- coding: utf-8 -*- from django.contrib import admin from django.db import models class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() rank = models.IntegerField() class Meta: ordering = ('name',) class Song(models.Model): band = models.ForeignK...
nd, related_name='covers') class Meta: ordering = ('name',) class SongInlineDefaultOrdering(admin.StackedInline): model = Song class SongInlineNewOrdering(admin.StackedInline): model = Song ordering = ('duration', ) class DynOrderingBandAdmin(admin.ModelAdmin): def get_ordering(self,...
_superuser: return ['rank'] else: return ['name']
LLNL/spack
var/spack/repos/builtin/packages/py-onnx/package.py
Python
lgpl-2.1
1,686
0.001779
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyOnnx(PythonPackage): """Open Neural Network Exchange (ONNX) is an open ecosystem that ...
computation graph model, as well as definitions of built-in operators and standard data types. Currently we focus on the capabilities needed for inferencing (scoring).""" homepage = "https://github.com/onnx/onnx" pypi = "Onnx/onnx-1.6.0.tar.gz" version('1.6.0', sha256='3b88c3fe521151651a040...
') # Protobuf version limit is due to https://github.com/protocolbuffers/protobuf/pull/8794 depends_on('protobuf@:3.17') depends_on('py-protobuf+cpp@:3.17', type=('build', 'run')) depends_on('py-numpy', type=('build', 'run')) depends_on('py-six', type=('build', 'run')) depends_on('[email protected]....
hiteshagrawal/python
udemy/russian-peasant-by-author-testing-fasting.py
Python
gpl-2.0
1,509
0.047714
#!/usr/bin/python ## Lecture 6 ## Fasting using a cache as empty dict ##: AKA - Mediation and DUplication ##: ##: Inouts -> two numbers #Output - > the solution to those two numbers # multiplied together using the Russian Peason # 192 x 13 = 2496 import time CACHE = {} def russian(a,b): key = (a,b) # define tuple...
start_time = time.time() print russian(357,16) print "Russian Algorithm took %f seconds" % (time.time()-start_time) # %f is a float assert russian(357,16) == 5712 test_russian() #5712 #Russian Algori
thm took 0.000015 seconds #5712 #Russian Algorithm took 0.000011 seconds #[Finished in 0.1s]
YAmikep/django-feedstorage
feedstorage/log.py
Python
bsd-3-clause
703
0.001422
# Django from django.core.files.storage import get_storage_class from django.utils.functional import LazyObject # Internal from .settings import ( FILE_STORAGE, FILE_STORAGE_ARGS, LOGGER_NAME, LOG_FILE, LOG_SIZE, LOGGER_FORMAT, LOG_LEVEL ) from .ut
ils.loggers import LoggerWithStorage class DefaultFileStorage(LazyObject):
def _setup(self): self._wrapped = get_storage_class(FILE_STORAGE)(**FILE_STORAGE_ARGS) default_file_storage = DefaultFileStorage() default_logger = LoggerWithStorage( storage=default_file_storage, logger_name=LOGGER_NAME, level=LOG_LEVEL, log_file=LOG_FILE, log_size=LOG_SIZE, ...
demisto/content
Packs/ILert/Integrations/ILert/ILert_test.py
Python
mit
1,276
0
import pytest import demistomock as demisto PARAMS = {'url': 'https://test.com', 'integrationKey': 'mock_key'} @pytest.fixture(autouse=True) def set_params(mocker): mocker.patch.object(demisto, 'params', return_value=PARAMS) def test_submit_new_event_command(requests_mock): from ILert import submit_new_eve...
}) result = submit_acknowledge_event_command(**kwargs) assert result == 'Incident has been acknowledged' def test_submit_resolve_event_command(requests_mock): from ILert import submit_resolve_event_command kwargs = { 'summary': 'mock_summary', 'incident_key': 'mock_key' } reque...
lt == 'Incident has been resolved'
marcomanciniunitn/Final-LUS-project
RNN/rnn/lus_rnn_lab/rnn_slu/data/new_data/word-pos-enhanced/enhance.py
Python
gpl-3.0
467
0.036403
#Funct
ion used to change all the O concepts of the words into the words themselves def changeAllO(file, out): w = open(out, "w") for line in (open(file).readlines()): v = line.split("\t") if(len(v)>1): if v[1][0:1] == "I" or v[1][0:1] == "B": w.write(line) else: w.write(v[0] + "\t" + "$-"+str(v[0])+"\n")...
.data")
whd/data-pipeline
reports/stability-summary/rollup.py
Python
mpl-2.0
11,194
0.001697
import psycopg2 import os import sys import csv from datetime import datetime, date, timedelta from utils import S3CompressedWriter from summarize import summarize # How many days "back" do we look for activity? latency_interval = 10 default_bucket = 'telemetry-public-analysis-2' current_cutoff = date.today() - time...
e.strftime('%Y%m%d'), segment=segment) with S3CompressedWriter(default_bucket, path) as fd: outcsv = csv.writer(fd) outcsv.writerow(( 'buildversion', 'buildid', 'buildarchitecture', 'channel', 'os',
'osversion', 'osservicepackmajor', 'osservicepackminor', 'locale', 'activeexperimentid', 'activeexperimentbranch', 'country', 'active_days', 'active_users')) for r in cur: outcsv.writerow(r) def put_c...
civisanalytics/ansible
lib/ansible/modules/cloud/ovirt/ovirt_disks.py
Python
gpl-3.0
20,012
0.002848
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible 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 #...
k profile name to be attached to disk. By default profile is chosen by oVirt engine." bootable: description: - "I(True) if the disk should be bootable. By default when disk is created it isn't bootable." shareable: description: - "I(True) if the disk should be shareable. ...
"C(address) - Address of the storage server. Used by iSCSI." - "C(port) - Port of the storage server. Used by iSCSI." - "C(target) - iSCSI target." - "C(lun_id) - LUN id." - "C(username) - CHAP Username to be used to access storage server. Used by iSCSI." - "...
meta-it/misc-addons
project_tags/project.py
Python
lgpl-3.0
1,241
0.002417
# -*- coding: utf-8 -*- # # # Project Tags # Copyright (C) 2013 Sistemas ADHOC # No email # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # ...
he GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # from openerp import models, fields class Project(models.Model): """""" _name = 'project.project' _inherits = {}
_inherit = ['project.project'] project_tag_ids = fields.Many2many('project_tags.project_tag', 'project_tags___project_tag_ids_rel', 'project_id', 'project_tag_id', string='Tags') _defaults = { } _constraints = [ ] Project() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4...
stnava/ITK
Wrapping/Generators/Python/Tests/SmoothingRecursiveGaussianImageFilter.py
Python
apache-2.0
1,076
0.001859
#========================================================================== # # Copyright Insight Software Consortium # # 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...
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. # #==========================================================================*/ ...
ingRecursiveGaussianImageFilter # import itk from sys import argv itk.auto_progress(2) reader = itk.ImageFileReader.IUC2.New(FileName=argv[1]) filter = itk.SmoothingRecursiveGaussianImageFilter.New( reader, Sigma=eval(argv[3])) itk.imwrite(filter, argv[2])
LaurentRDC/scikit-ued
skued/time_series/tests/test_fitting.py
Python
gpl-3.0
6,251
0.00144
from random import random, seed import numpy as np from skued import biexpone
ntial, exponent
ial, with_irf seed(23) def test_exponential_tzero_limits(): """Test that the output of ``exponential`` has the correct time-zero""" tzero = 10 * (random() - 0.5) # between -5 and 5 amp = 5 * random() + 5 # between 5 and 10 tconst = random() + 0.3 # between 0.3 and 1.3 t = np.arange(-10, 50, s...
bjpop/annokey
annokey/get_ncbi_gene_snapshot_xml.py
Python
bsd-3-clause
22,163
0.000406
#!/bin/env python '''NCBI Gene Downloading Tool This program downloads gene data from the ftp server and \ converts data to xml file by using linux.gene2xml tool. This program checks the last modified time of the database in the server, \ when it tries to download the gene database from the server. \ If the same vers...
Error Log] ' + str(exception)) return self.ftp def get_last_modified_time(self, filepath): '''Get the last modified time of the file on the server. The server gives the result code and the value. e.g) '213 20120101051112' ''' if self.ftp is None: print_v...
class MDTMError(Exception): '''Representation of modification time''' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) md_server = None try: print_verbose(1, 'Starts getting the la...
benkohler/catalyst
catalyst/builder.py
Python
gpl-2.0
702
0.035613
import os cla
ss generic(object): def __init__(self,myspec): self.settings=myspec self.settings.setdefault('CHROOT', 'chroot') def setarch(self, arch): """Set the chroot wrapper to run through `setarch |arch|` Useful for building x86-on-amd64 and such. """ if os.uname()[0] == 'Linux': self.settings['CHROOT'] = 'se...
to make sure we don't wipe the contents of a bind mount """ pass def mount_all(self): """do all bind mounts""" pass def umount_all(self): """unmount all bind mounts""" pass
ysh329/django-test
db10_admin/blog/admin.py
Python
apache-2.0
121
0.008264
from d
jango.contrib import admin from blog.models import User admin.site.register(User)
# Register your models here.
froyobin/horizon
openstack_dashboard/dashboards/admin/volumes/volume_types/qos_specs/tests.py
Python
apache-2.0
7,735
0
# 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 t...
(self): formData = {'name': 'qos-spec-1', 'consumer': 'back-end'} api.cinder.qos_spec_create(IsA(http.HttpRequest), formData['name'], {'consumer': formData['consume
r']}).\ AndReturn(self.cinder_qos_specs.first()) self.mox.ReplayAll() res = self.client.post( reverse('horizon:admin:volumes:volume_types:create_qos_spec'), formData) redirect = reverse('horizon:admin:volumes:volume_types_tab') self.assertNoFormError...
netscaler/neutron
neutron/db/db_base_plugin_v2.py
Python
apache-2.0
66,754
0.000075
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www....
salvatore-orlando): 'if query_filter' will try to evaluate the # condition, raising an exception if query_filter is not None: query = query.filter(query_filter) return query def _fields(self, resource, fields): if fields: return dict(((key, item) for key, ite...
return resource def _get_tenant_id_for_create(self, context, resource): if context.is_admin and 'tenant_id' in resource: tenant_id = resource['tenant_id'] elif ('tenant_id' in resource and resource['tenant_id'] != context.tenant_id): reason = _('Cannot ...
mwhoffman/pybo
pybo/demos/solve.py
Python
bsd-2-clause
1,238
0
""" Demo which illustrates how to use solve_bayesopt as a simple method for global optimization. The return values are the sequence of recommendations made by the algorithm as well as the final model. The point `xbest[-1]` is the final recommendation, i.e. the expected maximizer. """ from __future__ import division fr...
, info = solve_bayesopt(f, bounds, niter=30, verbose=True) # make some predictions mu, s2 = model.predict(x[:, None]) # plot the final model ax = figure().gca() ax.plot_banded(x, mu, 2*np.sqrt(s2)) ax.axvline(xbest) ax.scatter(info.x.ravel(), info.y) ax.figur
e.canvas.draw() show() if __name__ == '__main__': main()
BlogTANG/blog-a
theme.py
Python
mit
1,730
0.000578
import os def apply_theme(theme): theme_dir = os.path.join('themes', theme) if not os.path.isdir(theme_dir): print('There seems no "themes" directory existing.') return template_dir = os.path.join(theme_dir, 'templates') if not os.path.isdir(template_dir): print('The theme "' ...
.path.isdir(rel_path)) print('OK') # make symlinks for static files print('Applying static files...', end='') static_dir = os.path.join(theme_dir, 'static') if os.path.isdir(static_dir): if not os.path.exists(applied_static_dir): os.mkdir(applied_static_dir) file_list = ...
r, file) symlink_path = os.path.join(applied_static_dir, file) if os.path.lexists(symlink_path): os.remove(symlink_path) os.symlink(rel_path, symlink_path, os.path.isdir(rel_path)) print('OK') print('Successfully applied theme "' + theme + '"')
googleapis/python-dialogflow
samples/generated_samples/dialogflow_generated_dialogflow_v2_entity_types_batch_create_entities_async.py
Python
apache-2.0
1,788
0.001678
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
se is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the s
pecific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for BatchCreateEntities # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest publ...
odeke-em/mp
tests/testCacheConnector.py
Python
mit
1,439
0.006254
import unittest import sys import time import CacheConnector class TestInitializer(unittest.TestCase): def testInitializerWithArgs(self): cc = CacheConnector.CacheConnector() cc[9] = 10 self.assertEqual(cc.get(9, 100), 10) self.assertEqual(cc.pop(9, 'nonsense'), 10) self.a...
def dFuncUnchained(*args, **kwargs): global __terminationToggle for i in range(10): sys.stdout.write('#%d \033[92mSleeping.%s\033[00m\r'%(i, ' ' if i&1 else '.')) time.sleep(1) __terminationToggle = True self.assertEqual(cc.p...
# Expectation here is that dFuncUnchained should keep running # even after this test func exits, also __terminationToggle since it # is set to True at the end of dFuncUnchained, the assertion should hold self.assertEqual(__terminationToggle, False)
suutari-ai/shoop
shuup/configuration.py
Python
agpl-3.0
4,388
0
# -*- coding: utf-8 -*- # This file is part of Shuup.
# # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. """ API for Shuup's Dynamic Configuration. Idea of the Dynamic Configuratio
n is to allow storing configuration values similarly as :ref:`Django settings <django-settings-module>` allows, but in a more flexible way: Dynamic Configuration can be changed with a simple API and there is no need restart the application server after changing a value. Dynamic configuration values are permanent. Cur...
JavaCardOS/pyResMan
pyResMan/BaseDialogs/pyResManCommandDialogBase_MifareIncrement.py
Python
gpl-2.0
4,763
0.04325
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Jun 17 2015) ## http://www.wxformbuilder.org/ ## ## PLEASE DO "NOT" EDIT THIS FILE! ########################################################################### impo...
wx.EXPAND, 5 ) self._buttonOK = wx.Button( self, wx.ID_ANY, u"OK", wx.DefaultPosition, wx.DefaultSize, 0 )
self._buttonOK.SetDefault() bSizer47.Add( self._buttonOK, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self._buttonCancel = wx.Button( self, wx.ID_ANY, u"Cancel", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer47.Add( self._buttonCancel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) ...
alexskc/Fruitydo
profilepage/admin.py
Python
gpl-3.0
369
0.00813
"""Add tasks and events to the admin in
terface""" from django.contrib import admin from .models import Task, Event class EventInline(admin.StackedInline): """Create an interface for adding events.""" model = Event extra = 3 class TaskAdmin(a
dmin.ModelAdmin): """Add the interface.""" inlines = [EventInline] admin.site.register(Task, TaskAdmin)
areriff/pythonlearncanvas
Python Script Sample/create_dir_if_not_there.py
Python
mit
615
0.009756
# Script Name : create_dir_if_not_there.py # Author : Craig Richa
rds # Created : 09th January 2012 # Last Modified : # Version : 1.0 # Modifications : # Description : Checks to see if a directory exists in the users home directory, if not then create it import os # Import the OS module home = os.path.expanduser("~") # Set the variable home by expanding the users set...
y print home # Print the location if not os.path.exists(home + '/testdir'): # Check to see if the directory exists os.makedirs(home + '/testdir') # If not create the directory, inside their home directory
jinyu121/Canteen
CanteenWebsite/templatetags/canteen_website_tags.py
Python
gpl-3.0
1,773
0.00282
# -*- coding: utf-8 -*- from django import template from CanteenWebsite.models import Category from CanteenWebsite.utils.functions impor
t setting_get register = template.Library() @register.simple_tag def get_setting(name, default=None): return setting_get(name, default) @register.inclusion_tag('CanteenWebsite/inclusions/sidebar_category_list.htm
l', takes_context=True) def sidebar_category_list(context): categories = Category.objects.all() try: current_category = context['current_category'] except: current_category = None return { 'current': current_category, 'categories': categories, } @register.inclusion_...
Pursuit92/antlr4
runtime/Python3/src/antlr4/Recognizer.py
Python
bsd-3-clause
5,808
0.005682
# # Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. # from antlr4.RuleContext import RuleContext from antlr4.Token import Token from antlr4.error.ErrorListener import ProxyErrorLis...
# Indicate that the recognizer has changed internal state that is # consistent with the ATN state passed in. This way we always know # where we are in the ATN as the parser goes along. The rule # context objects form a stack that lets us see the stack of # invoking rules. Combine this and we have c...
tionException import unittest class Test(unittest.TestCase): def testVersion(self): major, minor = Recognizer().extractVersion("1.2") self.assertEqual("1", major) self.assertEqual("2", minor) major, minor = Recognizer().extractVersion("1.2.3") self.assertEqual("1", major) ...
dvarrazzo/arduino
thermo/client/google_api.py
Python
gpl-3.0
1,030
0.004854
#!/usr/bin/env python """Read the Google Weather API and emit data in the usual format. Write a sample every 5 minutes on stdout, log on stderr. """ import sys import time from ur
llib import quote_plus from urllib2 i
mport urlopen from datetime import datetime, timedelta from xml.etree import cElementTree as ET import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() def main(): location = sys.argv[1] url = ("http://www.google.com/ig/api?weather=" + quote_plus(location)) while 1: ...
kcompher/pygraphistry
docs/source/conf.py
Python
bsd-3-clause
11,851
0.006329
import sys import os sys.path.insert(0, os.path.abspath('../..')) # -*- coding: utf-8 -*- # # PyGraphistry documentation build configuration file, created by # sphinx-quickstart on Fri Aug 21 19:30:19 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that
not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in anothe
r directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs...
weidnerm/solar_data_monitor
SolarSensors_test.py
Python
mit
3,665
0.014734
from unittest import TestCase, main, skip from mock import patch, call, MagicMock from SolarSensors import SolarSensors import os class SolarSensors_test(TestCase): def setUp(self): pass def tearDown(self): pass def get_default_config(self): config = [ { ...
{'scale': 1.0, 'name': 'Batt 2', 'address': '0x4a'}, {'scale': 1.0, 'name': 'Batt 1', 'address': '0x46'}], c
onfig) @patch('SolarSensors.INA219') def test_ctor(self, mockINA): mySolarSensors = SolarSensors( self.get_default_config() ) self.assertEqual(['Panel', 'Batt 5', 'Batt 6', 'Load', 'Batt 7', 'Batt 8', 'Batt 4', 'Batt 3', 'Batt 2', 'Batt 1'] , mySolarSensors.m_sensorNames) #...
frewsxcv/lop.farm
app/landing/tests.py
Python
mpl-2.0
544
0
from django.core.urlresolvers impor
t reverse from django.test import Client, TestCase class LandingViewTestCase(TestCase): def test_landing(self): url = reverse('landing') res = self.client.get(url) self.assertEqual(200, res.status_code) class LandingTestCase(TestCase): def test_no_catch_all(self): """Ensure t...
/this-should-not-be-a-valid-endpoint') self.assertEqual(response.status_code, 404)
plecto/motorway
motorway/contrib/recurly_integration/ramps.py
Python
apache-2.0
1,594
0.000627
import os import time from motorway.messages import Message from motorway.ramp import Ramp """ Requires pip install recurly """ class RecurlyRamp(Ramp): @property def recurly(self): import recurly recurly.SUBDOMAIN = os.e
nviron.get('RECURLY_SUBDOMAIN') recurly.API_KEY = os.environ.get('RECURLY_API_KEY') return recurly class RecurlyInvoiceRamp(RecurlyRamp): def next(self): for invoice in self.recurly.Invoice.all(): yield Message(invoice.uuid, { 'uuid': invoice.uuid, ...
'vat_number': invoice.vat_number, 'total_in_cents': invoice.total_in_cents, 'tax_in_cents': invoice.tax_in_cents, 'subtotal_in_cents': invoice.subtotal_in_cents, 'state': invoice.state, 'collection_method': invoice.collectio...
felix9064/python
Demo/liaoxf/do_generator.py
Python
mit
2,677
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 生成器表达式----一边循环一边计算 # 列表元素可以在循环的过程中不断推算出后续的元素 # 这样就不必创建完整的list,从而节省大量的空间 from collections import Iterable import array # 第一种方法:将列表生成式最外面的[] 改成() # 列表生成式 list_comp = [x * x for x in range(10)] # 生成器表达式 list_gene = (x * x for x in range(10)) # 生成器是可迭代对象 print(isinstance(...
te'] sizes = ['S', 'M', 'L'] for t_shirts in ('%s %s' % (c, s) for c in colors for s in sizes): print(t_shirts) # 用函数循环的方法实现斐波拉契数列 def fibonacci1(num): n, a, b = 0, 0, 1 while n < num: prin
t(b, end=' ') a, b = b, a + b n = n + 1 print('done') return 'done' fibonacci1(20) # 第二种方法:如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator(生成器函数) # 把上面定义的函数改一下就成了一个生成器 def fibonacci2(num): n, a, b = 0, 0, 1 while n < num: yield b a, b = b, a + b n = n + 1 ...
lcpt/xc
verif/tests/database/test_database_14.py
Python
gpl-3.0
4,437
0.038323
# -*- coding: utf-8 -*- # home made test import xc_base import geom import xc from model import predefined_spaces from solution import predefined_solutions from materials import typical_materials __author__= "Luis C. Pérez Tato (LCPT)" __copyright__= "Copyright 2014, LCPT" __license__= "GPL" __version__= "3.0" __emai...
,ratio1 print "ratio2= ",ratio2 print "ratio3= ",ratio3 print "ratio4= ",ratio4 ''' import os from miscUtils import LogMessages as lmsg fname= os.path.basename(__file__) if (abs(ratio1)<1e-5) & (abs(ratio2)<1e-5) & (abs(ratio3)<1e-5): print "test ",fname,": ok." else: lmsg.error(fname+' ERROR.') os.system(
"rm -rf /tmp/test14.db") # Your garbage you clean it
MIT-LCP/mimic-code
mimic-iv/tests/test_sepsis.py
Python
mit
481
0.002079
import pandas as pd from pandas.io import gbq def test_sepsis3_one_row_per_stay_id(dataset, project_id): """Verifies one stay_id per row of sepsis-3""" query = f""" SELECT COUNT(*) AS n FROM
( SELECT stay_id FROM {dataset}.sepsis3 GROUP BY 1 HAVING COUNT(*) > 1 ) s """ df = gbq.read_gbq(query, project_id=project_id, d
ialect="standard") n = df.loc[0, 'n'] assert n == 0, 'sepsis-3 table has more than one row per stay_id'
TomasTomecek/docker-scripts
tests/test_integ_squash.py
Python
mit
19,462
0.001182
import unittest import pytest import mock import six import docker import os import json import logging import sys import tarfile import io from io import BytesIO import uuid from docker_scripts.squash import Squash from docker_scripts.errors import SquashError if not six.PY3: import docker_scripts.lib.xtarfile ...
Squash( self.log, self.image.tag, self.docker, tag=self.tag, from_layer=from_layer, output_path=self.outp
ut_path, load_output_back=self.load_output_back) self.image_id = squash.run() if not self.output_path or self.load_output_back: self.squashed_layer = self._squashed_layer() self.layers = [o['Id'] for o in self.docker.history(self.tag)] self.metada...
gkc1000/pyscf
examples/doci/00-simple_doci_casscf.py
Python
apache-2.0
361
0
#!/usr/bin/env python # # Author: Qiming Sun <[email protected]> # ''' A simple example to run DOCI-CASCI and DOCI-
CASSCF calculation. ''' from pyscf import gto from pyscf import
doci mol = gto.M(atom='N 0 0 0; N 0 0 2.', basis='6-31g') mf = mol.RHF().run() mc = doci.CASSCF(mf, 18, 14) mc.verbose = 4 mc.kernel() mc = doci.CASCI(mf, 18, 14) mc.kernel()
shadowmint/nwidget
lib/cocos2d-0.5.5/cocos/gl_framebuffer_object.py
Python
apache-2.0
3,430
0.003207
# ---------------------------------------------------------------------------- # cocos2d # Copyright (c) 2008-2012 Daniel Moisset, Ricardo Quesada, Rayentray Tappa, # Lucio Torre # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
ogl-sample/registry/EXT/framebuffer_object.txt API is not very OO, should be improved. """ def __init__ (self): """Create a new framebuffer object""" id = GLuint(0) glGenFramebuffersEXT (1, ct.byref(id)) self._id = id.value def bind (self): """Set FBO...
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0) def texture2d (self, texture): """Map currently bound framebuffer (not necessarily self) to texture""" glFramebufferTexture2DEXT ( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texture.target, ...
fxia22/ASM_xf
PythonD/site_python/MMTK/MolecularSurface.py
Python
gpl-2.0
6,739
0.006529
# # Copyright 2000 by Peter McCluskey ([email protected]). # You may do anything you want with it, provided this notice is kept intact. # # This module is in part a replacement for the MolecularSurface MMTK module # that uses the NSC code. It has a less restrictive license than the NSC code, # and is mostly more flexible,...
e): self.a1 = a1 self.a2 = a2 if dist is None: self.dist = (a1.position() - a2.position()).length() else:
self.dist = dist def __getitem__(self, index): return (self.a1, self.a2)[index] def __cmp__(a, b): return cmp(a.dist, b.dist) def __hash__(self): return (self.a1, self.a2) def __repr__(self): return 'Contact(%s, %s)' % (self.a1, self.a2) __str__ = __repr__ de...
jkilpatr/browbeat
lib/Shaker.py
Python
apache-2.0
22,576
0.001772
# 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 ...
ld not be found, pushing details to Elastic") record = {'status': "error"} shaker_stats = { 'timestamp': str(es_ts).replac
e(" ", "T"), 'browbeat_scenario': browbeat_scenario, 'shaker_uuid': str(shaker_uuid), 'record': record, 'browbeat_rerun': run } result = self.elastic.combine_metadata(shaker_stats) index_status = self.elastic.index_resu...
lojaintegrada/pyboleto
docs/conf.py
Python
bsd-3-clause
8,020
0.006862
# -*- coding: utf-8 -*- # # pyboleto documentation build configuration file, created by # sphinx-quickstart on Thu Jul 5 02:10:50 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # Al...
eamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pyboleto.tex', u'Documentação pyboleto', u'Eduardo Cereto Carvalho', 'manual'), ] # The name of an image file (r...
ts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is gene...
gridengine/config-api
uge/objects/access_list_v1_0.py
Python
apache-2.0
2,599
0.005002
#!/usr/bin/env python # # ___INFO__MARK_BEGIN__ ####################################################################################### # Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.) # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file e...
str :raises: **InvalidArgument** - in case metadata is not a dictionary, JSON string is not valid, or it does not contain dictionary representing an AccessList object. """ QconfObject.__init__(self, name=name, data=data, metadata=metadata
, json_string=json_string)
linhdh/SnakeRepellerOnMbed50
mbed-os/tools/build_api.py
Python
gpl-2.0
54,455
0.001653
""" mbed SDK Copyright (c) 2011-2016 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...
to a report dictionary Positional arguments: report - the report to append to result - the result to append """ result["date"] = datetime.datetime.utcnow().isoformat() result["uuid"] = str(uuid.uuid1()) target = result["target_name"] toolchain = result["toolchain_name"] id_name = re...
].append(result_wrap) def get_config(src_paths, target, toolchain_name): """Get the configuration object for a target-toolchain combination Positional arguments: src_paths - paths to scan for the configuration files target - the device we are building for toolchain_name - the string that identifie...
davcastroruiz/boston-django-project
webSite/music/models.py
Python
gpl-3.0
878
0.001139
from django.db import models from django.core.urlresolvers import reverse class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.FileField() def get_absolute_url(self): ...
ete=models.CASCADE) song_title = models.CharField(max_length=500) file_type = models.CharField(max_length=10) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.album_i
d}) def __str__(self): return self.song_title + "." + self.file_type
smartxworks/jira-comment-slack
setup.py
Python
mit
1,060
0
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, SMARTX import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) setup( name='jira-comment-slack', version='0.1', url='https://github.com/smartxworks/jira-comment-slack', license='MIT', author='SmartXWorks/Kisung', ...
mment update to slack channel', long_description=__doc__, py_modules=["jira_comment_slack"], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask',
'requests', ], entry_points={ 'console_scripts': [ 'jira-comment-slack-server = jira_comment_slack:main', ], }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ...
assertnotnull/bookmarklets
bookmarklets/bookmarkletsapp/methods.py
Python
mit
211
0.004739
from .model
s import Vote def get_review_avg(bid): votes = Vote.objects.filter(bookmarklet_id=bid) total = len(votes) avg = 0.0 for vote i
n votes: avg += vote.rating return avg/total
chrisspen/django-pjm
django_pjm/management/commands/import_pjm_prices.py
Python
mit
798
0.005013
from optparse import make_option from django.core.management.base import NoArgsCommand, BaseCommand from django_pjm import models class Command(BaseCommand): help = "Imports PJM locational marginal pricing day-ahead data." args = '' option_list = BaseCommand.option_list + ( make_option('--start-y...
lt=0), make_option('--end-year', default=0), make_option('--only-type', default=None), make_option('--auto-reprocess-days', default=0), ) def handle(self, **options): models.Node.load( start_year=int(options['start_year']), end_year=int(options['end_y...
reprocess_days=int(options['auto_reprocess_days']), )
eBrnd/i3pystatus
i3pystatus/syncthing.py
Python
mit
4,026
0.000248
import json import os.path import requests from subprocess import call from urllib.parse import urljoin import xml.etree.ElementTree as ET from i3pystatus import IntervalModule from i3pystatus.core.util import user_open class Syncthing(IntervalModule): """ Check Syncthing's online status and start/stop Syncth...
y').text def ping(self): try: ping_data = self.st_get('/
rest/system/ping') if ping_data['ping'] == 'pong': return True else: return False except requests.exceptions.ConnectionError: return False def run(self): self.read_config() self.online = True if self.ping() else False ...
BeTeK/EliteMerchant
src/ui/TabAbstract.py
Python
bsd-3-clause
1,019
0.040236
import time, Options class TabAbstract: def setTabName(self, name): raise NotImplemented() def getTabName(self): raise NotImplemented() def getType(self): raise NotImplemented() def dispose(self): raise NotImplemented() def AgeToColor(self,timestam...
,min(maxv,v)) age= ( (time.time() - timestamp )/(60.0*60.0*24.0) ) / float(Options.get("Market-valid-days", 7)) colorblind=False # todo: add an option # colorblind mode if (colorblind): print(age) i=clamp(64,255,255-age*128) return i,i,i ...
, have it show desat=1 if age>1.0: desat=0 age*=2 r=255*clamp(0.2*desat,1.0,(age-1)+0.5) g=255*clamp(0.4*desat,1.0,(1-age)+0.5) b=255*clamp(0.5*desat,1.0,(abs(age-1)*-1)+1) return r,g,b