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
Ikusaba-san/Chiaki-Nanami
chiaki.py
Python
mit
4,858
0.004529
#!/usr/bin/env python3 import asyncio import contextlib import datetime import functools import importlib import itertools import logging import os import sys import traceback import click import discord import config from cogs.utils import db from core import Chiaki, migration # use faster event loop, but fall bac...
de, verbose=verbose)) @main.command() @click.option('--version', default='', metavar='[version]', help='Version to migrate to, defaults to latest') @click.option('-v', '--ve
rbose', is_flag=True) def upgrade(version, verbose): """Upgrade the database to a version""" _sync_migrate(version, downgrade=False, verbose=verbose) click.echo('Upgrade successful! <3') @main.command() @click.option('--version', default='', metavar='[version]', help='Version to migrate to, defaults to lat...
brupoon/pipya
pipya.py
Python
gpl-3.0
3,093
0.005496
# -*- coding: utf-8 -*- """ pipya main cli file Copyright (c) 2015 Brunston Poon 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. Full license in LICENCE.txt """ #IMPORT IMPORT IMPORT IMPO...
() elif uin in ["jellyfish"]: h.jellyfish
() else: print("Pipya: Sorry, {0}, I didn't quite catch that.".format(user)) if (__name__ == '__main__') and (toggle==True): main()
hackultura/octofiles
docs/source/conf.py
Python
gpl-3.0
11,319
0.006538
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Octofiles documentation build configuration file, created by # sphinx-quickstart on Thu Mar 10 14:51:08 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # ...
nerated. #html_use_index = True # If true, the index is split into individual pag
es for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True....
n8foo/cigarbox
app.py
Python
apache-2.0
223
0.004484
#!/usr/bin/env
python # -*- coding:utf-8 -*- from flask import Flask from config import * # create the app app = Flask(__name__) # Load default config and override config from config fil
e app.config.from_object('config')
jordanemedlock/psychtruths
temboo/core/Library/Amazon/IAM/GetLoginProfile.py
Python
apache-2.0
3,876
0.005418
# -*- coding: utf-8 -*- ############################################################################### # # GetLoginProfile # Retrieves the user name
and password create date for the specified user. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo 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/li...
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. # # ############################################################################### from temboo.core.choreog...
Forage/Gramps
gramps/plugins/lib/libsubstkeyword.py
Python
gpl-2.0
48,355
0.007424
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Craig J. Anderson # # 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 ...
ue where = code.find(self.string_in.this.lower()) else: where = code.find(self.string_in.this) if where != -1: self.string_in.step() tmp = function[where]() if to_upper: tmp = tmp.upper
() if tmp == "" or tmp is None: main.add_remove() elif isinstance(tmp, VarString): #events cause this main.extend(tmp) else: main.add_variable(tmp) elif separator.is_a(): main.add_sep...
takmid/inasafe
safe_qgis/dock.py
Python
gpl-3.0
73,919
0.00188
""" InaSAFE Disaster risk assessment tool developed by AusAid - **GUI Dialog.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either vers...
self.setLayerNameFromTitleFlag = True self.zoomToImpactFlag = True self.hideExposureFlag = True self.hazardLayers = None # array of all hazard layers self.exposureLayers = None # array of all exposure layers self.readSettings() # getLayers called by this self.setOkBut...
self.initPostprocessingOutput() myButton = self.pbnHelp QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'), self.showHelp) myButton = self.pbnPrint QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'), sel...
nmccrory/job-visualization
jobvisualization/apps/data_storage/migrations/0003_auto_20150728_2302.py
Python
apache-2.0
953
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('data_storage', '0002_auto_20150727_2312'), ] operations = [ migrations.RenameField( model_name='readonly', ...
=False, ), migrations.AddField( model_name='writeonly', name='stateName', field=models.TextField(default='sexy cindy'), preserve_default=False, ),
]
jhosmer/find_unicode
find_unicode.py
Python
gpl-2.0
1,875
0.005867
#!/usr/bin/python # find_unicode.py # # Author: Jonathan Hosmer # Date: Sun Feb 15 14:06:15 2015 # import os import sys def help(): print 'Usage: {} [file, [dir, [file, ..]]]'.format(__file__) print 'Displays line:character position of all non-ascii Unicode character(s) in a file' def main(): args = sys....
_i, char in enumerate(line): if ord(char) > 126: chars.append(char) else: if chars: print out_str.format(fname, line_i+1, char_i+1-len(chars), chars=''.join(chars)) ...
if __name__ == '__main__': sys.exit(main())
Nosferatul/coala
tests/output/JSONEncoderTest.py
Python
agpl-3.0
2,948
0
import json import re import unittest from datetime import datetime from coalib.output.JSONEncoder import create_json_encoder class TestClass1(object): def __init__(self): self.a = 0 class TestClass2(object): def __init__(self): self.a = 0 self.b = TestClass1() class TestClass3(...
kw)) def test_propertied_class(self): uut = PropertiedCl
ass() self.assertEqual('{"prop": 5}', json.dumps(uut, **self.kw)) def test_jsonable_class(self): uut = JSONAbleClass() self.assertEqual('["dont", "panic"]', json.dumps(uut, **self.kw)) def test_type_error(self): with self.assertRaises(TypeError): json.dumps(1j, **se...
sandvine/horizon
openstack_dashboard/dashboards/project/routers/views.py
Python
apache-2.0
9,121
0
# Copyright 2012, Nachi Ueno, NTT MCL, Inc. # Copyright 2013, Big Switch Networks, 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...
port filters from openstack_dashboard.dashboards.project.routers\ import forms as project_forms from openstack_dashboard.dashboards.projec
t.routers import tables as rtables from openstack_dashboard.dashboards.project.routers import tabs as rdtabs class IndexView(tables.DataTableView): table_class = rtables.RoutersTable template_name = 'project/routers/index.html' page_title = _("Routers") FILTERS_MAPPING = {'admin_state_up': {_("up"): T...
JoakimLindbom/ago
tellstick/tellstickduo.py
Python
gpl-3.0
7,092
0.005781
#!/usr/bin/python AGO_TELLSTICK_VERSION = '0.0.9' """ ############################################ # # Tellstick Duo class # # Date of origin: 2014-01-25 # __author__ = "Joakim Lindbom" __copyright__ = "Copyright 2014, Joakim Lindbom" __credits__ = ["Joakim Lindbom", "The ago control team"] __license__ = "GP...
sterSensorEvent(self, deviceEvent): self.SensorEvent = deviceEvent return td.registerSensorEvent(self.SensorEventInterceptor) def listSensors(self): sensors = td.listSensors() if len(sensors) != 0: for id, value in sensors.iteritems(): self.log.trace("li...
if devId not in self.sensors: if value["isTempSensor"]: # New temp sensor found self.sensors[devId] = self.newTempSensor(devId, value["model"], value["temp"]) devId = str(id) + "-hum" if devI...
pquentin/libcloud
libcloud/test/storage/test_azure_blobs.py
Python
apache-2.0
38,350
0.000078
# 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 use ...
AGE_CHUNK_SIZE from libcloud.test import unittest from libcloud.test import MockHttp, generate_random_data # pylint: disable-msg=E0611 from libcloud.test.file_fixtures import StorageFileFixtures # pylint: disable-msg=E0611 from libcloud.test.secrets import ST
ORAGE_AZURE_BLOBS_PARAMS class AzureBlobsMockHttp(MockHttp, unittest.TestCase): fixtures = StorageFileFixtures('azure_blobs') base_headers = {} def _UNAUTHORIZED(self, method, url, body, headers): return (httplib.UNAUTHORIZED, '', self.base_headers, ...
aroth-arsoft/arsoft-web-crashupload
app/crashdump/model.py
Python
gpl-3.0
24,814
0.00129
#!/usr/bin/python # -*- coding: utf-8 -*- # kate: space-indent on; indent-width 4; mixedindent off; indent-mode python; import re import copy import os from trac.resource import Resource, ResourceNotFound from trac.util.translation import _ from trac.util.datefmt import from_utimestamp, to_utimestamp, utc, utcmax from...
self.status = None self.uuid = uuid self.env = env self._changes = None self.resource = Resource('crash', uuid, version) self.fields = CrashDumpSystem(self.env).get_crash_fields() self.std_fields, self.custom_fields
, self.time_fields = [], [], [] for f in self.fields: if f.get('custom'): self.custom_fields.append(f['name']) else: self.std_fields.append(f['name']) if f['type'] == 'time': self.time_fields.append(f['name']) self.value...
michhar/notedown
notedown/__init__.py
Python
bsd-2-clause
338
0
from __future__ import absolute_import from .notedown import * from .main impor
t convert, markdown_template, __version__ # avoid having to require the notebook to install notedown try: from .contentsmanager import NotedownContentsManager except ImportError:
NotedownContentsManager = 'You need to install the jupyter notebook.'
andrei4ka/fuel-web-redhat
nailgun/nailgun/test/integration/test_db_refresh.py
Python
apache-2.0
1,879
0
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complianc
e with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, eit...
icense. from datetime import datetime from unittest import TestCase from paste.fixture import TestApp from sqlalchemy import orm from nailgun.db import engine from nailgun.db import flush from nailgun.db import NoCacheQuery from nailgun.db.sqlalchemy.models import Node from nailgun.wsgi import build_app class Test...
alexykot/bitfund
bitfund/project/migrations/0006_auto__del_field_project_dependencies_is_public.py
Python
gpl-3.0
11,471
0.008195
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Project_Dependencies.is_public' db.delete_column('project_project_dependencies', 'is_publi...
oField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharFi...
ique_together': "(('project', 'key'),)", 'object_name': 'ProjectGoal'}, 'amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '12', 'decimal_places': '0'}), 'brief': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'date_added': ('djan...
rbuffat/pyidf
tests/test_chillerelectricreformulatedeir.py
Python
apache-2.0
10,596
0.005379
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.plant_heating_and_cooling_equipment import ChillerElectricReformulatedEir log = logging.getLogger(__name__) class TestChillerElectricReformulatedEir(unittest.TestCase): def...
gh_temperature_limit_schedule_name = var_heat
_recovery_inlet_high_temperature_limit_schedule_name # node var_heat_recovery_leaving_temperature_setpoint_node_name = "node|Heat Recovery Leaving Temperature Setpoint Node Name" obj.heat_recovery_leaving_temperature_setpoint_node_name = var_heat_recovery_leaving_temperature_setpoint_node_name ...
Thortoise/Super-Snake
Blender/animation_nodes-master/nodes/mesh/generation/line.py
Python
gpl-3.0
799
0.010013
import bpy from .... base_types.node import AnimationNode class LineMeshNode(bpy.types.Node, AnimationNode): bl_idname = "an_LineMeshNode" bl_label = "Line Mesh" def create(self): self.newInput("Vector", "Start", "start") self.newInput("Vector", "End", "end", value = [0, 0, 10]) se...
e = 2) self.newOutput("Vector List", "Vertices", "vertices") self.newOutput("Edge Indices List", "Edge Indices", "edgeIndices") def execute(self, start, end, steps): steps = max(steps, 2) divisor = steps - 1 vertices = [start * (1 - i / divisor) + end * i / divisor for i in ...
- 1)] return vertices, edges
uw-it-aca/mdot-developers
travis-ci/manage.py
Python
apache-2.0
252
0
#!/usr/bin/env pytho
n import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "travis-ci.settings") from django.core.management import execute_from_command_line execute_fro
m_command_line(sys.argv)
Saruus/drPencilcode
app/migrations/0015_survey_question2.py
Python
agpl-3.0
435
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db impor
t models, migrations class Migration(migrations.Migration): dependencies = [ ('app', '0014_survey'), ] operations = [ migrations.AddField( model_name='survey', name='question2', field=models.CharField(default=50, max_length=50),
preserve_default=False, ), ]
davy39/eric
Helpviewer/History/HistoryDialog.py
Python
gpl-3.0
5,112
0.003912
# -*- coding: utf-8 -*- # Copyright (c) 2009 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a dialog to manage history. """ from __future__ import unicode_literals from PyQt5.QtCore import pyqtSignal, Qt, QUrl from PyQt5.QtGui import QFontMetrics, QCursor from PyQt5.QtWidgets import QD...
self.__historyManager = manager if self.__historyManager is None: import Helpviewer.HelpWindow self.__historyManager = \ Helpviewer.HelpWindow.HelpWindow.historyManager() self.__model = self.__historyManager.historyTreeModel() self.__proxyMode...
elf.__proxyModel.setFilterKeyColumn(-1) self.__proxyModel.setSourceModel(self.__model) self.historyTree.setModel(self.__proxyModel) self.historyTree.expandAll() fm = QFontMetrics(self.font()) header = fm.width("m") * 40 self.historyTree.header().resizeSection(0, header) ...
cgmb/guardonce
tests/test_guess_guard.py
Python
mit
4,227
0.012302
# -*- coding: utf-8 -*- # Copyright (C) 2016-2018 Cordell Bloor # Published under the MIT License from nose.tools import * import guardonce.util as go def test_ok(): contents = ''' #ifndef MATCH_H #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) ...
f !defined( MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) def test_if_defined_space_after_symbol(): contents =
''' #if !defined(MATCH_H ) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) def test_if_defined_space_before_newline(): contents = ''' #if !defined(MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert...
wevoice/wesub
apps/videos/management/commands/load_thumbnails.py
Python
agpl-3.0
4,320
0.00787
from django.core.management.base import BaseCommand from django.conf import settings from utils.amazon import default_s3_store from videos.models import Video, VIDEO_TYPE_FLV, VIDEO_TYPE_HTML5 import urllib import os import commands import sys from django.core.exceptions import ImproperlyConfigured from django.core.fil...
ib.urlretrieve(video_url.url, path) self.print_to_console(u'Video saved.') else: self.print_to_console(u'File exist.') self.get_thumbnail(video, path) self.print_to_console(u'-----------------') #--- Save ...
nail='').filter(s3_thumbnail='') for video in qs: self.print_to_console(u'Handling %s' % video.__unicode__()) name = video.thumbnail.strip('/').split('/')[-1] cf = ContentFile(urllib.urlopen(video.thumbnail).read()) video.s3_thumbnail.save('%s/%s' % (...
TeachBoost/ansible
ansible.py
Python
mit
1,499
0
#! /usr/bin/python import bottle import settings from controller import admin as admin_controller from controller import email as email_controller app = application = bottle.Bottle() # Base url for regular users app.route(settings.BASEPATH, 'GET', admin_controller.index) app.route(settings.BASEPATH + '/', 'GET', adm...
'GET', admin_controller.read_user_tasks ) app.route( settings.BASEPATH + '/update/<id>', 'POST', admin_controller.update_self ) # Email handler email = bottle.Bottle() app.mount(settings.EMAIL_PATH, email) email.route('/', 'POST', email_controller.receive_email) email.route('/', 'GET', email_controlle...
oller.read_tasks) admin.route('/create', 'POST', admin_controller.create_person) admin.route('/delete', 'POST', admin_controller.delete_people) admin.route('/<id>', 'GET', admin_controller.read_person) admin.route('/<id>', 'POST', admin_controller.update_person) admin.route('/', 'GET', admin_controller.admin) # Static...
heyf/cloaked-octo-adventure
leetcode/1420_build-array-where-you-can-find-the-maximum-exactly-k-comparisons.py
Python
mit
550
0.003636
# https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: M = 1000000007 ret = 0 for i in range(k, m+1): ret += ((i-1)**(k-1)) * (i**(n-k)) return ret % M # n =...
m = 100 k = 25
ans = 34549172 # n = 37 # m = 17 # k = 7 # ans = 418930126 sl = Solution() ret = sl.numOfArrays(n, m, k) print(ret, "O" if ret==ans else "X")
materialsproject/pymatgen
pymatgen/phonon/tests/test_bandstructure.py
Python
mit
3,536
0.00198
import json import os import unittest from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine from pymatgen.util.testing import PymatgenTest class PhononBandStructureSymmLineTest(PymatgenTest): def setUp(self): with open( os.path.join(PymatgenTest.TEST_FILES_DIR, "NaCl_phonon_ba...
(PymatgenTest.TEST_FILES_DIR, "Si_phonon_bandstructure.json"), encoding="utf-8", ) as f: d = json.load(f) self.bs2 = PhononBandStructureSymmLine.from_dict(d) def test_basic(self):
self.assertAlmostEqual(self.bs.bands[1][10], 0.7753555184) self.assertAlmostEqual(self.bs.bands[5][100], 5.2548379776) self.assertArrayEqual(self.bs.bands.shape, (6, 204)) self.assertArrayEqual(self.bs.eigendisplacements.shape, (6, 204, 2, 3)) self.assertArrayAlmostEqual( s...
toenuff/treadmill
lib/python/treadmill/cli/show.py
Python
apache-2.0
4,580
0
"""Manage Treadmill app manifest.""" from __future__ import absolute_import import logging import urllib import click from .. import cli from treadmill import restclient from treadmill import context _LOGGER = logging.getLogger(__name__) _STATE_FORMATTER = cli.make_formatter(cli.InstanceStatePrettyFormatter) _EN...
.ON_REST_EXCEPTIONS @click.argument('pattern') @click.argument('endpoint', required=False) @click.argument('proto', required=False) def endpoints(pattern, endpoint, proto): """Show application endpoints.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_endpoints(apis, ...
') def instance(instance_id): """Show scheduled instance manifest.""" apis = context.GLOBAL.cell_api(ctx['api']) return _show_instance(apis, instance_id) del _all del running del scheduled del pending del instance del state del endpoints return show
mickypaganini/SSI2016-jet-clustering
spartyjet-4.0.2_mac/examples_py/pythiaExample.py
Python
mit
3,668
0.008179
#!/usr/bin/env python # $Id: pythiaExample.py 545 2012-01-18 06:10:03Z cvermilion $ #---------------------------------------------------------------------- # Copyright (c) 2010-12, Pierre-Antoine Delsart, Kurtis Geerlings, Joey Huston, # Brian Martin, and Christopher Vermilion # #-----------------------...
he Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # SpartyJet 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 General Publ...
c License # along with SpartyJet; if not, write to the Free Software # Foundation, Inc.: # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #---------------------------------------------------------------------- from spartyjet import SpartyJet as SJ, fastjet as fj, writeCurrentFile from ROOT import TPythi...
joelstanner/django-imager
imager/imager_images/urls.py
Python
mit
1,528
0.003927
from django.conf.urls import patterns, include, url from django.contrib import admin import views from django.contrib.auth.decorators import login_required urlpatterns = patterns('', url(r'^library$', views.library, name='profile-library'), url(r'^stream$', views.stream, name='profile-stream'), url(r'^add_...
e="imager_images/update_photo.html", success_url='/images/library')), name='update_photo'), url(r'^delete_photo/(?P<pk>\d+)/$', login_required(views.PhotoDelete.as_view( template_name="imager_images/delete_form.html", success_url='/images/library')), name='delete_photo'), ...
name='delete_album'), )
megaumi/django
tests/generic_relations/models.py
Python
bsd-3-clause
4,327
0.001156
""" Generic relations Generic relations let an object have a foreign key to any object through a content-type/object-id field. A ``GenericForeignKey`` field can point to any object, be it animal, vegetable, or mineral. The canonical example is tags (although this example implementation is *far* from complete). """ f...
ts having multiple GenericForeignKeys. One is defined through an inherited abstract model and one defined directly on this class. """ content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set") object_id2 = models.PositiveIntegerField() other_obj = GenericForeign...
obj, self.comparative, self.other_obj) @python_2_unicode_compatible class Animal(models.Model): common_name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) tags = GenericRelation(TaggedItem, related_query_name='animal') comparisons = GenericRelation(Comparison, ...
biomodels/BIOMD0000000462
BIOMD0000000462/model.py
Python
cc0-1.0
427
0.009368
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'BIOMD0000000462.xml') with open(sbmlFi
lePath,'r')
as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
toontownfunserver/Panda3D-1.9.0
direct/pyinst/archive_rt.py
Python
bsd-3-clause
7,405
0.017016
# # Gordon McMillan (as inspired and influenced by Greg Stein) # # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains pyt...
c(self): """ Overridable.
Default: After magic comes an int (4 byte native) giving the position of the TOC within self.lib. Default: The TOC is a marshal-able string. """ self.lib.seek(self.start + self.TOCPOS) (offset,) = struct.unpack('=i', self.lib.read(4)) self.lib.seek(self.start + offset) self....
acbilson/py-lex-lib
point.py
Python
gpl-3.0
593
0.016863
class Point: Empty = " " Full = "XX" def __init__(self, x, y): if not type(x) == int \ or not type(y) == int: raise Exception('Can only assign int type to x or y value') self.X = x self.Y = y self.Value = self.Empty def __eq__(self, other): if isinstance
(other, self.__class__): return self.X == other.X and self.Y == other.Y def __ne__(self, other): return not self.__eq__(other) def __str__(self): return "P(" + str(self.X) + "," + str(self.Y) + ")" d
ef __repr__(self): return "P(" + str(self.X) + "," + str(self.Y) + ")"
PennNLP/SLURP
download.py
Python
gpl-3.0
1,488
0.001344
#!/usr/bin/env python """Download data files needed by SLURP.""" # Copyright (C) 2012-2013 Constantine Lignos # # 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, ...
# 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/licen
ses/>. import os import gzip from datamanager import download, unzip # Assume that download.py and pennpipeline.py are located in the same # directory PIPELINE_NAME = "SUBTLEPipeline-master" ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) PIPELINE_URL = "https://github.com/PennNLP/SUBTLEPipeline/archive/maste...
davidcurrie/ci.docker.websphere-traditional
network-deployment/appserver/updateHostName.py
Python
apache-2.0
1,804
0.033259
##################################################################################### # # # Script to update Hostname # # ...
stname): nlist = AdminConfig.list('ServerIndex') attr=[["hostName", hostname ]] AdminConfig.modify(nlist,attr) AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName BOOTSTRAP_ADDRESS -host '+ hostname +' -port 2809 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName...
9202 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName CSIV2_SSL_SERVERAUTH_LISTENER_ADDRESS -host '+ hostname +' -port 9201 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName ORB_LISTENER_ADDRESS -host '+ hostnam...
Arvin-X/swarm
setup.py
Python
gpl-3.0
1,370
0.024818
from setuptools import find_packages from setuptools import setup with open('README.md') as f: setup( name = 'swarm', version = '0.5.0', author = 'arvin.x', author_email = 'arvin.x@icloud.com', description = 'A modular distributed penetration testing too...
'Progra
mming Language :: Python :: 2.6', ], )
BobWhitelock/termtris
termtris/debug.py
Python
mit
74
0.027027
import config def debug(*args): if config.DEBUG: print(*ar
gs)
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/compat/setup.py
Python
bsd-2-clause
371
0.005391
#!/usr/bin/env python from __future__ import division, print_function def co
nfiguration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('compat', parent_package, top_path)
return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
solex/django-odesk
django_odesk/auth/decorators.py
Python
bsd-3-clause
446
0.004484
from django.contrib.auth.decorators import user_passes_test from
django.contrib.auth.models import Group def group_required(names, login_url=None): """ Checks if the user is a member of a particular group (or at least one group from the list) """ if not hasattr(names,'__iter__'): names = [names] return user_passes_test(lambda u: u.groups.filter(name...
login_url=login_url)
openlmi/openlmi-doc
doc/python/lmi/scripts/logicalfile/lf_cmd.py
Python
gpl-2.0
3,427
0.003502
# LogicalFile Management Providers # # Copyright (C) 2013-2014 Red Hat, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright not...
Device file. Can be either block or character device. * Dir : Directory. * P
: Pipe file. * L : Symbolic link. * S : Unix socket. createdir Create a directory. The parent directory must exist. deletedir Delete a directory. The directory must be empty. show Show detailed information about target. Target can be any file ...
crlang/sublime-text---front-end-config
Data/Packages/CodeFormatter/CodeFormatter.py
Python
mit
6,068
0.000989
# @author Avtandil Kikabidze # @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com) # @link http://longman.me # @license The MIT License (MIT) import os import sys import sublime import sublime_plugin st_version = 2 if sublime.version() == '...
os.chmod(path, st.st_mode | stat.S_IEXEC) if st_version == 2: plugin_loaded() class CodeFormatterCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None, saving=None): run_formatter(self.view, edit, syntax=syntax, saving=saving) class CodeFormatterOpenTabsCommand(sublime_plu...
blime.active_window() for view in window.views(): run_formatter(view, edit, quiet=True) class CodeFormatterEventListener(sublime_plugin.EventListener): def on_pre_save(self, view): view.run_command('code_formatter', {'saving': True}) class CodeFormatterShowPhpTransformationsCommand(...
jelmer/xandikos
xandikos/vcard.py
Python
gpl-3.0
2,165
0.000924
# Xandikos # Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al. # # 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; version 3 # of the License or (at your option) any later version of # ...
# TODO(jelmer): Get data about what is invalid raise InvalidFileContents( self.content_type, self.content, "Invalid VCard file") @property def addressbook(self): if self._addressbook is None: import vobject text ...
.join(self.content).decode('utf-8', 'surrogateescape') try: self._addressbook = vobject.readOne(text) except vobject.base.ParseError as e: raise InvalidFileContents(self.content_type, self.content, str(e)) return self._addressbook
CiscoSystems/avos
openstack_dashboard/dashboards/project/data_processing/job_executions/tests.py
Python
apache-2.0
2,517
0
# Licens
ed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Licen...
S 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. from django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from openstack_dashboard impo...
Williams224/davinci-scripts
kstetappipieta/DNTupleMaker.py
Python
mit
3,046
0.017072
from Gaudi.Configuration import * from Configurables import GaudiSequencer from Configurables import DaVinci simulation=False from Configurables import EventNodeKiller eventNodeKiller = EventNodeKiller('DAQkiller') eventNodeKiller.Nodes = ['DAQ','pRec'] #MySequencer.Members+=[eventNodeKiller] from Configurables impo...
es import TupleToolDecayTreeFitter tuple.B0.addTool(TupleToolDecayTreeFitter("PVFit")) tuple.B0.PVFit.Verbose=True tuple.B0.PVFit.constrainToOriginVertex=True tuple.B0.PVFit.daughtersToConstrain = ["K*(892)0","eta_prime"] tu
ple.B0.ToolList+=["TupleToolDecayTreeFitter/PVFit"] from Configurables import TupleToolTISTOS tistos = tuple.B0.addTupleTool(TupleToolTISTOS, name="TupleToolTISTOS") tistos.VerboseL0=True tistos.VerboseHlt1=True tistos.VerboseHlt2=True tistos.TriggerList=["L0PhotonDecision", "L0ElectronDecision", ...
vinder/django-instaforms
templatetags/instaforms_tags.py
Python
mit
1,416
0.003531
import logging from django import template from django.conf import settings from django.core.urlresolvers import reverse from django.http import Http404 from apps.dasforms.forms import ContactForm from apps.dasforms.utils import
get_form register = template.Library() logger = logging.getLogger(__name__) @register.inclusion_tag('dasforms/inline_form.html', takes_context=True) def render_inline_form(context, formtype): """Render inline form.""" formtype = formtype.encode('utf8') try: formclass = get_form(formtype) ...
:formtype}) except: logger.warning('Form class could not be found: %s' % formtype) form = ContactForm() action = reverse("dasform", kwargs={'formtype':'ContactForm'}) senturl = reverse("sent") return { 'action': action, 'form': form, 'formtype': formtype, ...
mavlyutovrus/light_search
lib/utils.py
Python
mit
1,167
0.010283
#-*- coding:utf8 -*- def crawl_folder(folder): import os os_objects = [] seen = set([folder]) for os_object_name in os.listdir(folder): full_path = os.path.normpath(os.path.join(folder, os_object_name)) if not full_path in seen: os_objects.append((full_path, os_object_name...
self.value = 0 def add(self): from datetime import datetime self.value += 1 if self.verbosity and self.value % self.interval == 0: self.log_stream.write("Logger: " + self.name + ", value: " + str(self.value) + ", time: " + str(datetime.now())+ "\n") self.log_st...
+ str(datetime.now())+ "\n") self.log_stream.flush()
qkzk/sncf_lcd
adafruit_lcd/examples/red.py
Python
gpl-3.0
1,310
0.003817
#!/usr/bin/python # Example using an RGB character LCD wired directly to Raspberry Pi or BeagleBone Black. import time import Adafruit_CharLCD as LCD # Raspberry Pi configuration: lcd_rs = 27 # Change this to pin 21 on older revision Raspberry Pi's lcd_en = 22 lcd_d4 = 25 lcd_d5 =
24 lcd_d6 = 23 lcd_d7 = 18 lcd_red = 4 lcd_green = 17 lcd_blue = 7 # Pin 7 is CE1 # Define LCD column and row size for 16x2 LCD. lcd_columns = 16 lcd_rows =
2 # Initialize the LCD using the pins above. lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue) # Show some basic colors. lcd.set_color(1.0, 0.0, 0.0) lcd.clear() lcd.message('Joyeux') time.sleep(3...
kumar303/addons-server
src/olympia/core/tests/test_logger.py
Python
bsd-3-clause
2,279
0
# -*- coding: utf-8 -*- import logging from unittest import mock impor
t olympia.core.logger from olympia.amo.tests import TestCase from olympia.users.models import UserProfile class LoggerTests(TestCase): @mock.patch('olympia.core.get_remote_addr', lambda: '127.0.0.1') @mock.patch('olympia.core.get_user', lambda: UserProfile(username=u'fôo')) def test_get_logger_adapter(se...
{ 'extra': { 'REMOTE_ADDR': '127.0.0.1', 'USERNAME': u'fôo', } } assert log.process('test msg', {}) == ('test msg', expected_kwargs) @mock.patch('olympia.core.get_remote_addr', lambda: '127.0.0.1') @mock.patch('olympia.core.get_user', lam...
adlnet/ADL_LRS
lrs/managers/AgentProfileManager.py
Python
apache-2.0
5,034
0.001589
import json import datetime from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.utils.timezone import utc from ..models import AgentProfile from ..exceptions import IDNotFoundError, ParamError from ..utils import etag class AgentProfileManager(): def __...
d'], agent=self.Agent) post_profile = request_dict['profile'] # If incoming profile is application/json and if a profile didn't # already exist with the same agent and profileId if created: p.json_profile = post_profile p.content_type = "application/json" ...
else: orig_prof = json.loads(p.json_profile) post_profile = json.loads(post_profile) merged = json.dumps( dict(list(orig_prof.items()) + list(post_profile.items()))) p.json_profile = merged p.etag = etag.create_tag(merged) # S...
acsone/hr
hr_expense_product_policy/tests/__init__.py
Python
agpl-3.0
156
0
# -*- coding: utf-8 -*- # © 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/li
censes/ag
pl.html). from . import test_hr_expense
sysadminmatmoz/odoo-clearcorp
account_invoice_incoterm/models/__init__.py
Python
agpl-3.0
153
0
# -*- coding: utf-8 -*- # © 2016 ClearCorp # License AGPL-3.0 or later (http://www.gnu.or
g/licenses/agpl.html). from .
import account_invoice_incoterm
sk-rai/Intro-to-SPARK-with-Python
code/sales/sales_schema.py
Python
unlicense
899
0.053393
import datetime class Store: def parse(self,line): fields=line.split('\t') self.id = fields[0] self.name = fields[1] return self def __repr__(self): return "Store: id=%s \t name=%s"%(self.id,self.name) class Product: def parse(self,line): fields=line.split('\t') self.id = fields[0] self.name = fi...
# self.day=datetime.datetime.strptime(fields[0],"%Y-%m-%d") self.store_id=fields[1] self.product_id=fields[2] self.quantity=int(fields[3]) # let's parse this return self def __repr__(self): return "SaleRow: day=%s \t store_id=%s \t product_id=%s quantity=%d"%(self.day,self.store_id,self.product_id, self.qu...
googleapis/python-artifact-registry
google/cloud/artifactregistry_v1beta2/services/artifact_registry/pagers.py
Python
apache-2.0
25,894
0.00197
# -*- coding: utf-8 -*- # Copyright 2022 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...
sponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata. """ self._method = method self._request = repository.ListRepositoriesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response,...
noahgoldman/adbpy
tests/test_adb.py
Python
mit
2,479
0.006858
from mock import MagicMock, patch import pytest from adbpy.adb import Adb from adbpy import Target, AdbError @pytest.fixture def adb(): adb = Adb(()) adb.socket = MagicMock() return adb def test_get_transport(): assert Adb._get_transport(Target.ANY) == "host:transport-any" assert Adb._get_transp...
adb.socket.send.assert_called_once_with("host:version") def test_adb_get_serialno_any(adb): adb.get_serialno(Target.ANY) adb.socket.send.assert_called_once_with("host:get-serialno") def test_adb_get_serialno_serial(adb): adb.get_serialno("6097191b") adb.socket.send.assert_called_once_with("host-seria...
adb_get_devpath(adb): adb.get_devpath(Target.USB) adb.socket.send.assert_called_once_with("host-usb:get-devpath") def test_adb_get_state(adb): adb.get_state(Target.EMULATOR) adb.socket.send.assert_called_once_with("host-local:get-state") def test_shell(adb): with patch.object(Adb, "_setup_target")...
gravufo/commotion-router-testbench
ping/mainTest.py
Python
gpl-2.0
479
0.004175
from netools import nextIpInPool, ping, aliveHost, hostsUnDone def main(): aliveHosts = [] # pool IP ipStart = "192.168.56.1" ipEnd = "192.168.56.5"
print"Pools: ", ipStart + " -> " + ipEnd print"Scanning online Router on network..." aliveHosts = aliveHost(ipStart, ipEnd) print "online Router:" print aliveHosts # print"New Hosts Alive in Pools:",hostsUnDone(aliveHosts, aliveHost(ipStart,
ipEnd)) if __name__ == '__main__': main()
geowurster/Acronym
acronym/cmdl/_portable_algorithms/__init__.py
Python
bsd-3-clause
1,916
0.004175
# This document is part of Acronym # https://github.com/geowurster/Acronym # =================================================================================== # # # New BSD License # # Copyright (c) 2014, Kevin D. Wurster # All rights reserved. # # Redistribution and use in source and binary forms, with or with...
following disclaimer. # # * Redistributions 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. # # * The names of its contributors may not be used to endorse or promote products # derived from this software without specific prior written permis...
imrehg/electrum
lib/blockchain.py
Python
mit
8,852
0.00113
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@ecdsa.org # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including witho...
evious_height # The chain is complete. Reverse to order by increasing height chai
n.reverse() try: self.v
shawnfuryan/django_website_core
django_website/manage.py
Python
mit
257
0
#!/usr/bin/env pytho
n import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_website.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.arg
v)
SCSSoftware/BlenderTools
addon/io_scs_tools/ui/mesh.py
Python
gpl-2.0
2,693
0.001114
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 program is distributed ...
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (C) 2013-2019: SCS Software import bpy from bpy.types import Panel from io_scs_tools.
ui import shared as _shared class _MeshPanelBlDefs(_shared.HeaderIconPanel): bl_space_type = "PROPERTIES" bl_region_type = "WINDOW" bl_ui_units_x = 15 @classmethod def poll(cls, context): return hasattr(context, "active_object") and context.active_object and context.active_object.type == ...
wdm0006/Flask-Blogging
flask_blogging/__init__.py
Python
mit
403
0
from .engine import BloggingEngine from .processor import PostProcess
or from .sqlastorage import SQLAStorage from .storage import Storage """ Flask-Blogging is a Flask extension to add blog support to your web application. This extension uses Markdown to store and then render the webpage. Author: Gouthaman Balaraman Date: June 1, 2015 """ __author__ = 'Gouth
aman Balaraman' __version__ = '0.4.2'
mahak/keystone
keystone/common/validation/__init__.py
Python
apache-2.0
2,344
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
ate): """A non-decorator way to validate a request, to be used inline. :param request_body_schema: a schema to validate the resource reference :param resource_to_validate: dictionary to validate :raises keystone.exception.ValidationError: if `resource_to_validate` is None. (see wrapper meth...
Error: at decoration time when the expected resource to validate isn't found in the decorated method's signature """ schema_validator = validators.SchemaValidator(request_body_schema) schema_validator.validate(resource_to_validate) def nullable(property_schem...
rtcTo/rtc2git
migration.py
Python
mit
6,494
0.003388
#!/usr/bin/python3 import argparse import os import sys import configuration import shouter from gitFunctions import Commiter from gitFunctions import Initializer, Differ from rtcFunctions import ImportHandler from rtcFunctions import RTCInitializer from rtcFunctions import RTCLogin from rtcFunctions import Workspace...
if Differ.has_diff(): sys.exit("Your git repo has some uncommited changes, please add/remove them manually") RTCLogin.loginandcollectstreamuuid() Initializer.preparerepo() if config.previousstreamname: prepare() else: Commiter.branch(config.str
eamname) WorkspaceHandler().load() def existsrepo(): config = configuration.get() repodirectory = os.path.join(config.workDirectory, config.gitRepoName) return os.path.exists(repodirectory) def migrate(): rtc = ImportHandler() rtcworkspace = WorkspaceHandler() git = Commiter if ...
fhahn/rpyre
tools/cli.py
Python
mit
904
0.001106
""" Lua pattern matcher based on a NFA inspired by http://swtch.com/~rsc/regexp/regexp1.html """ from rpyre.interface.lua import compile_re from rpyre.matching import find def main(args): n = 20 s = args[1] #s = "(a|b)*a%sa(a|b)*$" % ("(a|b)" * n, ) print s evilregex = compile_re(s) import os...
chunks.append(s) s = "".join(chunks) print len(s) print find(evilregex, s, 0) """ for x in find2(evilregex, s, 0): print x """ return 0 # needed for the PyPy translation toolchain def target(*args): return main, None def jitpolicy(*args): from rpython.jit.codewriter.poli...
cy() if __name__ == '__main__': import sys sys.exit(main(sys.argv))
ntt-sic/neutron
neutron/plugins/common/constants.py
Python
apache-2.0
1,913
0.000523
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apac...
Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITI
ONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # service type constants: CORE = "CORE" DUMMY = "DUMMY" LOADBALANCER = "LOADBALANCER" FIREWALL = "FIREWALL" VPN = "VPN" METERING = "METERING" L3_ROUTER_NAT = "L3_ROUT...
apophys/ipaqe-provision-hosts
ipaqe_provision_hosts/backend/__init__.py
Python
mit
22
0
#
author: Milan Kubik
jacobbendicksen/BlueAPI
matchinfo.py
Python
mit
4,831
0.012834
##################################################### # # A library for getting match information for a given team at a given event # out of the Blue Alliance API # # Authors: Andrew Merrill and Jacob Bendicksen (Fall 2014) # # Requires the blueapi.py library ###################################################### #thi...
'tba': return videos[n]['key'] def getSetNumber(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['set_number'] def getTimeString(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['time_string'] def getMatchKey(matchNumber,eventKey): retur...
key'] def getMatchTime(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['time'] def getScoreBreakdown(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['score_breakdown']
roopali8/tempest
tempest/api/network/test_extra_dhcp_options.py
Python
apache-2.0
4,062
0.000246
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
elete_port, port_id) # Confirm port created has Extra DHCP Options body = self.client.list_ports() ports = body['ports'] port = [p for p in ports if p['id'] == port_id] self.assertTrue(port) self._confirm_extra_dhcp_options(port[0], self.extra_dhcp_opts) @test.idemp...
def test_update_show_port_with_extra_dhcp_options(self): # Update port with extra dhcp options name = data_utils.rand_name('new-port-name') body = self.client.update_port( self.port['id'], name=name, extra_dhcp_opts=self.extra_dhcp_opts) # Confirm e...
skuda/client-python
kubernetes/test/test_v2alpha1_horizontal_pod_autoscaler_spec.py
Python
apache-2.0
1,023
0.00391
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import i
mport os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.cli
ent.models.v2alpha1_horizontal_pod_autoscaler_spec import V2alpha1HorizontalPodAutoscalerSpec class TestV2alpha1HorizontalPodAutoscalerSpec(unittest.TestCase): """ V2alpha1HorizontalPodAutoscalerSpec unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV2alpha1...
MiczFlor/Booktype
lib/booktype/apps/portal/forms.py
Python
agpl-3.0
2,755
0.002178
from django import forms from django.utils.html import escape from django.forms.utils import ErrorList from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from booktype.utils.misc import booktype_slugify from booki.editor.models import BookiGroup from booktype.ut...
def set_group_image(self, group_id, group_image): try: filename = misc.set_group_image(group_id, group_image, 240, 240) if len(filename) == 0: raise ValidationError
(_('Only JPEG file is allowed for group image.')) else: misc.set_group_image( "{}_small".format(group_id), group_image, 18, 18) except Exception as err: # TODO: we should do something here print err class GroupCreateForm(BaseGroupForm): pass class Group...
shuoli84/gevent_socketio2
socketio/engine/handler.py
Python
mit
5,977
0.002175
# coding=utf-8 from __future__ import absolute_import import gevent from gevent.pywsgi import WSGIHandler import sys from webob import Request from .response import Response from .socket import Socket from ..event_emitter import EventEmitter from .transports import WebsocketTransport import logging logger = logging.g...
).__init__(*args, **kwargs) EventEmitter.__init__(self) self.server_context =
server_context if self.server_context.transports: self.transports = self.server_context.transports def bind_framework_info(self, socket): # Run framework's wsgi application to hook up framework specific info eg. request # This is why we define /socket.io url in web frameworks a...
yosshy/nova
nova/tests/unit/virt/libvirt/test_driver.py
Python
apache-2.0
667,651
0.000443
# Copyright 2010 OpenStack Foundation # Copyright 2012 University Of Minho # # 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/LICENS
E-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # ...
cloudera/hue
desktop/core/ext-py/prometheus_client-0.7.1/prometheus_client/registry.py
Python
apache-2.0
4,226
0.000237
import copy from threading import Lock from .metrics_core import Metric class CollectorRegistry(object): """Metric collector registry. Collectors must have a no-argument method 'collect' that returns a list of Metric objects. The returned metrics should be consistent with the Prometheus exposition f...
['_bucket', '_gsum', '_gcount'], 'info': ['_info'], } for metric in desc_func(): for suffix in type_suffixes.get(metric.type, ['']): result.append(metric.name + suffix) return result def collect(self): """Yields metrics from the collectors in...
names) for collector in collectors: for metric in collector.collect(): yield metric def restricted_registry(self, names): """Returns object that only collects some metrics. Returns an object which upon collect() will return only samples with the given na...
RathinakumarVisweswaran/MeetCI
python/meetCI_sub.py
Python
mit
14,507
0.004067
#!/usr/bin/env python # # Generated Sat Jul 18 17:11:29 2015 by generateDS.py version 2.16a. # # Command line options: # ('-o', 'meetCI.py') # ('-s', 'meetCI_sub.py') # # Command line arguments: # meetCI.xsd # # Command line: # generateDS.py -o "meetCI.py" -s "meetCI_sub.py" meetCI.xsd # # Current working dire...
t__(classification, prediction, ) supermod.MachineLearning.subclass = MachineLearningSub # end class MachineLearningSub class MultiLayerPerceptronSub(supermod.MultiLayerPer
ceptron): def __init__(self, inputLayerActivation='Linear', hiddenLayerActivation=None, hiddenLayers=None, outputLayerActivation=None, momentum=None, epochs=None, learningRate=None): super(MultiLayerPerceptronSub, self).__init__(inputLayerActivation, hiddenLayerActivation, hiddenLayers, outputLayerActivatio...
iocoop/beancount
src/python/beancount/reports/holdings_reports.py
Python
gpl-2.0
13,561
0.00118
"""Generate reports no holdings. """ __author__ = "Martin Blais <blais@furius.ca>" import csv from beancount.core.number import D from beancount.core.number import ZERO from beancount.core import account from beancount.core import data from beancount.core import flags from beancount.parser import options from beancou...
(report.TableReport): """The full list of holdings for Asset and Liabilities accounts.""" names = ['holdings'] aggregations = { 'commodity': dict(aggreg
ation_key=lambda holding: holding.currency), 'account': dict(aggregation_key=lambda holding: holding.account), 'root-account': dict( aggregation_key=lambda holding: account.root(3, holding.account), sort_key=lambda holding: holding.market_value or ZERO), 'currency': di...
Jayin/Lotus
Lotus/controller/user.py
Python
apache-2.0
2,550
0.001994
# -*- coding: utf-8 -*- from . import app, db from flask import request, g, session, redirect from Lotus.model.user import User from hashlib import md5 from Lotus.lib.msg_code import Msg import json @app.route('/user/login', methods=['POST']) def user_login(): email = request.form.get('email', None) psw = req...
user_register(): # todo (参数不够)有插入异常怎么办? # todo 忘记密码.. try: u = User() u.username = request.form.get('username', None) u.description = request.form.get('description', None) u.type = request.form.get('type', User.CONST_TYPE_USER) u.email = request.form.get(
'email', None) m = md5() m.update(request.form.get('psw', User.CONST_DEFAULT_PASSWORD)) # 默认密码 u.psw = m.hexdigest() db.session.add(u) db.session.commit() except Exception as e: return '{"code":%d,"msg":$s}'.format(Msg['faild'], 'register faild') return '{"code":...
Zolertia/openthread
tests/scripts/thread-cert/test_coap.py
Python
bsd-3-clause
16,471
0.002064
#!/usr/bin/python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # not...
alue() data = io.BytesIO(bytearray([extended_value])) # WHEN actual_value = coap.CoapOptionHeader._read_extended_value(data, value) # THEN self.assertEqual(extended_value + 13, actual_value) def test_should_return_value_stor
ed_in_first_byte_plus_269_when_read_extended_value_is_called_with_value_equal_14(self): # GIVEN value = 14 extended_value = any_value() data = io.BytesIO(bytearray([any_value(), extended_value])) # WHEN actual_value = coap.CoapOptionHeader._read_extended_value(data, val...
Telestream/telestream-cloud-python-sdk
telestream_cloud_qc_sdk/telestream_cloud_qc/models/partition_status_test.py
Python
mit
8,207
0
# coding: utf-8 """ Qc API Qc API # noqa: E501 The version of the OpenAPI document: 3.0.0 Contact: cloudsupport@telestream.net Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from telestream_cloud_qc.configuration import Configuration class...
artitionStatusTest. # noqa: E501 :type: bool """ self._not_present = not_present @property def reject_on_error(self): """Gets the reject_on_error of this PartitionStatusTest. # noqa: E501 :return: The reject_on_error of this PartitionStatusTest. # noqa: E501 ...
rror(self, reject_on_error): """Sets the reject_on_error of this PartitionStatusTest. :param reject_on_error: The reject_on_error of this PartitionStatusTest. # noqa: E501 :type: bool """ self._reject_on_error = reject_on_error @property def checked(self): ""...
nosedjango/nosedjango
nosedjangotests/settings_legacy.py
Python
lgpl-3.0
1,056
0
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'nosedjango' DATABASE_USER = 'root' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' SITE_ID ...
= True MEDIA_ROOT = '' MEDIA_URL = '' ADMIN_MEDIA_PREFIX = '/media/' SECRET_KEY = 'w9*+(qevfn*j2959ikv-_7kj7ivptt#8&n*gy0o&ktisx@%rzt' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( '...
common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'nosedjangotests.urls' TEMPLATE_DIRS = ( ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.session...
bowen0701/algorithms_data_structures
lc0100_same_tree.py
Python
bsd-2-clause
4,044
0.001731
"""Leetcode 100. Same Tree Easy URL: https://leetcode.com/problems/same-tree/ Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \ ...
TreeNode(15) q = TreeNode(10) q.left = TreeNode(5) q.left.right = TreeNode(15) print SolutionPreorderRecur().isSameTree(p, q)
print SolutionPreorderIter().isSameTree(p, q) if __name__ == '__main__': main()
WuShichao/computational-physics
2/2_5/2_5.py
Python
gpl-3.0
1,353
0.026667
# -*- coding: utf-8 -*- """ Created on Mon Jan 11 17:55:48 2016 用欧拉法计算自行车从静止起步后的速度 @author: nightwing """ import matplotlib.pyplot as plt DENSITY = 1.29 #空气密度(kg/m3) C = 1.0 #阻力系数 A = 0.33 #截面积(m2) M = 70.0 #人车质量(kg) v = 7.0 #转折速度(m/s) v1 = 0.0 #(无阻力)速度(m/s) v2 = 0.0 #(有阻力)速度(m/s...
v: v1 += P/(M*v)*dt if
v2 <= v: v2 += P/(M*v)*dt-C*DENSITY*A*v2**2/(2*M)*dt if v1 > v: v1 += P/(M*v1)*dt if v2 > v: v2 += P/(M*v2)*dt-C*DENSITY*A*v2**2/(2*M)*dt t += dt #------------绘图--------------- plt.title("Bicycling simulation: velocity vs. time") plt.xlabel("time (s)") plt.ylabel("velocity (m/s)...
jbedorf/tensorflow
tensorflow/python/ops/distributions/util.py
Python
apache-2.0
54,998
0.005364
# 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...
e used for casting. name: A name for this operation (optional). Returns: Op raising `InvalidArgumentError` if `cast(x, int_dtype) != x`. """ with ops.name_scope(name, values=[x, data]): x = ops.convert_to_tensor(x, name="x") if x.dtype.is_integer:
return control_flow_ops.no_op() message = message or "{} has non-integer components".format(x) if int_dtype is None: try: int_dtype = { dtypes.float16: dtypes.int16, dtypes.float32: dtypes.int32, dtypes.float64: dtypes.int64, }[x.dtype.base_dtype] ...
taejoonlab/taejoonlab-toolbox
KEGG/make-pathway2list.py
Python
gpl-3.0
2,013
0.027322
#!/usr/bin/env python import os import sys ## A name of directory containing 'path:...' file ## You can download them using 'make-wget_pathway.sh' script dir_name = sys.argv[1] f_summary = open('%s.summary'%dir_name,'w') f_genes = open('%s.genes'%dir_name,'w') f_compounds = open('%s.compounds'%dir_name,'w') gene_to...
) f_compounds.write('path:%s\t%s\n'%(path_id,line[11:].strip())) elif( tmp_tag == 'GENE' ): gene_list.append( line[11:].strip().split()[0] ) f_genes.write('path:%s\t%s\n'%(path_id,line[11:].strip())) #print line[1
1:].strip() elif( tmp_tag == '' and prev_tag == 'GENE' ): gene_list.append( line[11:].strip().split()[0] ) f_genes.write('path:%s\t%s\n'%(path_id,line[11:].strip())) #print line[11:].strip() if( tmp_tag != '' ): prev_tag = tmp_tag f.close() ...
SymbiFlow/prjuray
fuzzers/007-timing/bel/tim2json.py
Python
isc
10,507
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA 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 # # Unl...
imings, converts them into data used for SDF generation. """ REGEX_CFG = re.compile(r".*__CFG([0-9]+)$") def inner(): raw = list(parse_raw_timing(fin)) for slice, site_name, bel_name, speed_model, properties in raw: # Check if we have a bel timing
# TODO: There are other naming conventions for eg. BRAM and DSP if not speed_model.startswith("bel_"): continue # Get timings from properties timings = [(k, properties[k]) for k in [ "DELAY", "FAST_MAX", "FAST_M...
dke-knu/i2am
i2am-app/AlgorithmSelectionEngine/SamplingAccuracyEvaluation/SamplingAccuracyEvaluation.py
Python
apache-2.0
3,665
0.006276
from SamplingAccuracyEvaluation import SamplingAlgorithm as SA from SamplingAccuracyEvaluation import AccuracyEvaluation as AE from SamplingAccuracyEvaluation import PrintGraph as PG from SamplingAccuracyEvaluation import StatisticalCalculation as SC import operator def populationListGenerate(filePath, target): pr...
pulationList = [] populationFile = open(filePath, 'r') while True: line = populationFile.readline() if not line: break line_data = line.split(',') populationList.append(line_data[target]) populationFile.close() return populationList def calculateScore(evalList): s...
core + abs(evalList[i])/4 else: score = score + abs(evalList[i])/3 return score def run(windowSize, sampleSize, filePath, target=0): print('############## Sampling Accuracy Evaluation ##############') count = 1 numOfTrials = 1 jSDPieceCount = 20 pAAPieceCount = 20 print...
XXLRay/libreshot
libreshot/blender/scripts/blinds.py
Python
gpl-3.0
5,718
0.019237
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of Open
Shot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor is free software: you can redistribute i
t 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. # # OpenShot Video Editor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the impli...
nanchenchen/script-analysis
pyanalysis/settings/common.py
Python
mit
12,572
0.00517
""" Django settings for pyanalysis project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import sys import os from path import path import dj_database_url # No...
CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS FIXTURE_DIRS = ( (SITE_ROOT / 'fixtures').normpath(), ) ########## END FIXTURE CONFIGURATION ########## SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = get_env_setting('SECRET_KEY', 'secret') ########## END SECRET CONFIGURATION ########## TEST CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#test-runner TEST_RUNNER = 'django.test.runner.DiscoverRunner' ########## END TEST CONFIGURATION ########## TEMPLATE CONFIGURATION # See: ht...
SMALLplayer/smallplayer-image-creator
storage/.xbmc/addons/script.artwork.downloader/lib/common.py
Python
gpl-2.0
1,305
0.008429
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2011-2013 Martijn Kaijser # # 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 ...
o('id') __addonname__ = __addon__.getAddonInfo('name') __author__ = __addon__.getAddonInfo('author') __version__ = __addon__.getAddonInfo('version') __addonpath__ = __addon__.getAddonInfo('path') __addonprofile__= xbmc.translatePath(__addon__.getAddonInfo('profile')).decode('utf-8') __icon__ = __add...
lize__ = __addon__.getLocalizedString
ddico/odoo
addons/note/controllers/__init__.py
Python
agpl-3.0
118
0.008475
# -*- c
oding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing d
etails. from . import note
kingosticks/mopidy-tunein
tests/test_extension.py
Python
apache-2.0
483
0
import unittest from mopidy_tunein import Extension class ExtensionTest(unittest.TestCase): def test_get_default_config(self)
: ext = Extension() config = ext.get_default_config() self.assertIn("[tunein]", config) self.assertIn("enabled = true", config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn("timeout", schem
a) self.assertIn("filter", schema)
leanton/cianParser
appartment.py
Python
mit
5,447
0.035596
#!/usr/bin/python # -*- coding: utf-8 -*- import re COST_AUTO = 5 class Appartment(object): """Appartment class consists of features that have all appartments""" def __init__(self, address, metro, transportation, rooms, space, price, floor, addInfo): super(Appartment, self).__init__() self.address = self.setAd...
(price) is float): print "type is " +
str(type(price)) self.price = int(price) elif (type(price) is str) or (type(price) is unicode): price = price.replace(u',', '') price = re.search(u'^\d+', price) if price: self.price = int(price.group()) else: print "No match of price in string" self.price = None else: print "Type err...
XeryusTC/projman
functional_tests/management/commands/create_project.py
Python
mit
728
0.001374
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from projects.models import Project User = get_user_model() class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('user') parser.add_argument('
name', nargs='+') parser.add_argument('--description', nargs='*', default='') def handle(self, *args, **options): name = ' '.join(options['name']) description = ' '.join(options['description']) u
= User.objects.get(username=options['user']) p = Project.objects.create(user=u, name=name, description=description) p.save() self.stdout.write(str(p.pk))
pugpe/pugpe
apps/cert/management/commands/send_certificates.py
Python
mit
2,215
0.000904
# -*- coding: utf-8 -*- import traceback from datetime import timedelta from django.core import mail from django.core.mail import EmailMultiAlternatives, mail_admins from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.utils.translation import ugettext_laz...
l=True)
# Evitar envio para eventos muito antigos attendees = attendees.filter( pub_date__gte=timezone.now() - timedelta(days=10), ) for attendee in attendees: msg = self.get_email(attendee) try: num_emails += connection.send_messages([msg]) ...
pouyana/teireader
webui/scripts/fixws.py
Python
mit
646
0.001548
import sys import
glob def read_fileb(filename, mode='rb'): f = open(filename, mode) try: return f.read() finally: f.close() def write_fileb(filename, value, mode='wb'): f = open(filename, mode) try: f.write(value) finally: f.close() for filename in glob.glob(sys.argv[1]): ...
1 = read_fileb(filename) write_fileb(filename + '.bak2', data1) data2lines = read_fileb(filename).strip().split('\n') data2 = '\n'.join([line.rstrip( ).replace('\t', ' ' * 2) for line in data2lines]) + '\n' write_fileb(filename, data2) print filename, len(data1) - len(data2)
keybar/keybar
.hypothesis/eval_source/hypothesis_temporary_module_f921b2988402df61d5f91622b67a9e50eddd05fc.py
Python
bsd-3-clause
138
0.007246
f
rom hypothesis.utils.conventions import not_set def accept(f): def complex_numbers(): return f() return complex_numb
ers
Barrog/C4-Datapack
data/jscript/village_master/7026_bitz_occupation_change/__init__.py
Python
gpl-2.0
2,377
0.03618
# # Created by DraX on 2005.08.08 # # Updated by ElgarL on 28.09.2005 # print "importing village master data: Talking Island Village ...done" import sys from net.sf.l2j.gameserver.model.quest import State from net.sf.l2j.gameserver.model.quest import QuestState from net.sf.l2j.gameserver.model.quest.jy...
class Quest (JQuest) : def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) def onEvent (self,event,st): htmltext = "No Quest" if event == "7026-01.htm": htmltext =
event if event == "7026-02.htm": htmltext = event if event == "7026-03.htm": htmltext = event if event == "7026-04.htm": htmltext = event if event == "7026-05.htm": htmltext = event if event == "7026-06.htm": htmltext = event if event == "7026-07.htm": htmltext = e...
sproutsocial/botanist
packages/github_backup.py
Python
mit
8,574
0.003032
#!/usr/bin/env python """ Backup all your organization's repositories, private or otherwise. """ import argparse import base64 import contextlib import json import os import sys import urllib2 from collections import namedtuple from urllib import urlencode from urllib import quote API_BASE = 'https://api.github.com/...
_basic_auth(request, username, password) response = urllib2.urlopen(request) pagination = get_pagination(response.headers['Link']) repos = json.loads(response.read()) for r in repos: if not r.get('archived'): yield r # Github API call, can authenticate via a...
ing): """ >>> repocsv('org1/repo1, org2/repo2,org3/repo3 ,org4/repo4') ['org1/repo1', 'org2/repo2', 'org3/repo3', 'org4/repo4'] """ try: repos = [r.strip() for r in string.split(',')] return set(repos) except Exception as exc: raise argparse.ArgumentTypeError(exc.message)...
jddixon/upax_py
src/upax/ftlog.py
Python
mit
16,036
0
# dev/py/upax3/upax3/ftlog.py """ Fault-tolerant log for a Upax node. """ import os import re # import sys from collections import Container, Sized from xlattice import (HashTypes, check_hashtype, # u, SHA1_HEX_NONE, SHA2_HEX_NONE, SHA3_HEX_NONE, BLAKE2B_HEX_NONE) from ...
ng LogEntry or None. """ if key not in self._index: return None return self._index[key] @property def entries(self):
""" Return the list of LogEntries. """ return self._entries @property def index(self): """ Return the index by key into the list of LogEntries. """ return self._index @property def prev_hash(self): """ Return the content hash of the previous Log. """ return se...
bkahlert/seqan-research
raw/workshop13/workshop2013-data-20130926/trunk/misc/renaming/invalid_identifiers.py
Python
mit
5,253
0.002094
#!/usr/bin/env python import sys import re from helpers import * PROGRAM_USAGE = """ SeqAn invalid identifiers detection script. USAGE: invalid_identifiers.py BASE_PATH BASE_PATH is the root path of all the folders to be searched. This script generates a list of invalid identifiers found in the code base, paired wi...
') result = [] for line in f: matches = INVALID_IDENTIFIER.findall(line) invalids = [match for match in matches if not valid(match)] result += invalids return result def replacement(orig): """ Returns the replacement string for a given invalid identifier. """ retur...
identifiers. """ return dict([(original, replacement(original)) for original in ids]) def main(): if len(sys.argv) != 2: print >>sys.stderr, 'ERROR: Invalid number of arguments.' print >>sys.stderr, PROGRAM_USAGE return 1 results = {} project_path = sys.argv[1] for fi...
CZ-NIC/foris
foris/config_handlers/__init__.py
Python
gpl-3.0
833
0
# Foris - web administration interface for OpenWrt based on
NETCONF # Copyright (C) 2017 CZ.NIC, z.s.p.o. <http://www.nic.cz> # # This progr
am is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT AN...