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
allohakdan/minibus
test/test_syntax.py
Python
apache-2.0
1,148
0.008711
import unittest from jsonschema import SchemaError from minibus import MiniBusClient class SyntaxTest(unittest.TestCase): def setUp(self): self.client = MiniBusClient() def callback(self): pass def callback2(self): pass def test_sub_good(self): self.client.subscribe("...
.subscribe("test_sub_schema_mismatch", {"type": "number"}, self.callback) self.assertRaises(Exception, self.client.subscribe, "test_sub_schema_mismatch", {"type": "string"}, self.callback2) def test_sub_schema_dupcallback(self): self.client.subscribe("test_sub_schema_dupcallback", {...
self.assertRaises(Exception, self.client.subscribe, "test_sub_schema_dupcallback", {"type": "number"}, self.callback) if __name__ == "__main__": unittest.main()
sabinaczopik/python_training
test/test_edit_contact.py
Python
apache-2.0
949
0.004215
from model.contact import Contact from random import randrange def test_edit_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(first_name ="Sabina", last_name="test", company="Pewex", address="osiedle", phone_home="123456789", e_m...
year="2016",)) old_contact = db.get_contact_list() index = randrange(len(old_contact)) contact = Contact(first_name='
Kasia', last_name='Bober') contact.id = old_contact[index].id app.contact.edit_contact_by_index(index, contact) assert len(old_contact) == app.contact.count() new_contact = db.get_contact_list() old_contact[index] = contact assert old_contact == new_contact if check_ui: assert sorted...
ameihm0912/mozdef_client
mozdef_client.py
Python
mpl-2.0
20,473
0.00254
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation # Author: gdestuynder@mozilla.com # Author: ameihm@mozill...
f send(self, summary=None, category=None, severity=None, tags=None, details=None): tsummary = summary tcategory = category tseverity = severity ttags = tags tdetails = details if tsummary == None: tsummary = self.summary if tcategory
== None: tcategory = self.category if tseverity == None: tseverity = self.severity if ttags == None: ttags = self.tags if tdetails == None: tdetails = self.details amsg = MozDefEvent(self.hostname) amsg.set_simple_update_log(self.l...
mhvk/baseband
baseband/tests/test_conversion.py
Python
gpl-3.0
19,399
0
# Licensed under the GPLv3 - see LICENSE import pytest import numpy as np import astropy.units as u from astropy.time import Time from .. import vdif from .. import mark4 from .. import mark5b from .. import dada from ..base.encoding import EIGHT_BIT_1_SIGMA from ..data import (SAMPLE_MARK4 as SAMPLE_M4, SAMPLE_MARK5B ...
m5h = mark5b.Mar
k5BHeader.fromfile(fh, kday=56000) m5pl = mark5b.Mark5BPayload.fromfile(fh, sample_shape=(8,), bps=2) header = vdif.VDIFHeader.from_mark5b_header( m5h, nchan=m5pl.sample_shape.nchan, bps=m5pl.bps) # Create VDIF payload from the Mark 5B encoded payload. payload = vdif.VDIF...
acrosby/netcdf4-getncattrs
getncattrs.py
Python
mit
129
0
# # acrosby 2013 # def __call__(nc): s = {} for attr in nc.ncattrs(): s[attr] = nc.getncattr(attr)
return s
jeanslack/Videomass
videomass/vdms_threads/generic_task.py
Python
gpl-3.0
3,294
0
# -*- coding: UTF-8 -*- """ Name: generic_task.py Porpose: Execute a generic task with FFmpeg Compatibility: Python3 (Unix, Windows) Author: Gianluca Pernigotto <jeanlucperni@gmail.com> Copyright: (c) 2018/2022 Gianluca Pernigotto <jeanlucperni@gmail.com> license: GPL3 Rev: Feb.14.2022 Code checker: flake8: --ignor...
' % error) return """
get = wx.GetApp() appdata = get.appset def __init__(self, param): """ Attributes defined here: self.param, a string containing the command parameters of FFmpeg, excluding the command itself `ffmpeg` self.status, If the exit status is true (which can be an e...
alice1017/coadlib
coadlib/loopapp.py
Python
mit
871
0
#!/usr/bin/env python # coding: utf-8 from .interactiveapp import InteractiveApplication, ENCODING class InteractiveLoopApplication(InteractiveApplication): def __init__(self, name, desc, version, padding, margin, suffix, encoding=ENCODING): super(InteractiveLoopApplication, self).__in...
ding, margin, suffix, encoding) # loop status self.STATUS_EXIT = 0 self.STATUS_CONTINUE = 1 def loop(self, func): def mainloop(): loop_flag = self.STATUS_CONTINUE while loop_flag == self.STATUS_CONTINUE: try: loop_f
lag = func() except KeyboardInterrupt: self.write_error("Terminated.") self.exit(0) self.exit(0) return mainloop
elmamyra/kbremap
kbremap_app/keyTools/__init__.py
Python
gpl-3.0
12,391
0.011137
# This file is part of the kbremap project. # Copyright (C) 2014 Nicolas Malarmey # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
syms(self, keycode): entries = self.keycode2entries(keycode) return [e[0] for e in entries][:4] def char2entries(self, char): keysym = gdk.unicode_to_keyval(ord(char)) # @UndefinedVariable if keysym: return se
lf.keysym2deadEntries(keysym) return () def findWithDeadKey(self, keysym): name = gdk.keyval_name(keysym) # @UndefinedVariable for deadName in DEAD_KEYS: if name.endswith(deadName): keyName = name[:-len(deadName)] deadName = {'ring':...
dotoscat/Polytank-ASIR
client_setup.py
Python
agpl-3.0
626
0.033546
from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. buildOptions = dict(packages = ["pyglet", "polytanks", "codec
s", "encodings", "selectors"], excludes = ["tkinter", "PyQt5", "PIL", "setuptools"] , include_files="assets") import sys base = 'Win32GUI' if sys.platform=='win32' else None executables = [ Execu
table('main.py', base=base, targetName = 'cliente.exe') ] setup(name='polytanks-cliente', version = '1.0', description = 'Cliente de Polytanks', options = dict(build_exe = buildOptions), executables = executables)
marduk191/plugin.video.movie25
resources/libs/movies_tv/oneclickwatch.py
Python
gpl-3.0
11,474
0.022486
import urllib,re,sys,os import xbmc,xbmcgui,xbmcaddon,xbmcplugin from resources.libs import main #Mash Up - by Mash2k3 2012. addon_id = 'plugin.video.movie25' selfAddon = xbmcaddon.Addon(id=addon_id) art = main.art def LISTSP(murl): #urllist=main.OPENURL('http://oneclickwatch.org/category/movies/')+main.OPE...
stream_url = False return infoLabels =main.GETMETAEpiT(mname,thumbs,descs) video_type='episode' season=infoLabels['season'] episode=infoLabels['episode'] img=infoLabels['cover_url'] fanart =infoLabels...
infolabels = { 'supports_meta' : 'true', 'video_type':video_type, 'name':str(infoLabels['title']), 'imdb_id':str(infoLabels['imdb_id']), 'season':str(season), 'episode':str(episode), 'year':str(infoLabels['year']) } infoL={'Title': infoLabels['title'], 'Plot': infoLabels['plot'], 'Genre': infoLabels['g...
agry/NGECore2
scripts/expertise/expertise_sp_cloaked_recovery_1.py
Python
lgpl-3.0
700
0.027143
import sys def addAbilities(core, actor, player): if actor.getLevel() >= 10: actor.addAbility("sp_cloaked_recovery_0") if
actor.getLevel() >= 28: actor.addAbility("sp_cloaked_recovery_1") if actor.getLevel() >= 54: actor.addAbility("sp_cloaked_recovery_2") if actor.getLevel() >= 70: actor.addAbility("sp_cloaked_recovery_3") if actor.getLevel() >= 86: actor.addAbility("sp_cloaked_recovery_4") return def removeAbilities(core, a...
.removeAbility("sp_cloaked_recovery_1") actor.removeAbility("sp_cloaked_recovery_2") actor.removeAbility("sp_cloaked_recovery_3") actor.removeAbility("sp_cloaked_recovery_4") return
igemsoftware2017/USTC-Software-2017
biohub/forum/migrations/0005_auto_20171001_2105.py
Python
gpl-3.0
799
0.001252
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-01 13:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependenci
es = [ ('contenttypes', '0002_remove_content_type_name'), ('forum', '0004_activity_brick_name'), ] operations = [ migrations.AddField( model_name='activity', name='target_id', field=models.PositiveSmallIntegerField(default=0, null=True), ), ...
ld( model_name='activity', name='target_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'), ), ]
afrolov1/nova
nova/cells/messaging.py
Python
apache-2.0
84,342
0.000628
# Copyright (c) 2012 Rackspace Hosting # All Rights Reserved. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License");...
pache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i
n writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Cell messaging module. This module d...
NLHEALTHCARE/PYELT
tests/old/unit_tests_rob/_domain_rob_unittest.py
Python
gpl-3.0
2,194
0.001823
from pyelt.datalayers.database import Column, Columns from pyelt.datalayers.dv import Sat, DvEntity, Link, Hub, HybridSat, LinkReference clas
s Role: pass class Act: pass class Participation: pass class Zorgverlener(DvEntity, Role): class Default(Sat): zorgverlenernummer = Columns.TextColumn() aanvangsdatum = Columns.DateColumn()
einddatum = Columns.DateColumn() class Personalia(Sat): achternaam = Columns.TextColumn() tussenvoegsels = Columns.TextColumn() voorletters = Columns.TextColumn() voornaam = Columns.TextColumn() bijnaam = Columns.TextColumn() # wordt niet gebruikt in dwh2.0...
mishravikas/geonode-permissions
geonode/layers/models.py
Python
gpl-3.0
15,289
0.001243
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # 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 versio...
def __str__(self): if self.typename is not None: return "%s Layer" % self.service_typename.encode('utf-8') elif self.name is not None: return "%s Layer" % self.name
else: return "Unamed Layer" class Meta: # custom permissions, # change and delete are standard in django permissions = ( ('view_layer','Can view'), ('change_layer_permissions',"Can change permissions"), ('edit_layer_style','can edit style'),...
GutenkunstLab/SloppyCell
test/test_FixedPoints.py
Python
bsd-3-clause
3,610
0.006925
import unittest import scipy from SloppyCell.ReactionNetworks import * lorenz = Network('lorenz') lorenz.add_compartment('basic') lorenz.add_species('x', 'basic', 0.5) lorenz.add_species('y', 'basic', 0.5) lorenz.add_species('z', 'basic', 0.5) lorenz.add_parameter('sigma', 1.0) lorenz.add_parameter('r', 2.0) lorenz....
with_logs=False) # This should find the fixed-point [0, 0, 0] self.assertAlmostEqual(fp[0], 0, 6, 'Failed on basic 2,0.') self.assertAlmostEqual(fp[1], 0, 6, 'Failed on basic 2,1.') self.assertAlmostEqu
al(fp[2], 0, 6, 'Failed on basic 2,2.') def test_withlogs(self): """ Test fixed-point finding with logs """ net = lorenz.copy('test') fp = Dynamics.dyn_var_fixed_point(net, dv0=[1,1,1], with_logs=True) # This should find the fixed-point [sqrt(2), sqrt(2), 1] self.assertAlmos...
chenbachar/HelpApp
src/versions/Iter2/helpapp-seproject/models/request.py
Python
mit
739
0.051421
#this model represents a request in our system from google.appengine.ext import ndb from datetime import datetime from datetime import timedelta class Request(ndb.Model): city = ndb.StringProperty() phone = ndb.String
Property() date = ndb.DateTimeProperty() description = ndb.StringProperty() isCarNeeded = ndb.BooleanProperty() @classmethod def add(self,cit,phoneNum,desc,carNeeded): req = Request() req.city = cit req.phone = phoneNum req.description = desc req.isCarNeeded = carNeeded req.date = datetim...
(hours=UTC_OFFSET) #(UTC+3 = GMT+2) req.put()
dkliban/pulp_puppet
pulp_puppet_extensions_admin/pulp_puppet/extensions/admin/repo/status.py
Python
gpl-2.0
12,614
0.002299
from gettext import gettext as _ import traceback from pulp.client.commands.repo.sync_publish import StatusRenderer from pulp.client.extensions.core import COLOR_FAILURE from pulp_puppet.common import constants from pulp_puppet.common.publish_progress import PublishProgressReport from pulp_puppet.common.sync_progres...
dules_state in constants.COMPLETE_STATES: self._render_module_errors(sync_report.modules_individual_errors) # Before finishing update the st
ate self.sync_modules_last_state = sync_report.modules_state def _display_publish_modules_step(self, publish_report): # Do nothing if it hasn't started yet or has already finished if publish_report.modules_state == constants.STATE_NOT_STARTED or \ self.publish_modules_last_state...
yaniv14/OpenCommunity
src/communities/migrations/0014_auto_20160804_1517.py
Python
bsd-3-clause
603
0.001658
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-04 12:17 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('communities', '0013_
auto_20160801_1241'), ] operations = [ migrations.AlterField( mode
l_name='groupuser', name='group', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_users', to='communities.CommunityGroup', verbose_name='Group'), ), ]
justinwp/croplands
croplands_api/views/api/users.py
Python
mit
2,237
0.002235
from croplands_api import api from croplands_api.models import User from croplands_api.views.api.processors im
port api_roles, remove_relations from croplands_api.exceptions import Unauthorized from croplands_api.auth import is_anonymous, current_user, verify_role def can_edit_the_user(data=None, **kwargs): """ Determines if t
he current user can modify the specified user account. :param data: :param kwargs: :return: None """ if is_anonymous(): raise Unauthorized() if hasattr(current_user, 'id') and current_user.id == int(kwargs['instance_id']): return if verify_role('admin'): return ...
addition-it-solutions/project-all
addons/account_bank_statement_extensions/account_bank_statement.py
Python
agpl-3.0
6,685
0.005984
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under ...
bank_statement_line_obj.invalidate_cache(cr, uid, ['state'], line_ids, context=context) return True def button_cancel(self, cr, uid, ids, context=None): bank_statement_line_obj = self.pool.get('account.bank.statement.line') super(account_bank_statement, self).button_cancel(cr, uid, ...
line_ids = [l.id for l in st.line_ids] cr.execute("UPDATE account_bank_statement_line \ SET state='draft' WHERE id in %s ", (tuple(line_ids),)) bank_statement_line_obj.invalidate_cache(cr, uid, ['state'], line_ids, context=context) re...
xperienced/flask-rest-boilerplate
config/development.py
Python
mit
63
0.015873
DEBUG = True SQL
ALCHEMY_DATABASE_URI = 'sqlite:////tmp/t
est.db'
jpartogi/django-job-board
job_board/templatetags/tag_list.py
Python
bsd-3-clause
1,058
0.017013
from django.template import Library, Node, Variable, VariableDoesNotExist from django.core.urlresolvers import reverse from job_board.views import job_list_by_tag register = Library() def do_populate_tags(pa
rser,token): """ render a list of tags, with it's link. the token is tag. Arguments: - `parser`: - `token`: """ bits = token.split_contents() print bits return PopulateTagsNode(bits[1]) class Po
pulateTagsNode(Node): def __init__(self,tag): self.tag_tag = Variable(tag) def render(self,context): try: _tag = self.tag_tag.resolve(context) _font_size = _tag.font_size + 10 _font_weight = min(900,(300 + (_tag.font_size*100))) _url = reverse(job...
kmee/odoo-brazil-hr
l10n_br_resource/__openerp__.py
Python
agpl-3.0
854
0
# -*- coding: utf-8 -*- # Copyright 2016 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'L10n Br Resource', 'summary': """ This module extend core resource to create important brazilian informations. Define a Brazilian calendar and some tools to compute d...
s/resource_calendar.xml', 'views/resource_calendar_leaves.xml', 'views/menu_resource_calendar.xml', 'wizard/workalendar_holiday_impo
rt.xml', ], }
zstackio/zstack-woodpecker
integrationtest/vm/virt_plus/test_stub.py
Python
apache-2.0
33,035
0.007083
''' Create an unified test_stub to share test operations @author: Youyk ''' import os import subprocess import time import uuid import zstacklib.utils.ssh as ssh import zstacklib.utils.jsonobject as jsonobject import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_util as test_util...
executable='/bin/sh', shell=True, universal_newlines=True) else: process = subprocess.Popen(cmd, executable='/bin/sh', shell=True, stdout=logfd, stderr=logfd, universal_newlines=True) start_time = time.time() while process.poll() is None: curr_time = time.time() TEST_TIME = c...
ss.kill() test_util.test_logger('[shell:] %s timeout ' % cmd) return False time.sleep(1) test_util.test_logger('[shell:] %s is finished.' % cmd) return process.returncode def create_test_file(vm_inv, bandwidth): ''' the bandwidth is for calculate the test file...
rockstor/rockstor-core
src/rockstor/smart_manager/views/cpu_util.py
Python
gpl-3.0
963
0
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la...
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 this program. If not, see <http://www.gnu.org/licenses/>.
""" from smart_manager.models import CPUMetric from smart_manager.serializers import CPUMetricSerializer from generic_sprobe import GenericSProbeView class CPUMetricView(GenericSProbeView): serializer_class = CPUMetricSerializer model_obj = CPUMetric
pgrimaud/django-pokedex
pokemon/views.py
Python
mit
616
0.008117
from django.template import Context, loader from pokemon.models import Pokemon from django.http import HttpResponse from django.http import Http404
def index(request): Pokemons = Pokemon.objects.all().order_by('id_pokemon') t = loader.get_template('pokemon/index.html') c = Context({
'Pokemons': Pokemons, }) return HttpResponse(t.render(c)) def pokemon(request, id): try: Pkmn = Pokemon.objects.get(id_pokemon=id) except Pokemon.DoesNotExist: raise Http404 return HttpResponse(loader.get_template('pokemon/pokemon.html').render(Context({'Pokemon': Pkmn,})))
splice/gofer
src/gofer/metrics.py
Python
lgpl-2.1
1,728
0.004051
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU Lesser General Public # License as published by the Free Software Foundation; either version # 2 of the License (LGPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # includin...
r FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of LGPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/lgpl-2.0.txt. # # Jeff Ortel <jortel@redhat.com> # """ The I{metrics} module defines classes and other resources designed for collecting and reporting perform...
self.stopped = stopped def start(self): self.started = time.time() self.stopped = 0 return self def stop(self): if self.started > 0: self.stopped = time.time() return self def duration(self): return ( self.stopped - self.started ) def __st...
bmmalone/pymisc-utils
pyllars/__init__.py
Python
mit
76
0
__version_info__ = ('1', '0', '0') __version__ = '.'.join(__version_info__)
cinepost/Copperfield_FX
copper/cop/cop_comps.py
Python
unlicense
2,456
0.041938
from copper.cop.cop_node import CopNode import pyopencl as cl import numpy from PIL import Image class COP2_Comp_Add(CopNode): ''' This filter adds foreground over background using OpenCL ''' type_name = "add" category = "comps" def __init__(self, engine, parent): super(CLC_Comp_Add, self).__init__(engine, ...
round using OpenCL ''' type_name = "blend" category = "comps" def __init__(self, engine, parent): super(CLC_Comp_Blend, self).__init__(engine, parent)
self.program = engine.load_program("comp_blend.cl") self.__inputs__ = [None, None] self.__input_names__ = ["Input 1","Input 2"] self.addParameter("factor", float, 0.5) def bypass_node(self): factor = self.parm("factor").evalAsFloat() if factor <= 0.0: self.log("Bypassing with node %s at input 0" % (s...
shishaochen/TensorFlow-0.8-Win
tensorflow/contrib/learn/python/learn/estimators/__init__.py
Python
apache-2.0
1,777
0.00619
"""Scikit Flow Estimators.""" # Copyright 2015-present The Scikit Flow 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/L...
assifier from tensorflow.contrib.learn.python.learn.estimators.rnn import TensorFlowRNNRegressor from tensorflow.contrib.learn.python.learn.estimators.autoencoder import TensorFlowDNNAutoencoder from tensorflow.contrib.learn.python.learn.estimators.run_con
fig import RunConfig
codelab-mx/edi-translator
data_mining/forms.py
Python
gpl-3.0
193
0.036269
from django import forms from models import edi_address class DocumentForm(forms.ModelForm): docfile = forms.FileField(
)
class Meta: model = edi_address fields = ["docfile",]
bmazin/ARCONS-pipeline
examples/Pal2012-crab/enhancementPhaseP1.py
Python
gpl-2.0
21,133
0.022903
from matplotlib import rcParams, rc from spuriousRadioProbRangeP1 import
probsOfGRP from util import mpfit from util.fitFunctions import gaussian import matplotlib.pyplot as plt import numpy as np import matplotlib import scipy.stats import tables import scipy.special def fitGauss(xdata,ydata,yerr,flatLine=False): nBins=100 amplitude = .5*np.max(ydata) x_offset = xdata[np.ar...
flatLine == True: amplitude = 0 fixed[0:3] = [True]*3 params=[sigma, x_offset, amplitude, y_offset] # First guess at fit params errs = yerr errs[np.where(errs == 0.)] = 1. quiet = True parinfo = [ {'n':0,'value':params[0],'limits':[.0001, .1], 'limited':[True,True],'fixed':fixed[...
google/mirandum
alerts/main/migrations/0020_recentactivity.py
Python
apache-2.0
895
0.002235
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0019_auto_20170521_1332'), ] ...
ields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('timestamp', models.DateTimeField()), ('type', models.CharField(max_length=255, choices=[(b'follow', b'Followers/Subscribers'), (b'support', b'Recurring Support')])), ('dat...
danforthcenter/plantcv
tests/plantcv/visualize/test_auto_threshold_methods.py
Python
mit
558
0
import pytest import cv2 from plantcv.plantcv.visualize import auto_threshold_methods def test_auto_threshold_methods_bad_input(visualize_test_data): """Test for PlantCV.""" img = cv2.imread(visualize_test_data.small_rgb_img) with pytest.ra
ises(RuntimeError): _ = auto_threshold_methods(gray_img=img) def test_auto_threshold_methods(visualize_test_data): """Test for PlantCV.""" img = cv2.imread(visualize_test_data.small_
gray_img, -1) labeled_imgs = auto_threshold_methods(gray_img=img) assert len(labeled_imgs) == 5
jortel/gofer
test/unit/messaging/adapter/test_url.py
Python
lgpl-2.1
4,053
0.000247
# 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...
password) test.assertEqual(url.path, self.path) TESTS = [ Test('qpid+amqp://elmer:fudd@blue:5000/all', adapter='qpid', scheme='amqp', host='blue', port=5000, userid='elmer', password='fudd', path='all'), Test('amq
p://elmer:fudd@yellow:1234//', scheme='amqp', host='yellow', port=1234, userid='elmer', password='fudd', path='/'), Test('amqp://green:5678/all/good', scheme='amqp', host='green', port=5678, path='all/good'), Test('amqp://...
akintolga/superdesk-core
superdesk/activity.py
Python
agpl-3.0
10,291
0.002624
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import datet...
, 'filter': {'_created': {'$gte': utcnow() - datetime.timedelta(days=1)}} } superdesk.register_default_user_preference('email:notification', { 'type': 'bool', 'enabled': True, 'default': True, 'label': 'Send notifications via email', 'category': 'notifications', ...
def on_update(self, updates, original): """ Called on the patch request to mark a activity/notification/comment as having been read and nothing else :param updates: :param original: :return: """ user = getattr(g, 'user', None) if not user: ...
guillaume-philippon/aquilon
lib/aquilon/worker/commands/map_service.py
Python
apache-2.0
3,474
0.001727
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
er.dbwrappers.network import get_network_byip class CommandMapService(BrokerCommand): required_parameters = ["service", "instance"] def doit(self, session, dbmap, dbinstance, dblocation, dbnetwork, dbpersona, dbenv): if not dbmap: dbmap = ServiceMap(service_instance=dbinstan...
k=dbnetwork, personality=dbpersona, host_environment=dbenv) session.add(dbmap) def render(self, session, logger, service, instance, archetype, personality, host_environment, networkip, justification, reason, user, **kwargs): dbinstanc...
GoogleCloudPlatform/opentelemetry-operations-python
opentelemetry-exporter-gcp-trace/tests/test_cloud_trace_exporter.py
Python
apache-2.0
28,235
0.000106
# Copyright 2021 The OpenTelemetry 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 agreed t...
# pylint: disable=too-many-public-methods class TestCloudTraceSpanExporter(unittest.TestCase): def setUp(self): self.client_patcher = mock.patch( "opentelemetry.exporter.cloud_trace.TraceServiceClient" ) self.client_patcher.start() def tearDown(self): self.client_pat...
ls.project_id = "PROJECT" cls.attributes_variety_pack = { "str_key": "str_value", "bool_key": False, "double_key": 1.421, "int_key": 123, } cls.extracted_attributes_variety_pack = ProtoSpan.Attributes( attribute_map={ "s...
jmelesky/omwllf
omwllf.py
Python
isc
17,912
0.00709
#!/usr/bin/env python3 from struct import pack, unpack from datetime import date from pathlib import Path import os.path import argparse import sys import re configFilename = 'openmw.cfg' configPaths = { 'linux': '~/.config/openmw', 'freebsd': '~/.config/openmw', 'darwin': '~/Libra...
oldGetRecords(filename, rectype): return ( r for r in readRecords(filename) if r['type'] == rectype ) def getRecords(filename, rectypes): numtypes = len(rectypes) retval = [ [] for x in range(numtypes) ] for r in readRecords(filename): if r['type'] in rectypes:
for i in range(numtypes): if r['type'] == rectypes[i]: retval[i].append(r) return retval def packStringSubRecord(lbl, strval): str_bs = packString(strval) + bytes(1) l = packLong(len(str_bs)) return packString(lbl) + l + str_bs def packIntSubRecord(lbl, num...
pavithranrao/projectEuler
projectEulerPython/problem001.py
Python
mit
429
0
#!/bin/python import sys def getSumOfAP(n, m
ax): size = (max - 1) // n return (size * (n + size * (n)) / 2) def getSumOfMultiples(n): return (getSumOfAP(3, n) + getSumOfAP(5, n) - getSumOfAP(15, n)) def main(): numInputs = int(raw_input().strip()) for idx in xrange(numInputs): n = in
t(raw_input().strip()) ans = getSumOfAP(n) print(ans) if __name__ == '__main__': main()
schlueter/ansible-lint
lib/ansiblelint/rules/MismatchedBracketRule.py
Python
mit
1,497
0
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # 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...
# The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE ...
IABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ansiblelint import AnsibleLintRule class MismatchedBracketRule(AnsibleLintRule): id = 'ANSIBLE0003' shortdesc = 'Mismatched { and }' ...
odoousers2014/odoo_addons-2
clv_tray/wkf/clv_tray_wkf.py
Python
agpl-3.0
3,291
0.009116
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
, required=True, readonly=True, default=lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S')) date_activation = fields.Datetime("Activation date", required=False, readonly=False) dat
e_inactivation = fields.Datetime("Inactivation date", required=False, readonly=False) date_suspension = fields.Datetime("Suspension date", required=False, readonly=False) state = fields.Selection([('new','New'), ('active','Active'), ('inactive','Inacti...
Jumpscale/ays_jumpscale8
tests/test_services/test_validate_delete_models/actions.py
Python
apache-2.0
2,695
0.005937
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected ""
" # some default logic for simple actions return { 'test': ['install'] } def test(job): """
Tests parsing of a bp with/without default values """ import sys RESULT_OK = 'OK : %s' RESULT_FAILED = 'FAILED : %s' RESULT_ERROR = 'ERROR : %s %%s' % job.service.name model = job.service.model model.data.result = RESULT_OK % job.service.name test_repo_path = j.sal.fs.joinPaths(j.dirs....
codecakes/algorithms
algorithms/code30DaysImp/helper/quicksort.py
Python
mit
1,313
0.006855
#!/bin/python def swap(findex, sindex, ar): ar[findex], ar[sindex] = ar[sindex], ar[findex] def partition(ar, lo, hi): '''3 way djisktra partition method''' start = lo pivotIndex = (lo+hi)//2 # take the elemet @ hi as the
pivot and swap it to pivotIndex position swap(pivotIndex, hi, ar) pivotIndex = hi pivot = ar[pivotIndex] eq = lo for index in xrange(lo, hi): if (ar[eq] == pivot): eq += 1 if (ar[index] < pivot and index < pivotIndex): swap(index, lo, ar) lo += 1 ...
ar): '''Iterative unstable in-place sort''' n = len(ar) hi = n-1 lo = 0 stack = [(lo, hi)] while stack: lo, hi = stack.pop() pivot = partition(ar, lo, hi) if lo<pivot-1: stack.insert(0, (lo, pivot-1)) if pivot+1<hi: stack.insert(0, (pivot+1...
leakim/svtplay-dl
lib/svtplay_dl/service/vg.py
Python
mit
2,200
0.001364
from __future__ import absolute_import import re import json import copy import os from svtplay_dl.service impor
t Service, OpenGraphThumbMixin from svtplay_dl.utils.urllib import urlpar
se from svtplay_dl.utils import filenamify from svtplay_dl.fetcher.http import HTTP from svtplay_dl.fetcher.hds import hdsparse from svtplay_dl.fetcher.hls import HLS, hlsparse from svtplay_dl.error import ServiceError class Vg(Service, OpenGraphThumbMixin): supported_domains = ['vg.no', 'vgtv.no'] def get(s...
StackStorm/st2cd
actions/kvstore.py
Python
apache-2.0
1,061
0.000943
from st2actions.runners.pythonrunner import Action from st2client.client import Client # Keep Compatability with 0.8 and 0.11 until st2build is upgraded try: from st2client.models.datastore import KeyValuePair except ImportError: from st2client.models.keyvalue import KeyValuePair class KVPAction(Action): ...
ot kvp: raise Exception('Key error with %s.' % key) return kvp.value else: instance = client.keys.get_by_name(key) or KeyValuePair() instance.id = key instance.name = key
instance.value = value kvp = client.keys.update(instance) if action in ['create', 'update'] else None if action == 'delete': return kvp else: return kvp.serialize()
PNNutkung/Coursing-Field
index/views.py
Python
apache-2.0
876
0.004566
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Course, FeaturedCourse # Create your views here. def index(req): mostPopularCourses = Course.objects.raw('SELECT * FROM mainmodels_course as main_course JOIN (SELECT main_tran.courseID, COU...
ourse.c
ourseID = main_count.courseID LIMIT 10;') featureCourses = FeaturedCourse.objects.raw('SELECT * FROM mainmodels_featuredcourse as main_feat JOIN mainmodels_course as main_course ON main_feat.course_id = main_course.courseID LIMIT 10;') return render(req, 'index/main.html', {'pageTitle': 'Coursing Field', 'mostP...
italomaia/turtle-linux
games/FunnyBoat/run_game.py
Python
gpl-3.0
3,190
0.006583
#!/usr/bin/python import pygame import math import random import sys import PixelPerfect from pygame.locals import * from water import Water from menu import Menu from game import Game from highscores import Highscores from options import Options import util from locals import * import health import cloud impor...
if SCREEN_FULLSCREEN: scr_options += FULLSCREEN screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),scr_options ,32) pygame.display.set_icon(util.load_image("kuvake")) pygame.display.set_caption("Trip on the Funny Boat") init() joy = None if pygame.joystick.get_count() > 0: ...
nny_Boat") if Variables.music: pygame.mixer.music.play(-1) except: # It's not a critical problem if there's no music pass pygame.time.set_timer(NEXTFRAME, 1000 / FPS) # 30 fps Water.global_water = Water() main_selection = 0 while True: main_selection =...
dvitme/odoo-addons
portal_partner_fix/__openerp__.py
Python
agpl-3.0
1,565
0.000639
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
e implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Af
fero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Portal Partner Fix', 'version': '8.0.1.0.0', 'category': '', 'sequence': 14, 'summary': '', 'descript...
nacc/autotest
client/deps/grubby/grubby.py
Python
gpl-2.0
518
0.003861
#!/usr/bin/python import os from autotest.client import utils versi
on = 1 def setup(tarball, topdir): srcdir = os.path
.join(topdir, 'src') utils.extract_tarball_to_dir(tarball, srcdir) os.chdir(srcdir) utils.make() os.environ['MAKEOPTS'] = 'mandir=/usr/share/man' utils.make('install') os.chdir(topdir) pwd = os.getcwd() tarball = os.path.join(pwd, 'grubby-8.11-autotest.tar.bz2') utils.update_version(os.path.joi...
amcat/amcat
amcat/models/coding/tests/codingruletoolkit.py
Python
agpl-3.0
7,493
0.001735
########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # ...
est.create_test_schema_with_fields()[0], tree) def test_parse(self): import functools
o1, o2 = amcattest.create_test_code(), amcattest.create_test_code() schema_with_fields = amcattest.create_test_schema_with_fields() schema = schema_with_fields[0] codebook = schema_with_fields[1] text_field = schema_with_fields[2] number_field = schema_with_fields[3] ...
lazzyCloud/SLR
db2owl/course_json2owl.py
Python
agpl-3.0
4,862
0.004319
import json from owlready import * # input parameters file_path = sys.argv[1] onto_path = sys.argv[2] # load ontology onto = get_ontology(onto_path).load() # course found list course_ids = [] # for each course, find the active version (avoid multi instances of one course) with open(file_path + '/modulestore.active_...
xml_id) # set display name property if 'display_name' in block['fields'].keys(): obj_display_name = block['fields']['display_name'] getattr(temp_obj,o
bj_name+'_display_name').append(obj_display_name) # if this instance is a course if obj_name == 'course': temp_id = obj_xml_id + str(one_course[1]) course_org = temp_id.split(':')[-1].split('+')[0] course_tag...
garretlh/nimbus-drivers
src/main/python/nimbusdrivers/ws23xx.py
Python
gpl-3.0
72,031
0.004776
#!usr/bin/env python # # Copyright 2013 Matthew Wall # See the file LICENSE.txt for your full rights. # # Thanks to Kenneth Lavrsen for the Open2300 implementation: # http://www.lavrsen.dk/foswiki/bin/view/Open2300/WebHome # description of the station communication interface: # http://www.lavrsen.dk/foswiki/bin/vie...
river introduces a WindConversion object that uses open2300/wview decoding so that wind speeds match that of open2300/wview. ws2300 1.8 incorrectly uses bcd2num instead of bin2num. This bug is fixed in this driver. The memory map indicates the following: addr smpl description 0x527 0 Wind overflow flag: 0 = nor...
code: 0=min, 1=--.-, 2=OFL 0x529 0 Windspeed: binary nibble 0 [m/s * 10] 0x52A 0 Windspeed: binary nibble 1 [m/s * 10] 0x52B 0 Windspeed: binary nibble 2 [m/s * 10] 0x52C 8 Wind Direction = nibble * 22.5 degrees 0x52D 8 Wind Direction 1 measurement ago 0x52E 9 Wind Direction 2 measurement ago 0x52F 8...
Com-Ericmas001/py-userbase
py_userbase/userbase_models.py
Python
mit
2,746
0.00437
import datetime class AuthenticationInfo: def __init__(self, password, email): self.Password = password self.Email = email class ProfileInfo: def __init__(self, display_name): self.DisplayName = display_name class Token: def __init__(self, id_token, valid_until): self.Id =...
self.IdUser = id_user sel
f.Username = username self.DisplayName = display_name self.Groups = groups class Group: def __init__(self, id_group, name): self.Id = id_group self.Name = name class CreateUserRequest: def __init__(self, username, authentication, profile): self.Username = username ...
flavio-fernandes/networking-odl
networking_odl/fwaas/driver.py
Python
apache-2.0
2,105
0
# # Copyright (C) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
ightFwaasDriver(fwaas_base.FwaasDriverBase): """OpenDaylight FWaaS Driver This code is the backend implementation for the OpenDaylight FWaaS driver for Openstack Neutron. """ def __init__(self): LOG.debug("Initializing OpenDaylight FWaaS driver") self.client = odl_client.OpenDayli...
default policy will be applied on all the interfaces of trusted zone. """ pass def delete_firewall(self, apply_list, firewall): """Delete firewall. Removes all policies created by this instance and frees up all the resources. """ pass def updat...
i2c2-caj/CS4990
Homework/crminal/crm/migrations/0001_initial.py
Python
gpl-2.0
6,674
0.004495
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
name='
Campaign', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('description', models.TextField(null=True, blank=True)), ], ), migra...
MehmetNuri/ozgurlukicin
scripts/kargo/main.py
Python
gpl-3.0
1,129
0.004429
#!/usr/bin/python # -*- coding: utf-8 -*- import locale import os import sys from datetime import date from kargoxml import add_column script_dir = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] project_dir = os.path.split(script_dir)[0] sys.path.append(project_dir) sys.path.append(os.path.split(projec...
s.fil
ter(confirmed=1, sent=0, taken=0, version=version).order_by('date')[:limit] add_column(cdclient, date.today().isoformat(), slugify(version))
shadow/shadow-ctl
src/panel.py
Python
gpl-3.0
41,934
0.005032
""" Wrapper for safely working with curses subwindows. Based on code from the arm project, developed by Damian Johnson under GPLv3 (www.atagar.com - atagar@torproject.org) """ import os import copy import time import curses import curses.ascii import curses.textpad from threading import RLock from multiprocessing imp...
self.pauseBuffer[attr] = self.copyAttr(attr) if not suppressRedraw: self.redraw(True) return True else
: return False def getPauseTime(self): """ Provides the time that we were last paused, returning -1 if we've never been paused. """ return self.pauseTime def getTop(self): """ Provides the position subwindows are placed at within its parent. """...
Sid1057/obstacle_detector
depth_test.py
Python
mit
3,465
0.002886
#!/usr/bin/python3 import numpy as np import cv2 from collections import deque from obstacle_detector.distance_calculator import spline_dist from obstacle_detector.perspective import inv_persp_new from obstacle_detector.perspective import regress_perspecive from obstacle_detector.depth_mapper import calculate_depth...
rame = cap.read() height, width, _ = frame.shape out_height, out_width, _ = img.shape fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter( output_video_path \ if output_video_path is not None \ else 'output.avi', fourcc, 15.0, (out_width * 4, out_heigh...
t, frame = cap.read() original_frames.append(frame) img, pts1 = inv_persp_new( frame, (cx, cy), (roi_width, roi_length), spline_dist, 200) old_images.popleft() old_images.append(img) left = original_frames[-5][:, width // 2:] right = original_frames[-1][:, w...
DeltaEpsilon-HackFMI2/FMICalendar-REST
venv/lib/python2.7/site-packages/rest_framework/settings.py
Python
mit
6,264
0.000319
""" Settings for REST framework are all namespaced in the REST_FRAMEWORK setting. For example your project's `settings.py` file might look like this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.YAMLRenderer', ) 'DEFAULT...
tings = user_settings or {
} self.defaults = defaults or {} self.import_strings = import_strings or () def __getattr__(self, attr): if attr not in self.defaults.keys(): raise AttributeError("Invalid API setting: '%s'" % attr) try: # Check if present in user settings val = ...
NewsNerdsAtCoJMC/ProjectTicoTeam6
service/volunteers/migrations/0002_auto_20170314_1712.py
Python
mit
424
0
# -*-
coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-14 17:12 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('volunteers', '0001_initial'), ] operations = [ migrations.RenameField( model_...
]
ivanprjcts/equinox-spring16-API
equinox_spring16_api/equinox_spring16_api/urls.py
Python
lgpl-3.0
1,431
0.000699
"""equinox_spring16_api 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='hom...
ework import routers from equinox_api.views import ApplicationViewSet, OperationViewSet, InstancesViewSet, UserViewSet, ItemViewSet from equinox_spring16_api import settings router = routers.DefaultRouter() router.register(r'applications', ApplicationViewSet) router.register(r'operations', OperationViewSet) router....
, url(r'^', include(router.urls)), url(r'^docs/', include('rest_framework_swagger.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
ychab/privagal
privagal/gallery/tests/test_factories.py
Python
bsd-3-clause
584
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from privagal.core.utils import PrivagalTestCase from ...gal
lery.factories import GalleryFactory, ImageFact
ory class GalleryFactoryTestCase(PrivagalTestCase): def test_images_given(self): image = ImageFactory() gallery = GalleryFactory(images__images=[image]) self.timeline.add_child(instance=gallery) self.assertEqual(gallery.images.first().image, image) def test_images_default(sel...
mwalzer/Ligandomat
ligandomat/run_list_handling.py
Python
mit
2,262
0.07206
from sqlalchemy import and_ from DBtransfer import * from zlib import * #retrun compressed def generateFromDB(DBSession, InternData, tmp_name) : run_list=[] user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name) for data in user_data : if not data.run in run_list : run_list.append(da...
n_(runs_in_upload))] run_list = [x for x in runs_in_upload if x not in known_runs] #~ allRuns = getAllRuns_Filename(DBSession, Mass_specData)# in DB saved runs #~ decomruns_in_upload = decompressList(runs_in_upload) #~ for run in decomruns_in_upload : #~ if run in allRuns : #~ knownRuns.append(run) #~...
ed def usedRuns(run_list, params) : list_of_used_runs = [] runs = decompressList(run_list) for i in range(0, len(runs)) : if runs[i] in params : list_of_used_runs.append(runs[i]) return list_of_used_runs # input not compressed # output InternData objects def rowsToFill(DBSession, InternData, tmp_name, used...
riscmaster/risc_maap
risc_control/src/IRIS_DF_Controller.py
Python
bsd-2-clause
6,110
0.022913
#!/usr/bin/env python '''====================================================== Created by: D. Spencer Maughan Last updated: May 2015 File name: IRIS_DF_Controller.py Organization: RISC Lab, Utah State University Notes: ======================================================''' import roslib;...
jectories, GetTraj, queue_size=1, buff_size=2**24) sub_Batt
= rospy.Subscriber('/apm/status' , Status, GetBatt) sub_status = rospy.Subscriber('/controller_status' , Bool, GetStatus) Basic_Controller() r.sleep()
DestructHub/ProjectEuler
Problem030/Python/solution_1.py
Python
mit
1,884
0.010144
#!/usr/bin/env python # coding=utf-8 # Python Script # # Copyleft © Manoel Vilela # # from functools import reduce """ Digit fifth powers Problem 30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + ...
8 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """ """ Prova de um cara lá no fórum do PE sobre apenas ser necessário considerar números de 6 dígitos ou menos. Proof that one need only consider
numbers 6 digits or less: If N has n digits, then 10^{n-1} <= N. If N is the sum of the 5th powers of its digits, N <= n*9^5. Thus, 10^{n-1} <= n*9^5. We now show by induction that if n>=7, then 10^{n-6} > n. 1) Basis step (n=7): 10^{7-6} = 10 > 7. 2) Induction step: suppose 10^{n-6} > n for some n>=7. Show t...
gertingold/scipy
scipy/stats/_continuous_distns.py
Python
bsd-3-clause
220,936
0.000751
# -*- coding: utf-8 -*- # # Author: Travis Oliphant 2002-2011 with contributions from # SciPy Developers 2004-2011 # from __future__ import division, print_function, absolute_import import warnings import numpy as np from scipy._lib.doccer import (extend_notes_in_docstring, ...
cdf(x) def _sf(self, x): return _norm_sf(x) def _logsf(self, x): return _norm_logsf(x) def _ppf(self, q): return _norm_ppf(q) def _i
sf(self, q): return _norm_isf(q) def _stats(self): return 0.0, 1.0, 0.0, 0.0 def _entropy(self): return 0.5*(np.log(2*np.pi)+1) @replace_notes_in_docstring(rv_continuous, notes="""\ This function uses explicit formulas for the maximum likelihood estimation of the n...
Exterminus/harpia
harpia/bpGUI/runCmd.py
Python
gpl-2.0
6,533
0.002756
# -*- coding: utf-8 -*- # [HARPIA PROJECT] # # # S2i - Intelligent Industrial Systems # DAS - Automation and Systems Department # UFSC - Federal University of Santa Catarina # Copyright: 2006 - 2007 Luis Carlos Dill Junges (lcdjunges@yahoo.com.br), Clovis Peruchi Scotti (scotti@ieee.org), # Guilh...
'cmdString', 'BackgroundColor',
'BorderColor', 'HelpView', 'enIsntZero' ] handlers = [ 'on_cancel_clicked', 'on_prop_confirm_clicked', 'on_BackColorButton_clicked', 'on_BorderColorButton_clicked' ] top_window = 'Properties' G...
xaccc/videoapiserver
testNotifyTCPServer.py
Python
gpl-2.0
1,234
0.024311
#coding=utf-8 #-*- encoding: utf-8 -*- import tornado.ioloop import tornado.iostream import socket import struct import NotifyTCPServer def readPacketHeader(): stream.read_bytes(NotifyTCPServer.PACKET_HEADER_LEN, parsePacketHeader) def parsePacketHeader(data): sign,cmd,bodySize = struct.unpack('>2sHH', data) p...
def send_packet(cmd, msg): data = bytes(msg) stream.write(struct.pack(">2sHH", "NT", cmd, len(data))) stream.write(data) def send_request(): readPacketHeader() send_register('591410cbf9614cbf9aaa
c4a871ddb466') command=0 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) stream = tornado.iostream.IOStream(s) stream.connect(("localhost", 9002), send_request) #stream.connect(("221.180.20.232", 9002), send_request) tornado.ioloop.IOLoop.instance().start()
specht/proteomatic-scripts
transpose-dna.defunct.py
Python
gpl-3.0
911
0.009879
#! /usr/bin/env python import sys, os sys.path.append('./include/python') import proteomatic import string import re class TransposeDna(proteomatic.ProteomaticScript): def run(self): # convert all characters to upper case # Attention: parameters are Unicode
because of the JSON parser # used behind the scenes, convert
nucleotides to ASCII string dna = str(self.param['nucleotides']).upper() # remove invalid characters dna = re.sub('[^ACGT]', '', dna) # reverse sequence dna = dna[::-1] # replace nucleotides dna = dna.translate(string.maketrans('ACGT', 'TGCA')) # output t...
xrage/oauth2app-mongoDb
oauth2app/models.py
Python
mit
5,945
0.000168
#-*- coding: utf-8 -*- """OAuth 2.0 Django Models""" import time from hashlib import sha512 from uuid import uuid4 from django.db import models from django.contrib.auth.models import User from .consts import CLIENT_KEY_LENGTH, CLIENT_SECRET_LENGTH from .consts import SCOPE_LENGTH from .consts import ACCESS_TOKEN_LE...
odels.CharField( unique=True, max_length=CLIENT_SECRET_LENGTH, default=KeyGenerator(CLIENT_SECRET_LENGTH)) redir
ect_uri = models.URLField(null=True) class AccessRange(models.Model): """Stores access range data, also known as scope. **Args:** * *key:* A string representing the access range scope. Used in access token requests. **Kwargs:** * *description:* A string representing the access range desc...
Hexacker/Dexacker
Dexacker.py
Python
gpl-2.0
1,733
0.030006
#!/usr/bin/env python #______________________________________# #Dexacker is an open source tool developed by Abdelmadjd Cherfaoui #Dexacker is designed for Educational Stuff to do a LEGAL DDOS Test and the developers is # not responsible for ILLEGAL USES #Contacting using:@Hexacker | fb.com/Hexacker #http://www.hackerc...
want to Attack: ")) message = raw_input("Write the message you want to send it: ") connections = int(raw_input("How many beat you want to make: " )) IP = socket.gethostbyname(host) #/ #The Attacking Function def Attack(): attack = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: attack.connect((host,80)) ...
P,port)) attack.send(message); except socket.error,msg: print "Connection Failed" print "DDOS Attack Lunched" attack.close() for i in range(1,connections): Attack() print "______________________________________" print "The Operation is finished" #this is the restaring function def Restart(): program = sys.ex...
jawilson/home-assistant
homeassistant/components/plant/group.py
Python
apache-2.0
421
0
"""Describe group states.""" from homeassistant.components.group import GroupIntegration
Registry f
rom homeassistant.const import STATE_OK, STATE_PROBLEM from homeassistant.core import HomeAssistant, callback @callback def async_describe_on_off_states( hass: HomeAssistant, registry: GroupIntegrationRegistry ) -> None: """Describe group on off states.""" registry.on_off_states({STATE_PROBLEM}, STATE_OK)...
394954369/horizon
openstack_dashboard/dashboards/project/volumes/volumes/tests.py
Python
apache-2.0
49,698
0.001127
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
'], formData['name'], formData['description'], '', metadata={}, snapshot_id=None,
image_id=None, availability_zone=None, source_volid=None).AndReturn(volume) self.mox.ReplayAll() url = reverse('horizon:project:volumes:volumes:create') res = self.client.post(url, formData) redirec...
mattvryan/audiofile
afmq/__init__.py
Python
mit
3,351
0.021486
#!/usr/bin/env python # encoding: utf-8 """ __init__.py The MIT License (MIT) Copyright (c) 2013 Matt Ryan 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 ...
is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES 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 SOFTWAR...
dhruvilpatel/citation
citation/management/commands/validate_urls.py
Python
gpl-3.0
389
0.002571
import loggi
ng from django.core.management.base import BaseCommand from citation.ping_urls import verify_url_status logger = logging.getLogger(__name__) class Command(BaseCommand): help = '''Method that check if the code archived urls are active and working or not ''' def handle(self, *args, **options): verif...
dation completed")
clicheio/cliche
cliche/web/adv_search.py
Python
mit
2,111
0
from flask import Blueprint, flash, redirect, render_template, request, url_for from sqlalchemy.orm.exc import NoResultFound from ..sqltypes import HashableLocale as Locale from ..work import Trope, Work from .db import session adv_search_bp = Blueprint('adv_search', __name__) @adv_search_bp.route('/', methods=['P...
about, category, detail in query: if about == 'info': if category == 'media': media_list.append(detail) elif about == 'trope': try: trope = session.query(Trope).get(detail)
except NoResultFound: return error_redirect if trope_filter is None: trope_filter = Work.tropes.any(Trope.id == trope.id) else: trope_filter = trope_filter & \ Work.tropes.any(Trope.id == trope.id) if not media_lis...
ajportier/raspi-gpio-work
light-toggle/server.py
Python
gpl-2.0
1,463
0.005468
#!/usr/bin/env python from flask import (Flask, request, render_template) from flask.ext import restful from flask.ext.restful import reqparse import pickle SETTINGS_P = 'settings.p' app = Flask(__name__) api = restful.Api(app) def get_settings(): settings = {'state':'off'} try: settings = pickle.l...
s SetState(restful.Resource): def get(self): settings = get_settings()
parser = reqparse.RequestParser() parser.add_argument('value', type=str, location='args', choices=['on','off']) args = parser.parse_args() value = args['value'] if value: set_state(value) settings = get_settings() print "Setting stat...
JulyKikuAkita/PythonPrac
cs15211/NestedListWeightSum.py
Python
apache-2.0
4,780
0.004603
__source__ = 'https://leetcode.com/problems/nested-list-weight-sum/' # https://github.com/kamyu104/LeetCode/blob/master/Python/nested-list-weight-sum.py # Time: O(n) # Space: O(h) # # Description: Leetcode # 339. Nested List Weight Sum # # Given a nested list of integers, return the sum of all integers in the list wei...
sum += e.isInteger() ? e.getInteger() * depth : dfs(e.getList(), depth + 1); } return sum; } } # 2ms 97% class Solution { public int depthSum(List<NestedInteger> nestedList) { int sum = 0; for (NestedInteger ni
: nestedList) { sum += depthSum(ni, 1); } return sum; } private int depthSum(NestedInteger ni, int depth) { if (ni.isInteger()) { return ni.getInteger() * depth; } else { int sum = 0; for (NestedInteger n : ni.getList()) { ...
briancline/softlayer-python
SoftLayer/CLI/rwhois/edit.py
Python
mit
1,891
0
"""Edit the RWhois data on the account.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from S
oftLayer.CLI import exceptions import click @click.command() @click.option('--abuse', help='Set the abuse email address') @click.option('--address1', help='Update the address 1 field') @click.option('--address2', help='Update the address 2 field') @click.option('--city', help='Set the city name') @click.option('--co...
ck.option('--firstname', help='Update the first name field') @click.option('--lastname', help='Update the last name field') @click.option('--postal', help='Set the postal code field') @click.option('--public/--private', default=None, help='Flags the address as a public or private residence.'...
rero/reroils-app
tests/ui/locations/test_locations_mapping.py
Python
gpl-2.0
1,616
0
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # # This program is free software: you can re
dis
tribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNE...
wpjunior/terminator
terminatorlib/terminal_popup_menu.py
Python
gpl-2.0
11,983
0.004423
#!/usr/bin/env python2 # Terminator by Chris Jones <cmsj@tenshu.net> # GPL v2 only """terminal_popup_menu.py - classes necessary to provide a terminal context menu""" import string from gi.repository import Gtk from version import APP_NAME from translation import _ from encoding import TerminatorEncoding from termi...
url = terminal.vte.match_check_event(event) button = event.button time = event.time else: time = 0 button = 3 if url and url[0]: dbg("URL matches id: %d" % url[1]) if not url[1] in terminal.matches.values(): ...
None if url[1] == terminal.matches['email']: nameopen = _('_Send email to...') namecopy = _('_Copy email address') elif url[1] == terminal.matches['voip']: nameopen = _('Ca_ll VoIP address') namecopy = _('_Copy VoIP address') ...
yaelatletl/gj_e3d_api
py_gjapi.py
Python
lgpl-3.0
13,032
0.028392
# Game Jolt Trophy for Python # by viniciusepiplon - vncastanheira@gmail.com # version 1.1 # Python 3.x stable # Python 2.7 unstable # This is a general Python module for manipulating user data and # trophies (achievments) on GameJolt. # Website: www.gamejolt.com # This program is free software: you can redistribute ...
only* is set to True, only scores for the player stored on the object will be returned. """ URL = self.URL+'/scores/?format=json&game_id='+str(self.game_id) if user_info_only: URL += '&username='+str(self.us
ername)+'&user_token='+str(self.user_token) # ID of the score table if table_id: URL += '&table_id='+str(table_id) # Maximum number of scores should be 100 according with the GJAPI if limit > 100: limit = 100 URL += '&limit='+str(limit) return self.setSignatureAndgetJSONResponse(URL) def addScores(s...
arky/pootle-dev
pootle/apps/pootle_terminology/templatetags/terminology_tags.py
Python
gpl-2.0
1,119
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009, 2013 Zuza Software Foundation # # This file is part of Pootle. # # Pootle is free software; you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of
the License, or (at your option) any later # version. # # Pootle 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 GNU Gener
al Public License for more details. # # You should have received a copy of the GNU General Public License along with # Pootle; if not, see <http://www.gnu.org/licenses/>. from django import template register = template.Library() @register.inclusion_tag('terminology/term_edit.html', takes_context=True) def render_t...
BBN-Q/pyqgl2
test/test_basic_mins.py
Python
apache-2.0
34,859
0.004131
# Copyright 2016 by Raytheon BBN Technologies Corp. All Rights Reserved. ''' Test the qgl2/basic_sequences to ensure they replicate the QGL1 functionality. ''' import datetime import unittest import numpy as np from math import pi import random from pyqgl2.main import compile_function from pyqgl2.qreg import QRegiste...
flat_top_gaussian(edge, riseFall, length=l, amp=amp, phase=phase), Barrier(controlQ, targetQ), MEAS(controlQ), MEAS(targetQ) ] # Seq2 for l in lengths: expected_seq += [ qwait(channels=(controlQ, targetQ)...
scotwk/cloud-custodian
c7n/resources/elb.py
Python
apache-2.0
29,736
0.000303
# Copyright 2015-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
self.config.region, self.config.account_id, r[self.resource_type.id]) def get_source(self, source_type): if source_type == 'describe': return DescribeELB(self) return super(ELB, self).get_source(source_type) class DescribeELB(DescribeSource): def au...
self.manager.retry) return resources def _elb_tags(elbs, session_factory, executor_factory, retry): def process_tags(elb_set): client = local_session(session_factory).client('elb') elb_map = {elb['LoadBalancerName']: elb for elb in elb_set} while True: try: ...
Katsuya-Ishiyama/simulation
strategy/strategy.py
Python
mit
2,013
0.00149
#! /usr/bin/python # -*- coding: utf-8 -*- """ Created on Fri Jan 27 18:31:59 2017 @author: katsuya.ishiyama """ from numpy import random # Definition of module level constants SUCCESS_CODE = 1 FAILURE_CODE = 0 class Strategy(): def __init__(self, n): _success_probability = _generate_success_proba...
urn self._result_of_trial def _get_trial_result(p): _trial_result = random.choice([FAILURE_CODE, SUCCESS_CODE], size=1, p=[1 - p, p]) return _trial_result[0] def _generate_suc
cess_probability(size): return random.sample(size)
luoxufeiyan/python
burness/0013/get_photos.py
Python
mit
1,039
0.043095
import urllib2 from HTMLParser import HTMLParser from traceback import print_exc from sys import stderr class _DeHTMLParser(HTMLParser): ''' 利用HTMLParse来解析网页元素 ''' def __init__(self): HTMLParser.__init__(self) self.img_links = [] def handle_starttag(self, tag, attrs): if tag == 'img': # print(attrs) ...
le=stderr) return text def main(): html = urllib2.urlopen('http://tieba.baidu.com/p/2166231880') content = html.read() print(dehtml(content)) i = 0 for img_list in dehtml(content): img_content = urllib2.urlopen(im
g_list).read() path_name = str(i)+'.jpg' with open(path_name,'wb') as f: f.write(img_content) i+=1 if __name__ == '__main__': main()
jepio/pers_engine
persengine.py
Python
gpl-2.0
733
0.002729
#!/usr/bin/env python2 """ This is the main module, used to launch the persistency engine """ #from persio import iohandler import persui.persinterface as ui def main(): """ Launches the user interface, and keeps it on.""" interface = ui.Persinterface() while True: interface.run() if __name__ == ...
1), (0, 6, 2, 8)] graph_data = [graph_data1, graph_data2] name = "tree.xml" root = iohandler.xh.createindex(keynames) for i in xrange(2): iohandler.xh.creategraph(root, graph_data[i], keynames[i], 2) iohandler.xh.wr
itexml(root, name) """
hakonsbm/nest-simulator
pynest/nest/tests/test_sp/test_get_sp_status.py
Python
gpl-2.0
3,006
0
# -*- coding: utf-8 -*- # # test_get_sp_status.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 Lice...
ve, } nodes = nest.Create(neuron_model, 2, {'synaptic_elements': synaptic_elements} ) all = nest.GetStructuralPlasticityStatus() print(all) assert ('structural_plasticity_synapses' in all) assert ('syn1' in all['structural_p...
terval'] == 1000) sp_synapses = nest.GetStructuralPlasticityStatus( 'structural_plasticity_synapses' ) print(sp_synapses) syn = sp_synapses['syn1'] assert ('pre_synaptic_element' in syn) assert ('post_synaptic_element' in syn) assert (syn['pre_synaptic_element'] == 'Axon_ex') as...
n2o/dpb
dpb/apps.py
Python
mit
108
0
from filer.apps import FilerConfig class MyFi
lerConfig(F
ilerConfig): verbose_name = "Dateiverwaltung"
akehrer/fiddle
fiddle/controllers/PyConsole.py
Python
gpl-3.0
5,579
0.001255
# Copyright (c) 2015 Aaron Kehrer # Licensed under the terms of the MIT License # (see fiddle/__init__.py for details) import os import unicodedata from io import StringIO from PyQt4 import QtCore, QtGui from fiddle.config import EDITOR_FONT, EDITOR_FONT_SIZE class PyConsoleTextBrowser(QtGui.QTextBrowser): def ...
ore.Qt.TextEditorInteraction) def keyPressEvent(self, event):
if self.process is not None: # Skip keys modified with Ctrl or Alt if event.modifiers() != QtCore.Qt.ControlModifier and event.modifiers() != QtCore.Qt.AltModifier: # Get the insert cursor and make sure it's at the end of the console cursor = self.textCur...
alex/solum
solum/openstack/common/db/sqlalchemy/models.py
Python
apache-2.0
3,969
0
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Piston Cloud Computing, Inc. # Copyright 2012 Cloudscaling Group, Inc. # All Rights Reserved. # # Licens...
ssion.add(self) session.flush() def __setitem__(self, key, value): setattr(self, key, value) def __getitem__(self, key): return getattr(self, key) def get(self, key, default=None): return getattr(self, key, default) @property def _extra_keys(self):
"""Specifies custom fields Subclasses can override this property to return a list of custom fields that should be included in their dict representation. For reference check tests/db/sqlalchemy/test_models.py """ return [] def __iter__(self): columns =...
davidam/python-examples
bokeh/openstreetmap.py
Python
gpl-3.0
1,245
0
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <davidam@gnu.org> # Maintainer: David Arroyo Menéndez <davidam@gnu.org> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
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 # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file CO...
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, from bokeh.plotting import figure, show, output_file from bokeh.tile_providers import CARTODBPOSITRON output_file("tile.html") # range bounds supplied in web mercator coordinates p = figure(x_range=(-2000000, 6000000), y_range=(...
talkincode/toughlogger
toughlogger/console/handlers/password_forms.py
Python
agpl-3.0
789
0.006784
#!/usr/bin/env python # coding=utf-8 from toughlogger.common import pyforms from
toughlogger.common.pyforms import rules from toughlogger.com
mon.pyforms.rules import button_style, input_style password_update_form = pyforms.Form( pyforms.Textbox("tra_user", description=u"管理员名", size=32, readonly="readonly", **input_style), pyforms.Password("tra_user_pass", rules.len_of(6, 32), description=u"管理员新密码", size=32,value="", required="required", **input_st...
jazkarta/edx-platform-for-isc
lms/djangoapps/certificates/models.py
Python
agpl-3.0
17,158
0.000816
# -*- coding: utf-8 -*- """ Certificates are created for a student and an offering of a course. When a certificate is generated, a unique ID is generated so that the certificate can be verified later. The ID is a UUID4, so that it can't be easily guessed and so that it is unique. Certificates are generated in batches...
class ExampleCertificateSet(TimeStampedModel): """A set of example certificates. Example certificates are used to verify that certificate generation is working for a particular course. A particular course may have several kinds of certificates (e.g. honor and verified), in which case we generat...
ample certificates for the course. """ course_key = CourseKeyField(max_length=255, db_index=True) class Meta: # pylint: disable=missing-docstring, old-style-class get_latest_by = 'created' @classmethod @transaction.commit_on_success def create_example_set(cls, course_key): ""...
obulpathi/reversecoin
reversecoin/bitcoin/utils.py
Python
gpl-2.0
4,697
0.004897
#!/usr/bin/env python import binascii import hashlib from reversecoin.bitcoin.key import CKey as Key from reversecoin.bitcoin.base58 import encode, decode def myhash(s): return hashlib.sha256(hashlib.sha256(s).digest()).digest() def myhash160(s): h = hashlib.new('ripemd160') h.update(hashlib.sha256(s).di...
ve version byte: 0x00 for Main Netwo
rk hash160_address = extended_address[1:] return hash160_address def public_key_hex_to_pay_to_script_hash(public_key_hex): script = "41" + public_key_hex + "AC" return binascii.unhexlify(script) def address_to_pay_to_pubkey_hash(address): print "Not implemented >>>>>>>>>>>>>>>>>>>" exit(0) de...
jon2718/ipycool_2.0
edge.py
Python
mit
4,743
0.002321
from pseudoregion import * class Edge(PseudoRegion): """EDGE Fringe field and other kicks for hard-edged field models 1) edge type (A4) {SOL, DIP, HDIP, DIP3, QUAD, SQUA, SEX, BSOL, FACE} 2.1) model # (I) {1} 2.2-5) p1, p2, p3,p4 (R) model-dependent parameters Edge type = SOL p1: BS [T] ...
': { 'desc': 'Solenoid', 'doc': '', 'icool_model_name': 'SOL',
'parms': { 'model': { 'pos': 1, 'type': 'String', 'doc': ''}, 'bs': { 'pos': 3, 'type': 'Real', ...
michaelchu/kaleidoscope
kaleidoscope/options/order_leg.py
Python
mit
884
0.001131
from kaleidoscope.globals import SecType class OrderLeg(object): def __init__(self, quantity, contract): """ This class is an abstraction of an order leg of an option strategy. It holds the information for a single order leg as part of an entire option strategy. """ self.q...
uantity self.contract = contract def reverse(self): """ reverse the the position by negating the quantity """ self.quantity *= -1 class OptionLeg
(OrderLeg): """ Holds information of an option leg """ def __init__(self, option, quantity): self.sec_type = SecType.OPT super().__init__(quantity, option) class StockLeg(OrderLeg): """ Holds information of an stock leg """ def __init__(self, symbol, quantity): self.sec_type ...