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
PepperPD/edx-pepper-platform
lms/xblock/field_data.py
Python
agpl-3.0
885
0
""" :class:`~xblock.field_data.FieldData` subclasses used by the LMS """ from xblock.field_data import ReadOnlyFieldData, SplitFieldData from xblock.fields import Scope def lms_field_data(authored_data, student_data): """ Returns a new :class:`~xblock.field_data.FieldData` that
reads all UserScope.ONE and UserScope.ALL fields from `student_data` and all UserScope.NONE fields from `authored_data`. It also prevents writing to `authored_data`. """ authored_data = ReadOnlyFieldData(authored_data) return SplitFieldData({ Scope.content: authored_data, Scope.s...
ummary: student_data, Scope.user_state: student_data, Scope.user_info: student_data, Scope.preferences: student_data, })
aurora-pro/apex-sigma
sigma/plugins/administration/cheats/overriderategirl.py
Python
gpl-3.0
2,537
0.003176
import discord async def overriderategirl(cmd, message, args): if args: collection = 'HotCrazyOverrides' if args[0].lower() == 'disable': if message.mentions: target = message.mentions[0] target_data = {'UserID': target.id} lookup =
cmd.db.find_one(collection, target_data) if lookup: cmd.db.delete_one(collection, target_data) response = discord.Embed(color=0x66CC66,
title=f'✅ Removed {target.name} override.') else: response = discord.Embed(color=0xDB0000, title='❗ No Override Found') else: response = discord.Embed(color=0xDB0000, title='❗ No User Mentioned') else: if len(args...
swirlingsand/self-driving-car-nanodegree-nd013
p4-CarND-Advanced-Lane-Lines/methods/laneDetection/qualityControl.py
Python
mit
109
0.009174
# TODO implement a smoothing function perhaps # (Ie only accept frames within x
distance o
f previous frame)
blueyed/coveragepy
coverage/results.py
Python
apache-2.0
10,222
0.001076
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt """Results of coverage measurement.""" import collections from coverage.backward import iitems from coverage.misc import contract, format_lines, SimpleRepr clas...
self.file_reporter.filename self.statements = self.file_reporter.lines() self.excluded =
self.file_reporter.excluded_lines() # Identify missing statements. executed = self.data.lines(self.filename) or [] executed = self.file_reporter.translate_lines(executed) self.missing = self.statements - executed if self.data.has_arcs(): self._arc_possibilities = so...
shootstar/novatest
nova/cells/rpcapi.py
Python
apache-2.0
17,069
0.001055
# Copyright (c) 2012 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
delete_type=delete_type)) def instance_fault_create_at_top(self, ctxt, instance_fault): """Create an instance fault at the top.""" if not CONF.cells.enable: return instance_fault_p = jsonutils.to_primitive(instance_fault) self.cast(ctxt, self.make_msg('instance_fau...
e_fault_p)) def bw_usage_update_at_top(self, ctxt, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=None): """Broadcast upwards that bw_usage was updated.""" if not CONF.cells.enable: return bw_update_info = {'uuid': uuid, ...
vladimir-ipatov/ganeti
lib/rapi/baserlib.py
Python
gpl-2.0
17,689
0.006501
# # # Copyright (C) 2006, 2007, 2008, 2012 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This progr...
None) """ try: value = data[name] except KeyError: if default is not _DEFAULT: return default raise http.HttpBadRequest("Required parameter '%s' is missing" % name) if exptype is _DEFAULT: return value return CheckType(value, exptype, "'%s' parameter" %...
PI_ACCESS_WRITE] POST_ACCESS = [rapi.RAPI_ACCESS_WRITE] DELETE_ACCESS = [rapi.RAPI_ACCESS_WRITE] def __init__(self, items, queryargs, req, _client_cls=None): """Generic resource constructor. @param items: a list with variables encoded in the URL @param queryargs: a dictionary with additional options...
ric2b/Vivaldi-browser
chromium/build/android/pylib/utils/time_profile.py
Python
bsd-3-clause
1,141
0.007888
# Copyright (c) 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. import logging import time class TimeProfile: """Class for simple profil
ing of action, with logging of cost.""" def __init__(self, description='operation'): self._starttime = None self._endtime = None self._description = description self.Start() def Start(self): self._starttime = time.time() self._endtime = None def GetDelta(self): """Returns the rounde...
top(log=False) delta = self._endtime - self._starttime delta = round(delta, 2) if delta < 10 else round(delta, 1) return delta def LogResult(self): """Logs the result.""" logging.info('%s seconds to perform %s', self.GetDelta(), self._description) def Stop(self, log=True): """Stop profilin...
sauloal/pycluster
pypy-1.9_64/lib_pypy/pypy_test/test_md5_extra.py
Python
mit
6,315
0.003009
"""A test script to compare MD5 implementations. A note about performance: the pure Python MD5 takes roughly 160 sec. per MB of data on a 233 MHz Intel Pentium CPU. """ from __future__ import absolute_import import md5 # CPython's implementation in C. from lib_pypy import _md5 as pymd5 ...
re: "Compare pure Python MD5 against Pytho
n's std. lib. version." def test1(self): "Test cases with known digest result." cases = ( ("", "d41d8cd98f00b204e9800998ecf8427e"), ("a", "0cc175b9c0f1b6a831c399e269772661"), ("abc", "900150983cd24fb0d6963f7d28e17f72"), ...
wmde/render-algbackend
gp/tests/slave_test.py
Python
gpl-3.0
11,673
0.026047
#!/usr/bin/python # -*- coding: utf-8 import unittest import tempfile from test_base import * from gp.client import * def read_lines( filepath ): f = open(filepath, 'ra') lines = [ s for s in f ] f.close() return lines # Tests a connection to a slave process, as well as general client # lib fu...
owPipes = True self.assertCommandAccepted( 'clear > /tmp/test' ) self.assertCommandAccepted( 'clear < /tmp/test' )
# pipes conflict ----------------------------------------- self.assertCommandRejected( 'clear > /tmp/test', None, NullSink.instance ) self.assertCommandRejected( 'clear < /tmp/test', NullSource.instance, None ) def assertArgumentAccepted(self, arg ): s = re...
colajam93/aurpackager
manager/admin.py
Python
mit
483
0
from django.contrib import admin from manager.models import Package, Build, Artifact class PackageAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(Package,
PackageAdmin
) class BuildAdmin(admin.ModelAdmin): list_display = ('id', 'package', 'version', 'date', 'status') admin.site.register(Build, BuildAdmin) class ArtifactAdmin(admin.ModelAdmin): list_display = ('id', 'package', 'name') admin.site.register(Artifact, ArtifactAdmin)
mitch-kyle/message-board
support/apache-cassandra-2.2.1/pylib/cqlshlib/test/basecase.py
Python
apache-2.0
2,608
0.001917
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOU
T WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import logging from itertools import izip from os.path import dirname, join, normpath, islink cqlshlog = logging.getLogger('tes...
EmpireProject/Empire
lib/modules/powershell/code_execution/invoke_metasploitpayload.py
Python
bsd-3-clause
2,826
0.010616
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-MetasploitPayload', 'Author': ['@jaredhaight'], 'Description': ('Spawns a new, hidden PowerShell window that downloads' 'and ...
moduleSource = self.mainMenu.installPath + "/data/module_source/code_execution/Invoke-MetasploitPayload.ps1" if obfuscate: helpers.obfuscate_module(moduleSource=moduleSource, obfuscationCommand=obfuscationCommand) moduleSource = moduleSource.replace("module_source", "obfuscated_module_so...
leSource, 'r') except: print helpers.color("[!] Could not read module source path at: " + str(moduleSource)) return "" moduleCode = f.read() f.close() script = moduleCode scriptEnd = "\nInvoke-MetasploitPayload" for option,values in self.options...
crf1111/Bio-Informatics-Learning
Bio-StrongHold/src/Inferring_Genotype_from_a_Pedigree.py
Python
mit
1,261
0.024584
from StrongHold import Newick def child_prob(a,b): '''Returns th
e genotype probability for a child with parents who have genotype probabilities a and b.''' # Comes from the conditional probability of each possible Punit square. AA = a[0]*b[0] + 0.5*(a[0]*b[1] + a[1]*b[0] + 0.5*a[1]*b[1]) Aa = a[0]*b[2] + a[2]*b[0] + 0.5*(a[0]*b[1] + a[1]*b[0] + a[1]*b[1] + a[2]*b[1] + a[1]*b[2])...
ata.dat') as input_data: tree = input_data.read().strip() nwck = Newick(tree) genotype_prob = lambda genotype:[int(genotype.count('a') == i) for i in xrange(3)] # Convert the nodes with genotype names to probabilities. for node in [node for node in nwck.nodes if 'Node' not in node.name]: node.name = genotype_...
lawrluor/matchstats
db_create.py
Python
bsd-3-clause
518
0
#!flask/bin/python from migrate.versi
oning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import db import os.path db.create_all() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database2 repository') api.version_control(SQLALCHEMY_DATABASE_URI, SQLALC...
_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
fsteggink/stetl
stetl/utils/apachelog.py
Python
gpl-3.0
16,691
0.001078
#!/usr/bin/env python """Apache Log Parser Parser for Apache log files. This is a port to python of Peter Hickman's Apache::LogEntry Perl module: <http://cpan.uwinnipeg.ca/~peterhi/Apache-LogRegex> Takes the Apache logging format defined in your httpd.conf and generates a regular expression which is used to a line fr...
'gen_key': False} def __init__(self, format, key_map=None, options=default_options): """ Takes the log format from an Apache configuration file. Best just copy and paste directly from the .conf file and pass using a Python raw string e.g. format = r'%h %l %u %t \"...
format) """ self._names = [] self._regex = None self._pattern = '' self._parse_format(format) self._key_map = key_map self._options = options def _parse_format(self, format): """ Converts the input format to a regular expression, as we...
ahelsing/geni-ch
tools/SA_constants.py
Python
mit
6,842
0.016077
#---------------------------------------------------------------------- # Copyright (c) 2011-2015 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including ...
e', 'context_id' : 'context_id', 'request_text' : 'request_text', 'request_type' : 'request_type', 'request_details' : 'request_details', 'reques
tor' : 'requestor', 'status' : 'status', 'creation_timestamp' : 'creation_timestamp', 'resolver' : 'resolver' , 'resolution_timestamp' : 'resolution_timestamp', 'resolution_description' : 'resolution_description' }
hrosenhorn/gevent-memcache
lib/geventmemcache/codec.py
Python
bsd-3-clause
2,039
0.005885
import cPickle as pickle from geventmemcache import MemcacheError class MemcacheCodec(object): def decode(self, flags, encoded_value): assert False, "implement" #pragma: no cover def encode(self, value, flags): assert False, "implement" #pragma: no cover @classmethod def create(self,...
return pickle.loads(encoded_value) else: return encoded_value def encode(self, value, flags): if isinstance(value, str): encoded_value = value elif isinstance(value, int): flags |= self._FLAG_INTEGER encod
ed_value = str(value) elif isinstance(value, long): flags |= self._FLAG_LONG encoded_value = str(value) elif isinstance(value, unicode): flags |= self._FLAG_UNICODE encoded_value = value.encode('utf-8') else: flags |= self._FLAG_PICKLE ...
Ecotrust/cogs-priorities
priorities/seak/migrations/0001_initial.py
Python
bsd-3-clause
19,850
0.007103
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ConservationFeature' db.create_table('seak_conservationfeature', ( ('name', se...
self.gf('django.db.models.fields.FloatField')(default=0.0)), ('description', self.gf('django.db.models.fields.TextField')(default='', null=True, blank=True)), ('output_best', self.gf('seak.models.JSONField')(null=True, blank=True)), ('output_pu_count', self.gf('seak.models.JSONField...
_table('seak_scenario_sharing_groups', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('scenario', models.ForeignKey(orm['seak.scenario'], null=False)), ('group', models.ForeignKey(orm['auth.group'], null=False)) )) db.create_uniqu...
GoogleCloudPlatform/datacatalog-connectors-hive
google-datacatalog-apache-atlas-connector/src/google/datacatalog_connectors/apache_atlas/sync/metadata_synchronizer.py
Python
apache-2.0
6,243
0
#!/usr/bin/python # # 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 ag...
metadata...') metadata_dict, _ = self._metadata_scraper.get_metadata() self._log_metadata(metadata_dict) tag_templates_dict = self.
_make_tag_templates_dict(metadata_dict) assembled_entries = self._make_assembled_entries( metadata_dict, self._atlas_entity_types) logging.info('==== DONE ========================================') logging.info('') self._clean_up_obsolete_metadata(assembled_entries) s...
bbiskup/purkinje-messages
tests/message_test.py
Python
mit
7,537
0
# -*- coding: utf-8 -*- """Test cases for messages""" from __future__ import absolute_import from builtins import str import json import sys import pytest from datetime import datetime from mock import Mock import logging import purkinje_messages.message as sut logging.basicConfig(level=logging.DEBUG, stream=sys.stdo...
= session_terminated_event.serialize() expected = {'type': 'session_terminated', 'timestamp': '2014-02-01T08:09:10', 'suite_hash': u'668a86604fc7028f2d9ea4016ae0bf7c', } assert json.loads(serialized) == expected def test_parse_tc_start(): event_json = ('{"ty...
' "timestamp": "2014-02-01T08:09:11"}') event = sut.Event.parse(event_json) assert event['timestamp'] == '2014-02-01T08:09:11' def test_parse_connection_termination(): event_json = ('{"type": "terminate_connection",' ' "timestamp": "2014-02-01T08:09:10"}') sut.Event.p...
karesansui/karesansui
karesansui/lib/conf.py
Python
mit
9,611
0.007209
# -*- coding: utf-8 -*- # # This file is part of Karesansui Core. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, t
o any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom...
opyright 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 NONINFRIN...
yochow/autotest
client/bin/xen.py
Python
gpl-2.0
7,532
0.004514
__author__ = """Copyright Martin J. Bligh, 2006, Copyright IBM Corp. 2006, Ryan Harper <ryanh@us.ibm.com>""" import os, shutil, copy, pickle, re, glob from autotest_lib.client.bin import kernel, kernel_config, os_dep, test from autotest_lib.client.bin import utils class xen(kernel.kernel): def l...
# fix up XENGUEST value in EXTRAVERSION; we can't have # files with '$(XENGEUST)' in the name, =( self.fix_up_xen_kernel_makefile(kernel_base_tree) # make the kernel job self.kjob = self.job.kernel(kernel_base_tree) # hardcoding dom0 config (no modu...
c = self.build_dir + '/buildconfigs/linux-defconfig_xen0_x86_32' self.log('using kernel config: %s ' % c) self.kjob.config(c) # Xen's kernel tree sucks; doesn't use bzImage, but vmlinux self.kjob.set_build_target('vmlinuz') # also, the vmlinuz is...
berkowitze/hveto
setup.py
Python
gpl-3.0
3,688
0.000271
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2013) # # This file is part of the hveto python package. # # hveto 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...
'numpydoc', 'sphinx_rtd_theme', 'sphinxcontrib_programoutput', 'sphinxcontrib_epydoc', ], } # -- run setup ---------------------------------------------------------------- packagenames = find_packages() scripts = glob.glob(os.path.join('bin', '*')) setup(name=DISTNAME, provides=[...
kages=packagenames, include_package_data=True, cmdclass=cmdclass, scripts=scripts, setup_requires=setup_requires, install_requires=install_requires, requires=requires, tests_require=tests_require, extras_require=extras_require, dependency_links=[ 'http://s...
StevenCHowell/zazmol
src/python/test_sasmol/test_system/test_intg_system_Atom_setLoc.py
Python
gpl-3.0
1,425
0.027368
''' SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
elf.assertEqual(expected, resul
t) def tearDown(self): pass if __name__ == '__main__': main()
Tinkerforge/brickv
src/brickv/plugin_system/plugins/distance_ir/__init__.py
Python
gpl-2.0
922
0
# -*- coding: utf-8 -*- """ Distance IR Plugin Copyright (C) 2011 Olaf Lüke <olaf@tinkerforge.com> __init__.py: package initialization 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 ...
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See t
he 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from brickv.plugin_system.plugins.distance_ir.distance_ir import ...
zimolzak/crypto-challenges
chal34.py
Python
gpl-3.0
637
0.00157
#!/usr/bin/env python # chal34.py - Man in the middle vs. Diffie-Hellman # # Copyright (C) 2015 Andrew J. Zimolzak <a
ndyzimolzak@gmail.com>, # and licensed under GNU GPL version 3. Full notice is found in # the file 'LICENSE' in the same directory as this file. from cryptopals import warn from diffie_hellman import Persona alice = Persona() bob = Persona() mallory = Persona(evil=True, sucker=bob) print "Innocent conve
rsation:" alice.handshake_with(bob) alice.talk_to(bob) print print "Overheard conversation:" alice.handshake_with(mallory) alice.talk_to(mallory) #### tests warn("Passed assertions:", __file__)
astrofrog/numtraits
setup.py
Python
bsd-2-clause
790
0.003797
from setuptools import setup import re def read(filename): with open(filename) as f: return f.read() __version__ = re.search(r'^__version__ = ([\'"])(?P<version>.*)\1$', read('numtraits.py'), re.M).groupdict()['version'] try: import pypandoc long_description = pypandoc.con...
version=__version__, url="https://github.com/astrofrog/numtraits", name="numtraits", description='Numerical traits for Python objects', long_description=long_description, py_modules=['numtraits'], license='BSD', author='Thomas Robitaille', author_email='thomas.r
obitaille@gmail.com', install_requires=['numpy','traitlets'] )
muraliselva10/python-cloudkittyclient
cloudkittyclient/v1/client.py
Python
apache-2.0
2,879
0
# Copyright 2015 Objectif Libre # 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 b...
torage.StorageManager(self.http_client) self._expose_submodules() def _expose_submodules(self): extensions = extension.ExtensionManager( SUBMODULES_NAMESPACE, ) for ext in extensions:
client = ext.plugin.get_client(self.http_client) setattr(self, ext.name, client)
felix1m/pyspotify
examples/play_track.py
Python
apache-2.0
1,694
0
#!/usr/bin/env python """ This is an example of playing music from Spotify using pyspotify. The example use the :class:`spotify.AlsaSink`, and will thus only work on systems with an ALSA sound subsystem, which means most Linux systems. You can either run this file directly without arguments to play a default track::...
def on_connection_state_updated(session): if session.connection.state is spotify.ConnectionState.LOGGED_IN: logged_in.set() def on_end_of_track(self): end_of_track.set() # Register event listeners session.on( spotify.SessionEvent.CONNECTION_STATE_UPDATED, on_connection_state_updated) session.on(...
d_in.wait() # Play a track track = session.get_track(track_uri).load() session.player.load(track) session.player.play() # Wait for playback to complete or Ctrl+C try: while not end_of_track.wait(0.1): pass except KeyboardInterrupt: pass
NCTU-PCCA/NCTU_Yggdrasill
codebook/ToBeClassify/print_file.py
Python
mit
221
0.022624
import sublime, sublime_plugin import os class print_file(sublime_plugin.TextCommand): def run(self, edit): os.system('
cat -n "%s" > tmp.print; lpr tmp.print' % self.view.fi
le_name()) self.view.show_popup("JIZZ!!")
supermanue/montera
PilotResource.py
Python
gpl-2.0
1,450
0.044828
''' Created on Sep 2, 2013 @author: u5682 ''' from sqlalchemy import * import base from base import Base from sqlalchemy.orm import relationship, backref import Bessel class PilotResource(Base): ''' classdocs ''' __tablename__ = 'pilotResources' id = Column(Integer, primary_key=True) workerNode = Column(Strin...
ones, queueTime, bandwidth): if self.successfulExecutions == 0: self.whetstones = whetstones if bandwidth > 0: self.bandwidth = bandwidth else: oldWhetstones = self.whetstones newWhetstones = Bessel.calculateAverage(oldWhetstones, self.successfulExecutions, whetstones) self.whetstone
s = newWhetstones if bandwidth > 0: oldBandwidth = self.bandwidth newBandwidth = Bessel.calculateAverage(oldBandwidth, self.successfulExecutions, bandwidth) self.bandwidth = newBandwidth self.successfulExecutions +=1 self.failedProfilings -=1
jyejare/automation-tools
upgrade_tests/test_existance_relations/test_contentviews.py
Python
gpl-3.0
1,609
0
"""Upgrade TestSuite for validating Satellite CVs existence and associations post upgrade """ import pytest from automation_tools.satellite6.upgrade.tests.existence import ( compare_postupgrade ) @pytest.mark.parametrize( "pre,post", compare_postupgrade('content-view', 'repository ids') ) def test_positiv...
ert: All composite CVs should be retained post upgrade """ assert pre == post @pytest.mark.parametrize( "pre,post", compare_postupgrade('c
ontent-view', 'name') ) def test_positive_cvs_by_name(pre, post): """Test all CVs are existing after upgrade by their name :id: 7ad53fb0-f05c-4eea-bd6c-db6c35ea8841 :assert: All CVs should be retained post upgrade by their name """ assert pre == post
jjinux/squeamish
src/parameter.py
Python
bsd-3-clause
3,028
0.016513
"""This file contains the Parameter class.""" from AutomaticClass import AutomaticClass from Expression import Expression from Symbol import Symbol class Parameter(AutomaticClass): """This encapsulates a parameter to a builtin function. In order to implement lazy evaluation of function parameters for ...
are side effects). implicitUnval - During evaluation, if the Expression.parseTree is a list, automatically treat the list as data (i.e. a call to the unval function) instead of a normal function call. This is required in certain situations such as the value (i.e. body) of a...
implicitLast - If after evaluation, the value is a list, return only the last element of that list. Like implicitUnval, this is required in certain situations such as the value (i.e. body) of an if statement, which are meant to feel like the body of a function definition. """ f...
Parisson/TimeSide
timeside/plugins/analyzer/externals/aubio_mfcc.py
Python
agpl-3.0
3,382
0.001183
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Paul Brossier <piem@piem.org> # This file is part of TimeSide. # 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 Lic...
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 # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # ...
ccpgames/shiptoasting
shiptoasting/web.py
Python
mit
4,504
0
"""ShipToasting web handlers.""" import os import sys import atexit import random import traceback import gevent from flask import Response from flask import redirect from flask import render_template from flask import request from flask import session from apscheduler.schedulers.gevent import GeventScheduler from ...
'<div class="time">{time:%b %e, %H:%M:%S}</div>' ).format( ccp=" ccp" * int(shiptoast.author.startswith("CCP ")), **shiptoast._asdict() ) yield "data: {}\n\n".format(data) raise StopIteration def traceback_formatter(excpt, value, tback): "...
in(traceback.format_exception(excpt, value, tback))) def hook_exceptions(): """Hooks into the sys module to set our formatter.""" if hasattr(sys.stdout, "fileno"): # when testing, sys.stdout is StringIO # reopen stdout in non buffered mode sys.stdout = os.fdopen(sys.stdout.fileno(), "wb", 0)...
elstupido/rpg
rooms/testrooms/testroom2.room.py
Python
mit
539
0.007421
from room import Room r = Room() r.roomname = 'testroom2' r.exits = {'up': 'testroom'} r.roomdesc = """ As you look around, you notice there seems to be not much
here. it appears you can go up and get back to where you came from there is a pile of gold and a large monster looking at you strangely. """ r.looktargets = {'gold': 'oooh. Shiny!\n\n', 'monster': 'HOLY CRAP ITS A MONSTER\n\n', 'pile': 'oooh. Shiny!\n\n', 'pile of gold': 'oooh. Shiny!\n\n', } r.talktargets = {'m...
ter'} r.characters = ['test_monster']
ziowk/rejit
tests/test_x86encoder.py
Python
gpl-2.0
16,018
0.007929
#encoding: utf8 import pytest from rejit.x86encoder import InstructionEncodingError, Reg, Scale, Encoder, Encoder32, Encoder64, Opcode, Mem reg64 = [Reg.EAX, Reg.ECX, Reg.EDX, Reg.EBX, Reg.ESP, Reg.EBP, Reg.ESI, Reg.EDI, Reg.R8, Reg.R9, Reg.R10, Reg.R11, Reg.R12, Reg.R13, Reg.R14, Reg.R15] reg64_1 = reg64[:8] reg6...
def test_encode_R8_R15_index_x64
(self, encoder64): # R12 -> RSP, can't use RSP as addressing index ext_regs = [Reg.R8, Reg.R9, Reg.R10, Reg.R11, Reg.R13, Reg.R14, Reg.R15] for reg in ext_regs: binary = encoder64.encode_instruction([Opcode.MOV_R_RM], reg=Reg.EAX, base=Reg.EAX, index=reg, scale=Scale.MUL_1, size = 8...
justanr/owa
manager.py
Python
gpl-3.0
1,148
0.000871
#!/usr/bin/env python import sys from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager from owa import ( # extensions db, # configuration config, # modules schemas, models, utils, core, shell, # helpers create_app, after_request ) from owa.api im...
te = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.opti
on('-d', '--d', dest='basedir') def addfiles(basedir): try: store_directory(basedir) except (KeyboardInterrupt, EOFError): db.session.rollback() sys.exit(1) else: sys.exit(0) @manager.shell def _shell_context(): return dict(app=app, db=db, models=models, ...
DevinDewitt/pyqt5
examples/widgets/stylesheet/stylesheeteditor.py
Python
gpl-3.0
4,557
0.007242
############################################################################# ## ## Copyright (C) 2010 Hans-Peter Jansen <hpj@urpla.net>. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may ...
the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Nokia Corporation and its Subsidiary(-
ies) nor ## the names of its contributors may be used to endorse or promote ## products derived from this software without specific prior written ## permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## L...
kuke/models
fluid/PaddleCV/caffe2fluid/kaffe/custom_layers/power.py
Python
apache-2.0
1,292
0.004644
""" a custom layer for 'power', maybe we should implement this in standard way. more info can be found here: http://caffe.berkeleyvision.org/tutorial/layers/power.html """ from .register import register def power_shape(input_shape, shape=None): """ calculate the output shape of this layer using input shape ...
layer Returns: output (variable): output variable for this layer """ import paddle.fluid as fluid scale_out = fluid.layers.scale( input, scale=scale, bias=shift, bias_after_scale=True) output = fluid.layers.pow(scale_out, factor=power) return output register(k
ind='Power', shape=power_shape, layer=power_layer)
VijayKrishna/sleep-work-relax
tokenize/rianne-sentiment.py
Python
mit
1,530
0.034641
import nltk import math import fileinput import re lijst = dict() smileys = re.compile('[:;]-?[()PD/\\\\]') def do_tokens(tweet): tokens = [t for t in nltk.word_tokenize(tweet) if len(t) > 2] tok
ens.extend(smileys.findall(tweet)) return tokens total = {-1: 0, 0: 0, +1: 0} with open("Training_data.txt", "r") as f: next(f) #skip firstline for line in f: a = line.strip().split("\t") tweet = a[0] score = int(a[1]) # if score == 0 : continue # (haal neutrale eruit) tokens = do_tokens(tweet) ...
total[score] += 1 if not t in lijst: lijst[t] = {-1: 0, 0: 0, +1: 0} lijst[t][score] += 1 for i in lijst: score = lijst[i] score[-1] *= 1.0 / total[-1] score[ 0] *= 1.0 / total[ 0] score[+1] *= 1.0 / total[+1] score['sum'] = score[-1] + score[ 0] + score[+1] # w = 1 # elk woord gewicht ...
w1ll1am23/home-assistant
homeassistant/components/flo/device.py
Python
apache-2.0
7,961
0.001005
"""Flo device object.""" from __future__ import annotations import asyncio from datetime import datetime, timedelta from typing import Any from aioflo.api import API from aioflo.errors import RequestError from async_timeout import timeout from homeassistant.helpers.typing import HomeAssistantType from homeassistant....
"""Return the current humidity in percent (0-100).""" ret
urn self._device_information["telemetry"]["current"]["humidity"] @property def consumption_today(self) -> float: """Return the current consumption for today in gallons.""" return self._water_usage["aggregations"]["sumTotalGallonsConsumed"] @property def firmware_version(self) -> str: ...
nathanljustin/teamwork-analysis
teamworkApp/lib/delete_data.py
Python
mit
520
0.007692
# muddersOnRails() # Sara McAllister November 17, 2017 # Last updated: 11-17-2017 # delete all data from database and remove generated graphs (this is super sketch) import os import dbCalls summary_file = 'app/assets/images/summary.png' overall_file = 'a
pp/assets/images/overall.png' def main(): dbCalls.remove_all() # remove both summary and overall picture try: os.remove(summary_file) os.remove(overall_file) except OSError: pass if __name__ == "__main__": main()
YixuanLi/geo-tweet
LIWC-train/LIWC_classify.py
Python
gpl-2.0
10,894
0.028915
# -*- coding: utf-8 -*- # __author__: Yixuan LI # __email__: yl2363@cornell.edu import numpy as np import os from sklearn import svm import matplotlib.pyplot as plt import pickle from sklearn import preprocessing from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest from sk...
ma=0.1, probability = True, kernel='rbf',C=2.) #self.clf_SVM = svm.SVC() self.clf_SVM.fit(X_train, Y_tra
in) probas_SVM = self.clf_SVM.fit(X_train, Y_train).predict_proba(X_test) #print probas_SVM # prediction # http://scikit-learn.org/stable/tutorial/basic/tutorial.html#learning-and-predicting s = pickle.dumps(self.clf_SVM) clf2 = pickle.loads(s) diff_train_SVM = clf2.predict(X_train) - Y_train diff_t...
imbasimba/astroquery
astroquery/utils/url_helpers.py
Python
bsd-3-clause
1,603
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst try: from six.moves.urllib_parse import SplitResult, urlsplit except ImportError: from six.moves.urllib_parse import SplitResult, urlsplit import os.path def urljoin_keep_path(url, path): """Join a base URL and a relative or absolute path. Th...
ample.com/foo/bar' >>> from six.moves.urllib import parse as urlparse >>> urlparse.urljoin('http://example.com/foo', 'bar') 'http://example.com/bar' """ # urlparse.SplitResult doesn't allow overriding attribute values, # so ``splitted_url.path = ...`` is not possible here, unfortunately. sp...
join(splitted_url.path, path), splitted_url.query, splitted_url.fragment).geturl() def join(a, *p): """Taken from python posixpath.""" sep = '/' path = a if not p: path[:0] + sep for b in p: if b.startswith(sep): ...
totalgood/nlpia
src/nlpia/data_utils.py
Python
mit
11,738
0.001962
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division, absolute_import from builtins import (bytes, dict, int, list, object, range, str, # noqa ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip) from future import standard_library from past.builtins im...
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP
error code) cleaned up URL (following redirects and possibly adding HTTP schema "http://") >>> is_up_url("duckduckgo.com") # a more private, less manipulative search engine 'https://duckduckgo.com/' >>> urlisup = is_up_url("totalgood.org") >>> not urlisup or str(urlisup).startswith('http') ...
AtTheMatinee/Roguelike-Core
Items/bombs.py
Python
mit
2,318
0.039689
''' bombs.py ''' from items import Item import Items import objects import libtcodpy as libtcod ''' ==================== Bombs ==================== ''' class Bomb(Item): identified = False def __init__(self, game, x, y, char, name, color, level, timer, blocks=False, properNoun = False): Item.__init__(self, game, x...
l objects.SmokeCloud(self.game, self.x, self.y, 'smoke', libtcod.dark_grey, volume) self.identify(self.actor) self.destroy() class FlachetteGrenade(Bomb): pass # Does physical damage and bleed damage class FlashGrenade(Bomb): pass # confuses any actor withing its effective range class Spellbomb(Bomb): de...
self.spell = Items.spells.Spell(self.game,self.name,self) self.spell.magicCost = 0 def effect(self): # Note: this implementation only works if the spell requires no target self.spell.cast() self.identify(self.actor) self.destroy()
khoanguyen0791/cs170
CS170_homework/Armstrong.py
Python
apache-2.0
1,312
0.01753
#prerequisites: none, just a range from 0-9 # Each number is from 0-9, when raised to the power of 5 #will produce a the same number as when all are put together def armstrong5(): print("These are the five digit Armstrong numbers:") for first in range (1, 10)
: for second in range (0, 10): for third in range (0, 10): for fourth in range (0, 10): for fifth in range (0, 10): number = 10000* first + 1000* second + 100* third \
+ 10* fourth + fifth armstrong = first**5 + second**5 + third**5 \ + fourth**5 + fifth**5 if number == armstrong: print(number) armstrong5() def armstrong4a(): print ("Here ...
jade-cheng/Jocx
tests/ziphmm/test_mann.py
Python
gpl-2.0
1,967
0.000508
import unittest from ziphmm import _mann from _internal import create_hmm from _internal import create_seq class TestMann(unittest.TestCase): def test0(self): self.__test('test0', 'test0', -12.4766) def test1(self): self.__test('test1', 'test1', -12.5671) def test2(self): self....
cted_value): def fix(n, digits=4): if n is None: return None fmt = '{0:
.' + str(digits) + 'f}' return fmt.format(round(n, digits)) hmm = create_hmm('inputs/' + hmm_name + '.hmm') seq = create_seq('inputs/' + seq_name + '.seq') actual_value = _mann.evaluate(hmm, seq) self.assertEqual(fix(expected_value), fix(actual_value)) if __name__ == '__mai...
robbat2/teuthology
teuthology/task/full_sequential.py
Python
mit
986
0
""" Task sequencer - full """ impor
t sys import logging from teuthology import run_tasks log = logging.getLogger(__name__) def task(ctx, config): """ Run a set of tasks to completion in order. __exit__ is called on a task before __enter__ on the next example: - full_sequential: - tasktest: - tasktest: :param ...
if not isinstance(entry, dict): entry = ctx.config.get(entry, {}) ((taskname, confg),) = entry.iteritems() log.info('In full_sequential, running task %s...' % taskname) mgr = run_tasks.run_one_task(taskname, ctx=ctx, config=confg) if hasattr(mgr, '__enter__'): tr...
zstackorg/zstack-woodpecker
integrationtest/vm/simulator/iam2/test_iam2_project_basic_ops_network_service.py
Python
apache-2.0
7,842
0.009054
''' test iam2 vm operations by platform admin/operator/member # 1 create project # 2 create virtual id (project admin/operator/member) # 3 operations on vm with virtual id # 4 delete @author: quarkonics ''' import os import time import zstackwoodpecker.test_util as test_util import apibinding.inventory as inventory i...
' project_operator_password = 'password' attributes = [{"name": "__ProjectOperator__", "value": project_uuid}] project_operator_uuid = iam2_ops.create_iam2_virtual_id(project_operator_name,project_operator_password,attributes=attributes).uuid
virtual_id_uuid = iam2_ops.create_iam2_virtual_id('usernamethree','password').uuid # login in project by project operator iam2_ops.add_iam2_virtual_ids_to_project([project_operator_uuid],project_uuid) project_operator_session_uuid = iam2_ops.login_iam2_virtual_id(project_operator_name,...
artcz/epcon
assopy/tests/test_reset_password.py
Python
bsd-2-clause
481
0.004158
from django.core.urlres
olvers import reverse from django.test import TestCase class ResetPasswordTestCase(TestCase): def test_reset_password(self): url = reverse('password_reset_confirm', kwargs={ 'uidb64': '12123313A', 'token': 'a0-1212dd' ...
_reset_confirm.html')
qingqing01/Paddle
doc/ui/predict/predict_sample.py
Python
apache-2.0
8,781
0.001594
# Copyright (c) 2016 Baidu, Inc. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
yanheven/neutron
neutron/tests/tempest/common/credentials.py
Python
apache-2.0
2,822
0
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
force_tenant_isolation=False): # If a test requires a new account to work, it can have it via forcing # tenant isolation. A new account will be produced only for that test. # In case admin credentials are not available for the account creation, # the test should be skipped else it would fail. ...
name=name, network_resources=network_resources) else: if CONF.auth.locking_credentials_provider: # Most params are not relevant for pre-created accounts return accounts.Accounts(name=name) else: return accounts.NotLockingAccounts(name=name) #...
gilestrolab/ethoscope
src/ethoscope/tests/unittests/test_target_roi_builder.py
Python
gpl-3.0
1,055
0.017062
__author__ = 'quentin' import cv2 import unittest import os from ethoscope.roi_builders.target_roi_builder import SleepMonitorWithTargetROIBuilder, TargetGridROIBuilder try: from cv2.cv import CV_AA as LINE_AA except ImportError: from cv2 import LINE_AA images = {"bright_targets":"../st
atic_files/img/bright_targets.png", "dark_targets": "../static_files/img/dark_targets.png"} LOG_DIR = "./test_logs/" class TestTargetROIBuilder(unittest.TestCase): roi_builder = SleepMonitorWithTargetROIBuilder() def _draw(self,img, rois): for r in rois: cv2.drawContours(img,...
.build(img) self._draw(img, rois) cv2.imwrite(out,img) self.assertEqual(len(rois),20) def test_all(self): for k,i in list(images.items()): out = os.path.join(LOG_DIR,k+".png") print(out) self._test_one_img(i,out)
yesudeep/mils-secure
app/lovely/jsonrpc/wsgi.py
Python
mit
2,322
0.005168
############################################################################## # # Copyright 2008 Lovely Systems GmbH # # 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...
Logger(__name__) class WSGIJSONRPCApplication(dispatcher.JSONRPCDispatcher): """Ac WSGI Applicati
on for generic JSONRPC requests.""" def handler(self, environ, start_response): """A WSGI handler for generic JSONRPC requests.""" if environ['REQUEST_METHOD'].endswith('POST'): body = None if environ.get('CONTENT_LENGTH'): length = int(environ['CONTENT_LENG...
mpgirro/MarsRoverPictureCrawler
mrpc.py
Python
mit
5,158
0.020938
#!/usr/bin/python2.6 # MarsRoverPictureCrawler (mrpc): # A download bot for OPPORTUNITY and SPIRIT Mars Rover Pictures # # Copyright (C) 2011 by Max
imilian Irro <maximilian.irro@gmail.com> # #
Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copie...
dims/neutron
neutron/tests/functional/api/test_policies.py
Python
apache-2.0
3,716
0
# Copyright (c) 2014 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
setUp(self): super(APIPolicyTestCase, self).setUp()
self.useFixture(tools.AttributeMapMemento()) self.extension_path = os.path.abspath(os.path.join( TEST_PATH, "../../../extensions")) policy.reset() def _network_definition(self): return {'name': 'test_network', 'ports': [], 'subnets': [], ...
tempbottle/zerorpc-python
tests/test_heartbeat.py
Python
mit
12,536
0.001516
# -*- coding: utf-8 -*- # Open Source Initiative OSI - The MIT License (MIT):Licensing # # The MIT License (MIT) # Copyright (c) 2015 François-Xavier Bourlet (bombela+zerorpc@gmail.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files...
TIME_FACTOR * 2) gevent.sleep(TIME_FACTOR * 3) print 'CLOSE SERVER SOCKET!!!'
server_hbchan.close() if sys.version_info < (2, 7): assert_raises(zerorpc.LostRemote, client_hbchan.recv) else: with assert_raises(zerorpc.LostRemote): client_hbchan.recv() print 'CLIENT LOST SERVER :)' client_hbchan.close() server.close() client.close() def test_h...
Sunhick/design-patterns
Creational/AbstractFactory/GeometryFactory/GeometryFactory.py
Python
gpl-3.0
1,700
0
#!/usr/bin/python import Colors import Shapes from abc import ABCMeta, abstractmethod class AbstractFactory(object): __metaclass__ = ABCMeta @abstractmethod def get_color(self, color): pass @abstractmethod def get_shape(self, shape): pass class ShapeFactory(AbstractFactory): ...
raise 'use shape factory' class FactoryProducer(object): @staticmethod def get_factory(factory_name): factory_name = factory_name.lower() if factory_name == 'shape': return ShapeFactory() elif factory_name == 'color': return ColorFactory() else: ...
unknown factory specified') class InvalidFactoryException(Exception): pass class InvalidColorException(Exception): pass class InvalidShapeException(Exception): pass
strint/tensorflow
tensorflow/contrib/learn/python/learn/graph_actions_test.py
Python
apache-2.0
35,811
0.009243
# Copyright 2016 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...
r): Test lock, multi-threaded access? def test_summary_writ
er(self): writer = learn.graph_actions.get_summary_writer('log/dir/0') self._assert_summaries('log/dir/0', writer) self.assertTrue( learn.graph_actions.get_summary_writer('log/dir/0') is learn.graph_actions.get_summary_writer('log/dir/0')) self.assertTrue( learn.graph_actions.get...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/db/models/options.py
Python
bsd-3-clause
20,313
0.001477
import re from bisect import bisect from django.conf import settings from django.db.models.related import RelatedObject from django.db.models.fields.related import ManyToManyRel from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.fields.proxy import OrderWrt from django.db.models.loa...
mn, target in self.duplicate_targets.iteritems(): try: collections[target].add(column) except KeyError:
collections[target] = set([column]) self.duplicate_targets = {} for elt in collections.itervalues(): if len(elt) == 1: continue for column in elt: self.duplicate_targets[column] = elt.difference(set([column])) def add_field(self, f...
theone4ever/mackup
tests/utils_test.py
Python
gpl-3.0
11,764
0
import os import tempfile import unittest import stat # from unittest.mock import patch from mackup import utils def convert_to_octal(file_name): """ Using os.stat, returns file permissions (read, write, execute) as an octal. """ return oct(os.stat(file_name)[stat.ST_MODE])[-3:] class TestMackup(u...
) assert not os.path.exists(filepath) assert not os.path.exists(subfolder_path) assert not os.path.exists(subfilepath) def test_copy_file(self): # Create a tmp file tfile = tempfile.NamedTemporaryFile(delete=False) srcfile = tfile.name tfile.close() ...
tempfile.mkdtemp() # Set the destination filename dstfile = os.path.join(dstpath, "subfolder", os.path.basename(srcfile)) # Make sure the source file and destination folder exist and the # destination file doesn't yet exist assert os.path.isfile(srcfile) assert os.path....
PragmaticMates/django-clever-selects
clever_selects/forms.py
Python
mit
10,535
0.002468
from __future__ import absolute_import import json from django import forms from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ObjectDoesNotExist try: from django.urls import reverse, resolve except: from django.core.urlresolvers import reverse, resolve from django.core....
l get the callable from the url. # All we need to do is pass i
n a 'request' url_callable = resolve(url).func # Build the fake request fake_request = HttpRequest() fake_request.META["SERVER_NAME"] = "localhost" fake_request.META["SERVER_PORT"] = '80' # Add para...
PhE/dask
dask/array/image.py
Python
bsd-3-clause
1,949
0.001026
from glob import glob import os try: from skimage.io import imread as sk_imread except ImportError: pass from .core import Array from ..base import tokenize def add_leading_dimension(x): return x[None, ...] def imread(filename, imread=None, preprocess=None): """ Read a stack of images into a dask a...
. All images will be treated as individual chunks """ imread = imread or sk_imread filenames = sorted(glob(filename)) if not filenames: raise ValueError("No files found under name %s" % filename) name = 'imread-%s' % tokenize(filenames, map(os.pat
h.getmtime, filenames)) sample = imread(filenames[0]) if preprocess: sample = preprocess(sample) keys = [(name, i) + (0,) * len(sample.shape) for i in range(len(filenames))] if preprocess: values = [(add_leading_dimension, (preprocess, (imread, filename))) for filenam...
40223104/w16b_test
rf.py
Python
gpl-3.0
11,334
0.003047
import cherrypy # 這是 MAN 類別的定義 ''' # 在 application 中導入子模組 import programs.cdag30.man as cdag30_man # 加入 cdag30 模組下的 man.py 且以子模組 man 對應其 MAN() 類別 root.cdag30.man = cdag30_man.MAN() # 完成設定後, 可以利用 /cdag30/man/assembly # 呼叫 man.py 中 MAN 類別的 assembly 方法 ''' class MAN(object): # 各組利用 index 引導隨後的程式執行 @cherrypy.exp...
assembly(session, assembly, t
ransf, featID, inc, part2, plane1, plane2, plane3, plane4, plane5, plane6){ var descr = pfcCreate("pfcModelDescriptor").CreateFromFileName ("v:/home/lego/man/"+part2); var componentModel = session.GetModelFromDescr(descr); var componentModel = session.RetrieveModel(descr); if (componentModel != void null) { var asm...
jonathf/chaospy
tests/test_lagrange_polynomials.py
Python
mit
800
0.0025
import chaospy import numpy import pytest @pytest.fixture def samples(joint): return joint.sample(10, rule="sobol") @pytest.fixture def evaluations(model_solver, samples): return numpy.array([model_solver(sample) for sample in samples.T]) @pytest.fixture def expansion(samples): return chaospy.lagrange...
(lagrange_approximation, joint, true_variance): assert num
py.allclose(chaospy.Var(lagrange_approximation, joint), true_variance, rtol=1e-2)
live-clones/pybtex
pybtex/style/formatting/__init__.py
Python
mit
3,956
0.002022
# Copyright (c) 2006-2021 Andrey Golovizin # # Permission i
s hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublic
ense, and/or sell copies of the Software, and to # permit persons to whom the Software 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", ...
mtils/ems
ems/qt4/gui/util.py
Python
mit
8,464
0.007916
''' Created on 10.07.2011 @author: michi ''' import sys from PyQt4.QtCore import QObject, QRectF, QPointF, QSizeF, Qt from PyQt4.QtGui import QTreeWidgetItem, QFontMetrics, QFont, QPrinter from PyQt4.QtGui import QPalette, QDialogButtonBox, QVBoxLayout, QHBoxLayout from PyQt4.QtGui import QFormLayout, QGridLayout f...
ainter.translate(body.left(), body.top() - (index - 1) * body.height()) view = QRectF(0, (index - 1) * body.height(), body.width(), body.height()) layout = doc.documentLayout() ctx = doc.documentLayout().PaintContext() painter.setClipRect(view) ctx.clip = view ...
oesn't look that nice''' ctx.palette.setColor(QPalette.Text, Qt.black) layout.draw(painter, ctx) # if not pageNumberPos.isNull(): # painter.setClipping(False) # painter.setFont(QFont(doc.defaultFont())) # pageString = QString.number(index...
IQSS/gentb-site
apps/predict/app.py
Python
agpl-3.0
1,507
0.000664
# # Copyright 2018, Maha Farhat # # This file is part of the software gentb, consisting of custom # code for the Inkscape project's django-based website. # # gentb 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 Fo...
lf): """Called when the app is ready""" from .models import PredictStrain
signals.pre_delete.connect(self.delete_piperun, sender=PredictStrain)
abalakh/robottelo
robottelo/ui/base.py
Python
gpl-3.0
19,925
0
# -*- encoding: utf-8 -*- """Base class for all UI operations""" import logging from robottelo.helpers import escape_search from robottelo.ui.locators import locators, common_locators from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException from selenium.co...
b_locator) entity_locator = common_locators['entity_select'] self.select_deselect_entity(
filter_key, entity_locator, new_entity_list) def delete_entity(self, name, really, name_locator, del_locator, drop_locator=None, search_key=None): """Delete an added entity, handles both with and without dropdown.""" searched = self.search_entity( name, n...
synw/django-linkcat
linkcat/conf.py
Python
mit
577
0.005208
# -*- coding: utf-8 -*- from django.conf import settings PAGINATE_BY = getattr(settings, 'LINKCAT_PAGINATE_BY', 20) GROUPS_CAN_POST_LINK = getattr(settings, 'LINKCAT_GROUPS_CAN_PO
ST_LINK',
['linkcat_post']) GROUPS_CAN_MODERATE = getattr(settings, 'LINKCAT_GROUPS_CAN_MODERATE', ['linkcat_moderation']) languages = ( ('en', 'English'), ('fr', 'Français'), ) LANGUAGES = getattr(settings, 'LINKCAT_LANGUAGES', languages) default_lang = LANGUAGES[0][0] DEFAULT_LANGUAGE...
lordnord/tkSnake
main.py
Python
lgpl-3.0
7,825
0.006901
import Tkinter as tk import random NOMOVE = { 'Left': 'Right', 'Right': 'Left', 'Up': 'Down', 'Down': 'Up', } OFF = 0 PLACE = 1 DELETE = 2 # TODO # 1. speed management # 3. not empty field by default, additional borders # 5. menu configure before start # 6. levels and egg counter class Snake(object): def __ini...
ze d['SnakeWidth'] = self.fat d['Borders'] = list(self.borders.keys()) print(d) if self.locked or self.paused: return if event.keysym in ('Left', 'Right', 'Up', 'Down'): if NOMOVE[event.keysym] == self.direction: #...
: id = self.canvas.drawSquare(coords, self.fat, fill=self.color) self.idstack.append(id) self.body.append(coords) def gameOverCondition(self): if self.flat_thorus: return (self.body.count(self.headcoord) == 2 or tuple(self.headcoord) in self.b...
felixink/labarge-engineering
setup.py
Python
mit
1,191
0
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_d...
version='0.0', description='labarge_engineering', long_description=README + '\n\n' + CHANGES, classifiers=[ 'Programming Language :: Python', 'Framework :: Pyramid', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', ], author='',...
require={ 'testing': tests_require, }, install_requires=requires, entry_points={ 'paste.app_factory': [ 'main = labarge_engineering:main', ], }, )
wathsalav/xos
xos/model_policies/model_policy_ControllerSlice.py
Python
apache-2.0
573
0.015707
def handle(controller_slic
e): from core.models import ControllerSlice, Slice try: my_status_code = int(controller_slice.backend_status[0]) try:
his_status_code = int(controller_slice.slice.backend_status[0]) except: his_status_code = 0 if (my_status_code not in [0,his_status_code]): controller_slice.slice.backend_status = controller_slice.backend_status controller_slice.slice.save(update_fields = ['backen...
erstrom/opencv-home-cam
opencv_home_cam/recorder.py
Python
mit
3,907
0.001024
import cv2 from collections import namedtuple import logging import re import os RecorderConfig = namedtuple('RecorderConfig', ['file_limit', 'time_limit', 'directory', 'file_base'], ...
self._fps, self._resolution) self._nbr_of_outfiles += 1 self._cur_nbr_of_recorded_frames = 0 def _remove_old_video_file(self): directory = self._directory base = self._file_base ext = self._ext oldest_filename...
f._cur_outfile_lowest_index) + ext self._logger.info("Removing old output file: %s", oldest_filename) os.remove(oldest_filename) # Update oldest and current index by rescanning all outfiles self._scan_video_files() def record_frame(self, frame): if self._cur_nbr_of_recorded...
ilexius/odoo
openerp/addons/base/ir/ir_values.py
Python
gpl-3.0
25,389
0.00449
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import pickle from openerp import tools from openerp.osv import osv, fields from openerp.exceptions import AccessError, MissingError from openerp.tools.translate import _ EXCLUDED_FIELDS = set(( 'report_sxw_content'...
help="Model to which this entry applies"), # TODO: model_id and action_id should be read-write function fields 'model_id': fields.many2one('ir.model', 'Model (change only)', size=128,
help="Model to which this entry applies - " "helper field for setting a model, will " "automatically set the correct model name"), 'action_id': fields.many2one('ir.actions.actions', 'Action (change only)', ...
soarpenguin/python-scripts
human_log.py
Python
gpl-3.0
2,511
0.000796
# adapted from https://gist.github.com/cliffano/9868180 import json import os FIELDS = os.environ.get('ANSIBLE_HUMAN_LOG_FIELDS') if FIELDS: FIELDS = FIELDS.split(',') if not FIELDS: FIELDS = ['stdout', 'stderr'] def human_log(callback, host, res): if hasattr(res, 'startswith'): if callback == '...
def playbook_on_notify(self, host, handler): pass def playbook_on_no_hosts_matched(self): pass def playbook_on_no_hosts_remaining(self): pass def playbook_on_task_start(self, name, is_conditional): pass def playbook_on_vars_prompt(self, varname, private=True, prom...
t=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None): pass def playbook_on_setup(self): pass def playbook_on_import_for_host(self, host, imported_file): pass def playbook_on_not_import_for_host(self, host, missing_file): pass def playbook_on_p...
kaedroho/django
tests/builtin_server/tests.py
Python
bsd-3-clause
5,660
0.000177
import sys import traceback from io import BytesIO from unittest import TestCase from wsgiref import simple_server from django.core.servers.basehttp import get_internal_wsgi_application from django.test import RequestFactory, override_settings from .views import FILE_RESPONSE_HOLDER # If data is too large, socket wi...
roperly(TestCase): """ The ServerHandler c
hunks data properly. Tests for #18972: The logic that performs the math to break data into 32MB (MAX_SOCKET_CHUNK_SIZE) chunks was flawed, BUT it didn't actually cause any problems. """ def test_chunked_data(self): env = {'SERVER_PROTOCOL': 'HTTP/1.0'} handler = WriteChunkCounterHa...
openelections/openelections-core
openelex/us/vt/validate/__init__.py
Python
mit
64
0
from __future__ i
mport absolute_import f
rom .validates import *
fahadshaon/tv_tracker
db.py
Python
mit
3,213
0.001867
import logging from datetime import datetime from core import app from sqlalchemy import inspect from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Show(db.Model): show_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) link = db.Column(db.String(255)) c...
db.Column(db.Integer, primary_key=True) show_id = db.Column(db.Integer, db.ForeignKey('show.show_id')) episode_number = db.Column(db.Integer) season_number = db.Column(db.Integer) season_episode_number = db.Column(db.Integer) air_date = db.Column(db.Date) title = db.Column(db.String(255)) li...
d = db.Column(db.String(1)) # show = db.relationship("Show", backref=db.backref("episodes", order_by=episode_id)) __table_args__ = ( db.UniqueConstraint('show_id', 'season_number', 'season_episode_number', name='_show_session_epi_uc'),) def __int__(self, episode_id, show_id, episode_number, season_...
SFTtech/sftmake
conf_smfile.py
Python
gpl-3.0
1,455
0.024742
#!/usr/bin/python3 # this file is, again, part of [sft]make # # licensed GPLv3 or later, no warranty, gschichten. # # as the sftmake config language and its parsing is struggling # in development, this is an attempt to sftmake configuration # via the regular python language # # (c) 2013 [sft]technologies, jonas jelten...
return self.content def run(self): raise NotImplementedError("run method must be implemented") def get_associated_smname(self): return self.fileobj.get_associated_smname() def smfile_factory(fobj): if not isinstance(fobj, dirscanner.simple_file): raise Exception("smfile creation needs to have a dirscanner...
mfile import pysmfile smfile = pysmfile(fobj) return smfile #TODO: smlang smfile else: raise Exception("only python smfiles supported yet.") # smlang conf file # from conf_smsmfile import smsmfile # smfile = smsmfile(filepath) # return smfile
jjbrophy47/sn_spam
relational/scripts/comments.py
Python
mit
3,047
0.001313
""" Spam comments to be classified by the relational model. """ import os import numpy as np class Comments: """Class to write comment predicate data for the relational model.""" def __init__(self, config_obj, util_obj): """Initializes object dependencies.""" self.config_obj = config_obj ...
a_f: folder to store data.""" ev = open(data_f + dset + '_evidence.txt', 'w') q = open(data_f + dset + '_query.txt', 'w') for index, row in df.iterrows(): pred = row.ind_pred com_id = str(int(row.com_id)) wgt = str(np.log(self.util_obj.div0(pred, (1 - pred)))
) ev.write('Indpred(' + com_id + ', ' + wgt + ')\n') q.write('Spam(' + com_id + ')\n') ev.close() q.close()
sendgridlabs/ddbmock
tests/unit/test_item_field_comparison.py
Python
lgpl-3.0
6,663
0.0009
# -*- coding: utf-8 -*- import unittest class TestItemFieldComparison(unittest.TestCase): def test_eq(self): from ddbmock.database.comparison import eq self.assertTrue(eq({u'S':
u'waldo'}, {u'S': u'waldo'})) self.assertFalse(eq({u'S': u'waldo'}, {u'S': u'on-time'})) self.assertFalse(eq(None, {u'S': u'on-time'})) def test_ne(self): from ddbmock.database.comparison import ne self.assertFalse(ne({u'S': u'waldo'}, {u'S': u'waldo'})) self.assertTrue(ne...
u'on-time'})) def test_le(self): from ddbmock.database.comparison import le self.assertTrue(le({u'S': u'waldo'}, {u'S': u'waldo'})) self.assertTrue(le({u'S': u'waldo'}, {u'S': u'waldo1'})) self.assertFalse(le({u'S': u'waldo'}, {u'S': u'wald'})) self.assertTrue(le({u'N': u...
robinwyss/raspberry-scripts
config.py
Python
mit
606
0.006601
__author__ = 'robinwyss' import ConfigParser Config = ConfigParser.ConfigParser() Config.read("config.ini") def configSectionMap(section): dict1 = {} options = Config.options(sec
tion) for option in options: try: dict1[option] = Config.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option)
except: print("exception on %s!" % option) dict1[option] = None return dict1 def getFtpConfig(): return configSectionMap("FTP") def getCameraConfig(): return configSectionMap("Camera")
nrser/qb
dev/scratch/docker/image/qb_docker_image.scratch.py
Python
mit
26,930
0.004753
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['prev...
l registry docker_image: name: centos repository: localhost:5000/centos tag: 7 push: yes - name: Remove image docker_image: state: absent name: registry.ansible.com/chouseknecht/sinatra tag: v1 - name: Build an image and push it to a private repo docker_image: path: ./sinatra...
Archive image docker_image: name: registry.ansible.com/chouseknecht/sinatra tag: v1 archive_path: my_sinatra.tar - name: Load image from archive and push to a private registry docker_image: name: localhost:5000/myimages/sinatra tag: v1 push: yes load_path: my_sinatra.tar - name: Build ...
wasit7/book_pae
pae/forcast/src/csv/CS_table_No5_A.py
Python
mit
193
0.005181
# -*- coding: utf-8 -*- """ Created on Wed Sep 09 15:12:07 2015 @author: Administrator """
import pandas as pd data = pd.read_csv('D:\\project\\forcast\\data\\
CS_table_No5_A.csv') print data
iulian787/spack
var/spack/repos/builtin/packages/py-unicycler/package.py
Python
lgpl-2.1
1,554
0.002574
# Copyright 2013-2020 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 PyUnicycler(PythonPackage): "
""Unicycler is an assembly pipeline for bacterial genomes. It can assemble Illumina-only read sets where it functio
ns as a SPAdes-optimiser. It can also assembly long-read-only sets (PacBio or Nanopore) where it runs a miniasm+Racon pipeline. For the best possible assemblies, give it both Illumina reads and long reads, and it will conduct a hybrid assembly. """ homepage = "https://github.com/rrwick/Unicycler" ...
LordDarkula/chess_py
chess_py/players/human.py
Python
mit
994
0
# -*- coding: utf-8 -*- """ Included class for human interaction via console. Prints position and takes move written in algebraic notation as string input Copyright © 2016 Aubhro Sengupta. All rights reserved. """ from chess_py.core.algebraic import converter from chess_py.players.player import Player try: inpu...
_input except NameError: pass class Human(Player): def __init__(self, input_color): """ Creates interface for human player. :type: input_color: Color """ super(Human, self).__init__(input_color) def
generate_move(self, position): """ Returns valid and legal move given position :type: position: Board :rtype: Move """ while True: print(position) raw = input(str(self.color) + "\'s move \n") move = converter.short_alg(raw, self.color...
sjdv1982/seamless
seamless/highlevel/HelpMixin.py
Python
mit
688
0.001453
class HelpMixin: @property def help(self): from .Help import HelpCell if self._path[:1] == ("HELP",): raise AttributeError("Help cells can't have help") return HelpCell(self) @help.setter def help(self, value): from .Help import HelpCell wrapper = Hel...
self.self.help.value elif name in self.__dict__:
return self.__dict__[name] return super().__getattribute__(name)
kierse/mediarover
mediarover/source/nzbmatrix/item.py
Python
gpl-3.0
2,929
0.019461
# Copyright 2009 Kieran Elliott <kierse@mediarover.tv> # # Media Rover is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Media Rover...
s- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def __
init__(self, item, type, priority, quality, delay, size=0, title=None, url=None): """ init method expects a DOM Element object (xml.dom.Element) """ self._type = type self._priority = priority self._quality = quality self.__delay = delay if item is None: self._size = size self._title = title self...
wtttc/apkshrink
lib_apk_shrink/instrument/JarDecompile.py
Python
mit
1,608
0.001926
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import shutil from lib_apk_shrink.model.DecompileConfig import DecompileConfig __author__ = 'tiantong' class JarDecompile(object): decompile_config = DecompileConfig() output_path_decompile = "" output_path
_out = "" def __init__(self, decompileConfig=DecompileConfig()): self.decompile_config = decompileConfig def decompile_jar(self): jad_path = self.decompile_config.jad_path output_path = self.decompile_config.output_path # 删除以前的文件夹 self.output_path_out = os.path.join(ou...
= os.path.join(output_path, 'decompile') self.clearOutput(); # 确保文件夹存在 if not os.path.exists(self.output_path_out): os.makedirs(self.output_path_out) # 删除无用的 META-INF META_path = os.path.join(self.output_path_out, 'META-INF') # 解压jar for jar_path i...
mrnoodles/AI-Pygame
models/projectiles.py
Python
cc0-1.0
1,123
0.003562
# Projectiles import pygame import environment from models import Projectile class
Laser(Projectile): def __init__(self, laser_x, laser_y, sign=None, speed=20): self.laser_height = 20 self.laser_width = environment.WINDOW_WIDTH - laser_x self.laser_rect = pygame.Rect(laser_x, laser_y, self.laser_width, self.laser_height) Projectile.__init__(self, self.laser_rect, ...
et(Projectile): """ def __init__(self, spawn_x, spawn_y): self.bullet_width = 10 self.bullet_height = 3 self.bullet_rect = pygame.Rect(spawn_x, spawn_y, self.bullet_width, self.bullet_height) Projectile.__init__(self, self.bullet_rect) self.base_speed = 20 """ def __i...
eoncloud-dev/eontools
latency_dump.py
Python
apache-2.0
1,467
0.027948
#!/usr/bin/env python import json import argparse latencys = [ { 'osd':[ 'op_latenc
y', 'op_process_latency', 'op_r_latency', 'op_r_process_latency', 'op_w_rlat', 'op_w_latency', 'op_w_process_latency', 'op_rw_rlat', 'op_rw_process_latency', 'subop_latency', 'subop_w_latency', 'subop_pull_latency', 'subop_push_latency', ] }, { 'filestore':[
'journal_latency', 'commitcycle_latency', 'apply_latency', 'queue_transaction_latency_avg', ] } ] def format_data(item, sum, avgcount): try: result = sum / avgcount * 1000 except ZeroDivisionError: result = 0 formatdata = '%-30s | %-30f | %-30f | %-30f' %(item, sum, avgcount, re...
Louis31415/opugStore
Store/polls/migrations/0001_initial.py
Python
mit
1,230
0.003252
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-15 05:57 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
0)), ('votes', mo
dels.IntegerField(default=0)), ], ), migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question_text', models.CharField(max_length=200)...
meejah/crossbarexamples
authentication/cryptosign/dynamic/authenticator.py
Python
apache-2.0
4,674
0.011339
############################################################################### ## ## Copyright (C) Tavendo GmbH and/or collaborators. All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1....
ons in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED W...
ICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## I...
asoplata/dynasim-benchmark-brette-2007
Brian2/brian2_benchmark_COBAHH_clocksyn_hidens_compiled_0001.py
Python
gpl-3.0
3,932
0.002036
""" # Notes: - This simulation seeks to emulate the COBAHH benchmark simulations of (Brette et al. 2007) using the Brian2 simulator for speed benchmark comparison to DynaSim. However, this simulation includes CLOCK-DRIVEN synapses, for direct comparison to DynaSim's clock-driven architecture. The synaptic connec...
P, # model='''ds/dt=1000.*2.*(1 + tanh(v_pre/(4.*mV)))*
(1-s)/ms - s/(5*ms) : 1 (clock-driven) # sGABAAtotal_post = s : 1 (summed) # ''') # sGABAA_RETC.connect(p=0.90) # Initialization P.v = 'El + (randn() * 5 - 5)*mV' # Record a few traces trace = StateMonitor(P, 'v', record=[1, 10, 100]) totaldata = StateMonitor(...
byteface/sing
core/_meta.py
Python
gpl-2.0
742
0.045822
""" _meta.py @author: byteface """ class _meta(object): """ parser to the meta.json on each object """ # TODO -
may get rid in favour of a config obj with regular python vars. setup on the commands path=None data=None def __init__( self, path ): """ meta for each object. initialised by Program passes the path """ self.path = path import js
on with open(self.path+"/_meta.json") as json_file: # print "open file" self.data = json.load(json_file) def get(self,meta_type): """ getter for json nodes """ return self.data[meta_type] def get_property(self,meta_type,prop): """ getter for props on json nodes """ return self.data[meta_type][prop...
hforge/itools
test/test_ical.py
Python
gpl-3.0
16,037
0.001373
# -*- coding: UTF-8 -*- # Copyright (C) 2005-2010 J. David Ibáñez <jdavid.ibp@gmail.com> # Copyright (C) 2006-2007 Nicolas Deram <nderam@gmail.com> # Copyright (C) 2010 Alexis Huet <alexis@itaapy.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public...
CRIPTION'] = value member = '"mailto:DEV-GROUP@host2.com"' value = Property('mailto:darwin@itaapy.com', MEMBER=[member]) properties['ATTENDEE'] = value uid = cal.add_component('VEVENT', **properties)
event = cal.get_component_by_uid(uid) properties = event.get_property_values() self.assertEqual('MYADD' in properties, True) self.assertEqual('DESCRIPTION' in properties, True) self.assertEqual('ATTENDEE' in properties, True) self.assertEqual('VERSION' in properties, False) ...
himyouten/ansible
lib/ansible/runner/action_plugins/assemble.py
Python
gpl-3.0
5,733
0.002791
# (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com> # Stephen Fromm <sfromm@gmail.com> # Brian Coca <briancoca+dev@gmail.com> # # 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 publish...
OR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have receive
d a copy of the GNU General Public License import os import os.path import pipes import shutil import tempfile import base64 from ansible import utils from ansible.runner.return_data import ReturnData class ActionModule(object): TRANSFERS_FILES = True def __init__(self, runner): self.runner = runner...