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
ndunsworth/python-shotgunorm
ShotgunORM/SgEventFilters.py
Python
bsd-3-clause
2,856
0.014356
__all__ = [ 'SgAssetCreatedFilter', 'SgHumanUserCreatedFilter', 'SgPlaylistCreatedFilter', 'SgProjectCreatedFilter', 'SgProjectFilter', 'SgPublishedFileCreatedFilter', 'SgSequenceCreatedFilter', 'SgShotCreatedFilter', 'SgTaskCreatedFilter', 'SgVersionCreatedFilter' ] # This module imports import S...
init__() def filter(self, sgEvent): ''' '''
return sgEvent.type() == 'Shotgun_HumanUser_New' class SgPlaylistCreatedFilter(ShotgunORM.SgEventFilter): ''' ''' def __init__(self): super(SgPlaylistCreatedFilter, self).__init__() def filter(self, sgEvent): ''' ''' return sgEvent.type() == 'Shotgun_Playlist_New' class SgProjectCrea...
pansapiens/mytardis
tardis/tardis_portal/tests/test_download.py
Python
bsd-3-clause
16,594
0.000301
# -*- coding: utf-8 -*- from os import makedirs from os.path import abspath, basename, dirname, join, exists, getsize from shutil import rmtree from zipfile import is_zipfile, ZipFile from tarfile import is_tarfile, TarFile from tempfile import NamedTemporaryFile from compare import expect from django.test import Te...
te() self.experiment2.delete() rmtree(self.dest1) rmtree(self.dest2) def testView(self): client = Client() # check view of file1 response = client.get('/datafile/view/%i/' % self.datafile1.id) self.assertEqual(response['Content-Disposition'], ...
'inline; filename="%s"' % self.datafile1.filename) self.assertEqual(response.status_code, 200) response_content = "" for c in response.streaming_content: response_content += c self.assertEqual(response_content, 'Hello World!\n') # chec...
ASMlover/study
zeroMQ/python/push-pull/sinker.py
Python
bsd-2-clause
1,726
0.006952
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2013 ASMlover. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # ...
ODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGE
NCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import zmq if __name__ == '__main__': ctx = zmq.Context() sinker = ctx.socket(zmq.PULL) sinker.bind('tcp://*:6666') print 'sender server init success ...' msg = sinker.recv() prin...
30loops/nova
nova/notifier/list_notifier.py
Python
apache-2.0
2,145
0
# Copyright 2011 OpenStack LLC. # 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...
a import flags from nova import log as logging from nova import utils from nova.exception import ClassNotFound flags.DEFINE_multistring('list_notifier_drivers',
['nova.notifier.no_op_notifier'], 'List of drivers to send notifications') FLAGS = flags.FLAGS LOG = logging.getLogger('nova.notifier.list_notifier') drivers = None class ImportFailureNotifier(object): """Noisily re-raises some exception over-and-over when notify ...
DarknessSwitch/django-tutorial
catalog/migrations/0019_bookinstance_borrower.py
Python
cc0-1.0
667
0.001499
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-11 09:40 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models imp
ort django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('catalog', '0018_book_language'), ] operations = [ migrations.AddField( model_name='bookinstance', name='borro...
dels.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), ]
anhstudios/swganh
data/scripts/templates/object/draft_schematic/scout/shared_item_camp_multi.py
Python
mit
450
0.046667
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/scout/shared_item_camp_multi.iff" result.at
tribute_template_id = -1 result.stfName("string_id_table","") ####
BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
gouthambs/qtk-python
qtk/creators/engine.py
Python
mit
2,401
0.002915
import QuantLib as ql from qtk.fields import Field as F from qtk.templates import Template as T from .common import CreatorBase class DiscountingBondEngineCreator(CreatorBase): _templates = [T.ENGINE_BOND_DISCOUNTING] _req_fields = [F.DISCOUNT_CURVE] _opt_fields = [] def _create(self, asof_date): ...
ineCreator(Crea
torBase): _templates = [T.ENGINE_EQUITY_FDAMERICAN] _req_fields = [F.GENERAL_BLACKSCHOLES_PROCESS] _opt_fields = [] def _create(self, asof_date): process = self[F.GENERAL_BLACKSCHOLES_PROCESS] engine = ql.FDAmericanEngine(process) return engine @classmethod def set_info...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/names/hosts.py
Python
gpl-3.0
52
0.019231
..
/../../../
../share/pyshared/twisted/names/hosts.py
Fireforge/RagnarokPy3.2
Ragnarok.py
Python
lgpl-3.0
116,100
0.00627
## Ragnarok Engine copyright 2010 Clinton Myers ## This library is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later ver...
anty of ## MERCHANTABILITY or FITNESS FOR A PART
ICULAR PURPOSE. See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/lgpl.html>. ## Ragnarok Version 1.0 ## ## ## Developer Note: This is...
saurbkumar/programming_question_python
my_question/binary-tree-all-path-to-given-sum.py
Python
apache-2.0
1,163
0.015477
#First case #http://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/ '''Print all the paths from root, with a specified sum in Binary tree - For that Second If condition''' '''Print all the paths from root, with a specified node in Binary tree - For that first If condition''' class Node: def ...
nt is the element
that we are looking for, # then path found print (path) # If want to print all the path, from root to given node for given sum if sum(path)==k: print (path) path.pop() return False root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Nod...
Mellthas/quodlibet
quodlibet/qltk/tagsfrompath.py
Python
gpl-2.0
11,346
0.000176
# Copyright 2004-2005 Joe Wreschnig, Michael Urman, Iñigo Serna # # 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. impor...
title=_('File')) col.pack_start(render, True) col.set_sizing(Gtk.TreeViewColum
nSizing.AUTOSIZE) def cell_data_file(column, cell, model, iter_, data): entry = model.get_value(iter_) cell.set_property("text", entry.name) col.set_cell_data_func(render, cell_data_file) def cell_data_header(column, cell, model, iter_, header): entry = mod...
fsalamero/pilas
pilasengine/ejemplos/plataformas.py
Python
lgpl-3.0
1,868
0.006959
import pilasengine pilas = pilasengine.iniciar() #pilas.depurador.definir_modos(fisica=True) pilas.reiniciar_si_cambia(__file__) class Protagonista(pilasengine.actores.Actor): def iniciar(self): self.imagen = "aceituna.png" self.figura = pilas.fisica.Circulo(self.x, self.y, 17, fr
iccion=0, restitucion=0) self.figura.sin_rotacion = True self.figura.escala_de
_gravedad = 2 self.sensor_pies = pilas.fisica.Rectangulo(self.x, self.y, 20, 5, sensor=True, dinamica=False) def actualizar(self): velocidad = 10 salto = 15 self.x = self.figura.x self.y = self.figura.y if self.pilas.control.derecha: self.figura.velocid...
wenottingham/ansible
lib/ansible/executor/task_executor.py
Python
gpl-3.0
35,230
0.00369
# (c) 2012-2014, Michael DeHaan <michael.dehaan@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 published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
ed=False, skipped=True, skipped_reason='No items in the list', results=[]) else: display.debug("calling self._execute()") res = self._execute() display.debug("_execute() done") # make sure changed is set in the result, if it's not present ...
res['changed'] = False def _clean_res(res): if isinstance(res, UnsafeProxy): return res._obj elif isinstance(res, binary_type): return to_text(res, errors='surrogate_or_strict') elif isinstance(res, dict): ...
ales-erjavec/orange-canvas
orangecanvas/canvas/items/tests/test_graphicstextitem.py
Python
gpl-3.0
3,214
0.000933
from typing import Optional from unittest import skipUnless from AnyQt.QtCore import QPointF, QPoint, Qt, QT_VERSION_INFO from AnyQt.QtTest import QSignalSpy from AnyQt.QtWidgets import ( QGraphicsScene, QGraphicsView, QGraphicsItem, QMenu, QAction, QApplication, QWidget ) from orangecanvas.gui.test import QAp...
ms.graphicstextitem import GraphicsTextItem from orangecanvas.utils import findf @skipUnless((5, 15, 1) <= QT_VERSION_INFO < (6, 0, 0), "contextMenuEvent is not reimplemented") class TestGraphicsTextItem(QAppTestCase): def setUp(self): super().setUp() self.scene = QGraphicsScene() ...
self.item.setPlainText("AAA") self.item.setTextInteractionFlags(Qt.TextEditable) self.scene.addItem(self.item) self.view.setFocus() def tearDown(self): self.scene.clear() self.view.deleteLater() del self.scene del self.view super().tearDown() ...
melviso/phycpp
beatle/app/resources/_mini_logo.py
Python
gpl-2.0
8,170
0.055936
_mini_logo = [ "24 24 431 2", " c None", ". c #EDEDED", "+ c #ECEBEB", "@ c #EBE7E7", "# c #F2FBFB", "$ c #F4FFFF", "% c #F3FFFF", "& c #EEF2F2", "* c #EAE5E5", "= c #ECE9E9", "- c #F0F6F6", "; c #E7DDDD", "> c #C18383", ", c #9F4A4A", "' c #8E2E2E", ") c #953636", "! c #B06262", "~ c #D8ACAC", "{ c...
2B", "R. c #BC2C2C", "S. c #AF3737", "T. c #C47777", "U. c #EFC7C7", "V. c #FFF8F5", "W. c #FFFFFC", "X. c #FEFFF7", "Y. c #F1B1E0", "Z. c #CF867D", "`. c #BF3B38", " + c #B62522", ".+ c #B82928", "++ c #B4221F", "@+ c #D32B26", "#+ c #B079A1", "$+ c #A86B75", "%+ c #F0F5F3", "&+ c #ECEFEC", "*+ c #CFA2AF", "=+ c #FFC6...
^+ c #F2B6E5", "/+ c #E4908B", "(+ c #C84646", "_+ c #C32E2E", ":+ c #B52C2C", "<+ c #C02E2E", "[+ c #CA2F2D", "}+ c #BD86B4", "|+ c #914047", "1+ c #F5FDFE", "2+ c #B57671", "3+ c #F2ADE5", "4+ c #DEA8E6", "5+ c #C23A3F", "6+ c #CC3435", "7+ c #C62E2E", "8+ c #CA3C3E", "9+ c #AF6C73", "0+ c #EC9BA5", "a+ c #FFCBCB", "...
varunarya10/ironic
ironic/openstack/common/rpc/dispatcher.py
Python
apache-2.0
7,008
0
# Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
---- Adding a new method is a backwards compatible change. It should be added to nova/compute/manager.py, and RPC_API_VERSION should be bumped from X.Y to X.Y+1. On the client side, the new method in n
ova/compute/rpcapi.py should have a specific version specified to indicate the minimum API version that must be implemented for the method to be supported. For example:: def get_host_uptime(self, ctxt, host): topic = _compute_topic(self.topic, ctxt, host, None) return self.call(ctxt, self.make_msg...
amath574w2015/am574-class
labs/lab4/chap6/compareadv/setrun.py
Python
bsd-3-clause
7,172
0.010876
""" Module to set up run time parameters for Clawpack -- classic code. The values set in the function setrun are then written out to data files that will be read in by the Fortran code. """ import os import numpy as np #------------------------------ def setrun(claw_pkg='classic'): #---------------------------...
# Number of auxiliary variables in the aux array (initialized in setaux) clawdata.num_aux = 0 # Index of aux array corresponding to capacity function, if there is one: clawdata.capa_index = 0 # ------------- # Initial time: # ------------- clawdata.t0 = 0.000000 ...
g, t0 above should be from original run, and the # restart_file 'fort.qNNNN' specified below should be in # the OUTDIR indicated in Makefile. clawdata.restart = False # True to restart from prior results clawdata.restart_file = 'fort.q0006' # File to use for restart data ...
dhruvaldarji/InternetProgramming
Assignment_7/clients/poly_client.py
Python
mit
2,136
0.003277
import socket __author__ = 'Dhruval' # DESCRIPTION ##############
############################################################################################ # This Client connects to a Polynomial Server at "localhost:12321", # Evaluates a Bisection, # And then Evaluates a polynomial based on the result. # Bisection : S0 2
-945 1689 -950 230 -25 1 1e-15 # Evaluate : E1.0 -945 1689 -950 230 -25 1 ######################################################################################################################## host = "localhost" port = 12321 # Evaluate which mode we are based on code and construct the proper message string. de...
harmy/kbengine
kbe/res/scripts/common/Lib/test/test_codecmaps_cn.py
Python
lgpl-3.0
1,006
0.005964
#!/usr/bin/env python3 # # test_codecmaps_cn.py # Codec mapping tests for PRC encodings # from test import support from test import test_multibytecodec_support im
port unittest class TestGB2312Map(test_multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gb2312' mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-CN.TXT' class TestGBKMap(test_multibytecodec_support.TestBase_Mapping, unittest.TestCase...
tibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gb18030' mapfileurl = 'http://source.icu-project.org/repos/icu/data/' \ 'trunk/charset/data/xml/gb-18030-2000.xml' def test_main(): support.run_unittest(__name__) if __name__ == "__main__...
google/skia
gn/gn_to_bp.py
Python
bsd-3-clause
23,280
0.005627
#!/usr/bin/env python # # Copyright 2016 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Generate Android.bp for Skia from GN configuration. from __future__ import print_function import os import pprint import string import subprocess import tempf...
ith exceptions? "-fexceptions", ], srcs: [ $srcs ], target: { android: { srcs: [ $android_srcs ], local_include_dirs: [ "android", ], export_include_dirs: [ "android", ], }, linux_glibc: { ...
ux", ], export_include_dirs: [ "linux", ], }, darwin: { srcs: [ $mac_srcs ], local_include_dirs: [ "mac", ], export_include_dirs: [ "mac", ], }, windows: { enabled: true, ...
hpfem/cython
Cython/Compiler/Nodes.py
Python
apache-2.0
322,384
0.003778
# # Parse tree nodes # import cython cython.declare(sys=object, os=object, time=object, copy=object, Builtin=object, error=object, warning=object, Naming=object, PyrexTypes=object, py_object_type=object, ModuleScope=object, LocalScope=object, ClosureScope=object, \ Struct...
absolute_path_length = len(os.path.abspath(os.getcwd())) return (pos[0].get_filenametable_entry()[absolute_path_length+1:], pos[1]) def embed_position(pos, docstring): if not Options.embed_pos_in_d
ocstring: return docstring pos_line = u'File: %s (starting at line %s)' % relative_position(pos) if docstring is None: # unicode string return EncodedString(pos_line) # make sure we can encode the filename in the docstring encoding # otherwise make the docstring a unicode string...
390910131/Misago
misago/conf/tests/test_hydrators.py
Python
gpl-2.0
4,184
0
from django.test import TestCase from misago.conf.hydrators import hydrate_value, dehydrate_value from misago.conf.models import Setting class HydratorsTests(TestCase): def test_hydrate_dehydrate_string(self): """string value is correctly hydrated and dehydrated""" wet_value = 'Ni!' dry_v...
f test_hydrate_dehydrate_string(self): """string value is correctly hydrated and dehydrated in model""" setting = Setting(python_type='string') wet_value = 'Lorem Ipsum' dry_value = dehydrate_value(setting.python_type, wet_value)
setting.value = wet_value self.assertEqual(setting.value, wet_value) self.assertEqual(setting.dry_value, dry_value) def test_hydrate_dehydrate_bool(self): """bool values are correctly hydrated and dehydrated in model""" setting = Setting(python_type='bool') wet_value...
zzzeek/sqlalchemy
test/orm/test_defaults.py
Python
mit
16,424
0
import sqlalchemy as sa from sqlalchemy import Computed from sqlalchemy import event from sqlalchemy import Identity from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy import testing from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing.assertsql im...
rt(self): Default = self.classes.Default d1 = Default(id=1) eq_(d1.col1, None) eq_(d1.col2, None) eq_(d1.col3, None) eq_(d1.col4, None) session = fixture_session() session.add(d1)
session.flush() eq_(d1.col1, None) eq_(d1.col2, "ins") eq_(d1.col3, None) # don't care which trigger fired assert d1.col4 in ("ins", "up") def test_update(self): Default = self.classes.Default d1 = Default(id=1) session = fixture_session() ...
jadielam/object-detection-tensorflow
lib/rpn_msr/anchor_target_layer.py
Python
mit
11,708
0.001452
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import caffe import os import yaml import numpy as np i...
de), 4), dtype=np.float32) if gt_boxes.shape[0] != 0: bbox_targets = _compute_targets(anchors, gt_boxes[argmax_overlaps, :]) bbox_insi
de_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_inside_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS) bbox_outside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) if cfg.TRAIN.RPN_POSITIVE_WEIGHT < 0: # uniform weighting of exam...
bobbyluig/CCTF-Platform
ctf/ctf/views.py
Python
mit
1,888
0.043432
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.db import models from api.interact import get_ip from api.latest import latest from api.account import pre_load from api.config import config def home(request): if 'teamid' not in request.session: return rende...
eboard(request): return render(request, 'scoreboard.html') def interact(request): if 'teamid' not in request.session or not config.comp_started(): return HttpResponseRedirect('/')
return render(request, 'interact.html', {'ip': get_ip(request)}) def stats(request): return render(request, 'stats.html') def account(request): if 'teamid' not in request.session: return HttpResponseRedirect('/') return render(request, 'account.html', pre_load(request)) def login(request): if 'teamid' in ...
openstack/osprofiler
osprofiler/drivers/messaging.py
Python
apache-2.0
7,425
0
# Copyright 2016 Mirantis 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...
) for n in events:
trace_id = n["trace_id"] parent_id = n["parent_id"] name = n["name"] project = n["project"] service = n["service"] host = n["info"]["host"] timestamp = n["timestamp"] self._append_results(trace_id, parent_id, name, project, service, ...
longman694/youtube-dl
youtube_dl/extractor/mixcloud.py
Python
unlicense
12,644
0.001661
from __future__ import unicode_literals import base64 import functools import itertools import re from .common import InfoExtractor from ..compat import ( compat_chr, compat_ord, compat_str, compat_urllib_parse_unquote, compat_urlparse, ) from ..utils import ( clean_html, ExtractorError, ...
def _fetch_tracks_page
(self, path, video_id, page_name, current_page, real_page_number=None): real_page_number = real_page_number or current_page + 1 return self._download_webpage( 'https://www.mixcloud.com/%s/' % path, video_id, note='Download %s (page %d)' % (page_name, current_page + 1), ...
ChristineLaMuse/mozillians
mozillians/groups/migrations/0021_auto__del_languagealias__del_language.py
Python
bsd-3-clause
13,062
0.007962
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): # Explicitly declare the order of migrations depends_on = ( ('users', '0053_auto_del_languages'), ) def forwards(self, orm): ...
'groups_languagealias
') # Deleting model 'Language' db.delete_table('groups_language') def backwards(self, orm): # Adding model 'LanguageAlias' db.create_table('groups_languagealias', ( ('url', self.gf('autoslug.fields.AutoSlugField')(max_length=50, unique_with=(), unique=True, populate_fr...
AakashRaina/radpress
radpress/tests/base.py
Python
mit
7,339
0.000818
import os.path from django.core.urlresolvers import reverse from django.template import Context, Template from django.template.defaultfilters import slugify from django.test import TestCase from django.test.client import Client from radpress.compat import get_user_model User = get_user_model() from radpress.models imp...
access_not_published_article(self): """ If user is not authenticated, user can not access not published articles and pages.
""" article = Article.objects.get(slug='i-have-a-dream') page = Page.objects.get(slug='page-3-not-published') def get_responses(): response_article = self.client.get( reverse('radpress-article-detail', args=[article.slug])) response_page = self.client...
CERNDocumentServer/cds
tests/e2e/conftest.py
Python
gpl-2.0
5,085
0
# -*- coding: utf-8 -*- # # This file is part of CERN Document Server. # Copyright (C) 2016, 2019 CERN. # # CERN Document Server 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 # Licens...
EAGER=True, # CELERY_CACHE_BACKEND="memory", # CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, # CELERY_RESULT_BACKEND="cache", SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME", MAIL_SUPPRESS_SEND=True, TESTING=True, ) with app.app_context():
yield app # Teardown shutil.rmtree(instance_path) @pytest.yield_fixture(scope='session') def db(base_app): """Initialize database.""" # Init if not database_exists(str(_db.engine.url)): create_database(str(_db.engine.url)) _db.create_all() yield _db # Teardown _db.sess...
she11c0de/cubes
cubes/backends/sql/functions.py
Python
mit
7,113
0.000422
# -*- encoding=utf -*- from collections import namedtuple from ...errors import * try: import sqlalchemy import sqlalchemy.sql as sql from sqlalchemy.sql.functions import ReturnTypeFromArgs except ImportError: from ...common import MissingPackage sqlalchemy = sql = MissingPackage("sqlalchemy", "SQ...
s` and browser context. If `missing_value` is not `None`, then the aggregate's source value should be wrapped in ``COALESCE(column, missing_value)``. Returns a SQLAlchemy expression.""" if not context: raise InternalError("No context prov
ided for AggregationFunction") if not aggregate.measure: raise ModelError("No measure specified for aggregate %s, " "required for aggregate function %s" % (str(aggregate), self.name)) try: source = context.cube.measure(a...
desarrollosimagos/svidb
administrativo/documentos/models.py
Python
gpl-3.0
1,156
0.025087
#!/usr/bin/python -u # -*- coding: utf-8 -*- from django.db import models from django.contrib import admin from datetime import datetime from gestion.models import * # Create your models here. class Licencias(models.Model): tipo = models.CharField(max_length=150, blank=True,verbose_name='nombre') des...
='pathImg',db_column='pathImg3',blank=True,null=True) siglas = models.CharField(max_length=45, blank=True) update = models.DateTimeField(default=
datetime.now(),editable = False) userupdate = models.ForeignKey(User,verbose_name='Usuario') class Meta: db_table = u'licencias' verbose_name_plural='Licencias' verbose_name='Licencias' #app_label = 'Datos_Transversales' def __unicode__(self): return u"%s %s"...
igabr/Metis_Projects_Chicago_2017
03-Project-McNulty/helper_functions.py
Python
mit
3,521
0.01136
import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle import seaborn as sns import warnings import re from datetime import datetime warnings.filterwarnings("ignore") def difference_in_days(date1, date2): """ The assumption here is that Date 2 > Date 1. can always use abs(d2-...
kl, 'rb')) data_dict = unpickle_object("data_dict.pkl") def plot_corr_matrix(data): ''' Heatmap of correlation matrix Inputs: dataframe
Returns: Heatmap (Green + corr. Red - corr.) ''' sns.set(font_scale=1.4)#for label size ax = plt.axes() sns.heatmap(data.corr(), square=True, cmap='RdYlGn') ax.set_title('Correlation Matrix') #functions below relate to logisitic regression coef interpretation def convert_to_p...
headrotor/aurora-server
imagemunger.py
Python
mit
6,314
0.01758
# SendImage.py: read an image from the command line, spit it out to DMX # Requires Python Image library: http://www.pythonware.com/products/pil/ # usage: Python SendImage.py test.png import Image import sys import os import time import colorsys from optparse import OptionParser #local classes import aurora class Ima...
r.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "-
-quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() if len(args) != 1: parser.error("Expecting image file name") print "using config file %s" % options.cfgfile # make the DMX data structure from the config file treeDMX = aurora.Aurora...
xuru/pyvisdk
pyvisdk/do/vmfs_datastore_create_spec.py
Python
mit
1,109
0.009017
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def VmfsDatastoreCreateSpec(vim, *args, **kwargs): '''This data object type is used when ...
mfsDatastoreCreateSpec') # do some validation checking... if (len(args) + len(kwargs)) < 3: raise IndexError('Expected at least 4 arguments got: %d' % len(args)) required = [ 'partition', 'vmfs', 'diskUuid' ] optional = [ 'extent', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(r...
else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
iamaris/xtornado
test/Introduction-to-Tornado-master/template_basics/bookstore/main.py
Python
apache-2.0
1,173
0.026428
#!/usr/bin/env python import os.path import tornado.escape import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options define("port
", default=8000, help="run on the given port", type=int) class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), ] sett
ings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=True, autoescape=None ) tornado.web.Application.__init__(self, handlers, **settings) class MainHandler(tornado.web.RequestHandler): def get(self): ...
the-zebulan/CodeWars
katas/beta/assignment_2.py
Python
mit
531
0.001883
from string import ascii_lowercase, maketrans def mirror(code, rev=ascii_lowercase): # python 2 half = len(rev) // 2 the_mirror = (rev[:half][::-1
] + rev[::-1][:half]).lower() return code.lower().translate(maketrans(the_mirror, the_mirror[::-1])) # from string import ascii_lowercase # # # def mirror(code, rev=ascii_lowercase): # python 3 # half = len(rev) // 2 # the_mirror = (rev[:half][::-1] + rev[::-1][:half]).lower() # return code.lower().t...
trans(the_mirror, the_mirror[::-1]))
hjoliver/cylc
cylc/flow/workflow_files.py
Python
gpl-3.0
70,188
0.000014
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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 Licen...
WorkflowFiles.Service.PUBLIC_FILE_EXTENSION self.file_name = f"{file_name}{file_extension}" # Build key path (without filename) for client public keys if (key_owner is KeyOwner.CLIENT and key_type is KeyType.PUBLIC and server_held): temp = f"{key...
in( os.path.expanduser("~"), self.workflow_srv_dir, temp) elif ( (key_owner is KeyOwner.CLIENT and key_type is KeyType.PUBLIC and server_held is False) or (key_owner ...
Kevin-Ray-Johnson/DM_Desk_Calc
Infix.py
Python
gpl-2.0
976
0.020492
# Allows the creation of infix operators # Thanks to Ferdinand Jamitzky # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122 class Infix(object): def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x: self.function(other, x)) def __or__(s...
def __rlshift__(self, other): return Infix(lambda x, self=self,
other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) # To create a binary operator just make a function that takes 2 arguments like say # def my_add (a, b): # return a + b # ...
itdxer/neupy
tests/layers/test_recurrent.py
Python
mit
10,661
0
import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from neupy.datasets import reber from neupy.utils import asfloat, tensorflow_session from neupy.exceptions import LayerConnectionError from neupy.layers.recurrent import clip_gradient from neupy import layers, algorithms, i...
return_indices=True, ) data = add_sequence_padding(data + 1) # +1 to shift indices self.data = train_test_split(data, labels, test_size=0.2) self.n_categories = len(reber.avaliable_letters) + 1 self.n_time_steps = self.data[0].shape[1] def train_gru(self, data, *...
rithms.RMSProp( [ layers.Input(self.n_time_steps), layers.Embedding(self.n_categories, 10), layers.GRU(20, **gru_options), layers.Sigmoid(1), ], step=0.05, verbose=False, batch_size=16, ...
azylstra/impy
impy/gui/widgets/Value_Prompt.py
Python
mit
3,377
0.001481
# impy - a post-processor for HYADES implosion simulations # Copyright (c) Massachusetts Institute of Technology / Alex Zylstra # Distributed under the MIT License __author__ = 'Alex Zylstra' __date__ = '2014-01-06' __version__ = '0.1.0' import tkinter as tk import tkinter.ttk as ttk import platform class Value_Prom...
"""Add the OK and cancel buttons""" box = tk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.__ok__) w.pack(side=tk.LEFT, padx=5, pady=5) w = ttk.Button(box, text="Cancel", width=10,
command=self.__cancel__) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.__ok__) self.bind("<Escape>", self.__cancel__) box.pack() def __ok__(self, event=None): """Handle activation of the OK button.""" if not self.__validate__(): print...
chienlieu2017/it_management
odoo/addons/anonymization/__manifest__.py
Python
gpl-3.0
1,171
0.000858
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Database Anonymization', 'version': '1.0', 'category': 'Extra Tools', 'description': """ This module allows you to anonymize a database. =============================================== This m...
e you get back your migrated database, you restore it and reverse the anonymization process
to recover your previous data. """, 'depends': ['base'], 'demo': ['data/anonymization_demo.xml'], 'data': [ 'data/ir.model.fields.anonymization.csv', 'security/ir.model.access.csv', 'views/anonymization_views.xml', 'wizard/anonymize_wizard_views.xml' ], 'installab...
psci2195/espresso-ffans
src/python/espressomd/io/mpiio.py
Python
gpl-3.0
3,867
0.000776
# Copyright (C) 2010-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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 v...
prefix=None, positions=False, velocities=False, types=False, bonds=False): """MPI-IO write. Outputs binary data using MPI-IO to several files starting with prefix. Suffixes are: - head: Information about fields that are dumped, - pref: Information about p...
nformation (if dumped): 3 doubles per particle, - vel: Velocity information (if dumped): 3 doubles per particle, - typ: Type information (if dumped): 1 int per particle, - bond: Bond information (if dumped): variable amount of data, - boff: Bond offset information (if bon...
cle1109/sigviewr
signalbrowser.py
Python
gpl-3.0
1,710
0.004678
# This file is part of Sigviewr. # This project is licensed under the GNU GPL (version 3 or higher). # Copyright 2014 by Clemens Brunner and Thomas Brunner. from qt import QtCore from signalscene import SignalScene from signalitem import SignalItem from signalview import SignalView class SignalBrowser(...
erID = None def addSource(self, source, height, background=QtCore.Qt.white): item = SignalItem(source, height=height, pixelPerSec=200, scrollMode=self._scrollMode) item.setBackground(background) se...
_scene.updateItems() self._view.scrollData() def view(self): return self._view def start(self, updateRate): if self._timerID: self.stop() self._timerID = self.startTimer(1000 / updateRate) self._view.setHorizontalScrollBar...
pbougue/navitia
source/jormungandr/jormungandr/street_network/parking/augeas.py
Python
agpl-3.0
3,845
0.00156
# Copyright (c) 2001-2019, Kisio Digital and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Kisio Digital (http://www.kisiodigital.com/). # Help us simplify mo...
}
url = requests.compat.urljoin(self.service_url, '/v0/park_duration') r = requests.get(url=url, params=params, timeout=self.request_timeout) durations = r.json().get('durations') if not durations: return self.max_park_duration return durations[0].get('duration', self.max_park...
JulienMcJay/eclock
windows/Python27/Lib/site-packages/docutils/parsers/__init__.py
Python
gpl-2.0
1,657
0.001811
# $Id: __init__.py 7646 2013-04-17 14:17:37Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ This package contains Docutils parser modules. """ __docformat__ = 'reStructuredText' import sys from docutils import Component if sys.version_info < (2...
""Return the Parser class from the `parser_name` module.""" parser_name = parser_name.lower() if parser_nam
e in _parser_aliases: parser_name = _parser_aliases[parser_name] try: module = __import__(parser_name, globals(), locals(), level=1) except ImportError: module = __import__(parser_name, globals(), locals(), level=0) return module.Parser
wolfram74/numerical_methods_iserles_notes
venv/lib/python2.7/site-packages/IPython/html/widgets/tests/test_interaction.py
Python
mit
19,299
0.01114
"""Test interact and interactive.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function from collections import OrderedDict import nose.tools as nt import IPython.testing.tools as tt from IPython.kernel.comm import Comm from IP...
cls=widgets.FloatSlider,
value=4.5, ), g=dict( cls=widgets.IntSlider, value=1, ), ) def test_default_values(): @annotate(n=10, f=(0, 10.), g=5, h={'a': 1, 'b': 2}, j=['hi', 'there']) def f(n, f=4.5, g=1, h=2, j='there'): pass c = interactive(f) check_widgets(c, ...
zwChan/VATEC
~/eb-virt/Lib/site-packages/flask/testsuite/templating.py
Python
apache-2.0
11,237
0.003382
# -*- coding: utf-8 -*- """ flask.testsuite.templating ~~~~~~~~~~~~~~~~~~~~~~~~~~ Template functionality :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import flask import unittest from flask.testsuite import FlaskTestCase class TemplatingTestCase(Flask...
ask(__name__) @app.context_processor def context_processor(): return {'injected_value': 42} @app.route('/') def index(): return flask.render_template('context_template.html', value=23) rv = app.test_client().get('/') self.assert_equal(rv.data, b'<p...
app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template_string('{{ config }}', config=42) rv = app.test_client().get('/') self.assert_equal(rv.data, b'42') def test_request_less_rendering(self): app = flask.Flask(__name__) ...
mcmcplotlib/mcmcplotlib
api/generated/arviz-plot_forest-2.py
Python
apache-2.0
350
0.014286
rope = {'theta': [{'school': 'Cho
ate', 'rope': (2, 4)}], 'mu': [{'rope': (-2, 2)}]} axes = az.plot_forest(non_centered_data, rope=rope, var_names='~tau', combined=True,
figsize=(9, 7)) axes[0].set_title('Estimated theta for 8 schools model')
potatolondon/centaur
models.py
Python
bsd-3-clause
5,647
0.001948
import sys import traceback import json import os import logging import time from hashlib import md5 from django.utils import timezone from django.db import models from django.http import HttpResponse from django.utils.encoding import smart_str from djangae.db.transaction import atomic, TransactionFailedError from ....
que_
together = [ ('exception_class_name', 'hashed_file_path', 'line_number') ] @staticmethod def hash_for_file_path(file_path): return md5(smart_str(file_path)).hexdigest() def save(self, *args, **kwargs): self.hashed_file_path = Error.hash_for_file_path(self.file_path) ...
oncokb/oncokb-annotator
test_AnnotatorCore.py
Python
agpl-3.0
4,654
0.003008
#!/usr/bin/python import pytest from AnnotatorCore import * def test_getgenesfromfusion(): AB_EXAMPLE = ('A', 'B') assert getgenesfromfusion('A-B') == AB_EXAMPLE assert getgenesfromfusion('A-B ') == AB_EXAMPLE assert getgenesfromfusion('a-b') == ('a', 'b') assert getgenesfromfusion('A') == ('A', ...
assert replace_all('Ly Lys Pr Pro Gln Glad Ph PH Phe') == 'Ly K Pr P Q Glad Ph PH F' assert replace_all( 'nOt can fat Tan Rat cat dog man Men FAn rot taR car fAr map TAP Zip poP') == 'nOt can fat Tan Rat cat dog man Men FAn rot taR car fAr map TAP Zip poP' # Test replace_al
l is not affected by numbers assert replace_all('Tyr600E Cys56734342342454562456') == 'Y600E C56734342342454562456' assert replace_all( '60 045 434 345 4 26 567 254 245 34 67567 8 56 8 364 56 6 345 7567 3455 6 8 99 89 7 3') == '60 045 434 345 4 26 567 254 245 34 67567 8 56 8 364 56 6 345 7567 3455 6 8 9...
kidmaple/CoolWall
user/python/Tools/webchecker/webchecker.py
Python
gpl-2.0
27,274
0.001503
#! /usr/bin/env python # Original code by Guido van Rossum; extensive changes by Sam Bayer, # including code to check URL fragments. """Web tree checker. This utility is handy to check a subweb of the world-wide web for errors. A subweb is specified by giving one or more ``root URLs''; a page belongs to the subweb ...
in opts: if o == '-R': restart = 1 if o == '-d': dumpfile = a if o == '-m': maxpage = string.atoi(a) if o == '-n': norun = 1 if o
== '-q': verbose = 0 if o == '-r': roundsize = string.atoi(a) if o == '-t': extra_roots.append(a) if o == '-a': nonames = not nonames if o == '-v': verbose = verbose + 1 if o == '-x': checkext = not checkext...
elhanarinc/streambasednotifications
challenge/notifications/apps.py
Python
gpl-3.0
165
0.006061
# -*- coding: utf-8 -*- fr
om __future__ import unicode_lite
rals from django.apps import AppConfig class NotificationsConfig(AppConfig): name = 'notifications'
bosichong/17python.com
Django/Django02.py
Python
apache-2.0
3,182
0.002153
#codeing=utf-8 # @Time : 2017-11-08 # @Author : J.sky # @Mail : bosichong@qq.com # @Site : www.17python.com # @Title : 实战:利用Django开发部署自己的个人博客(2)视图/路由 # @Url : http://www.17python.com/blog/53 # @Details : 实战:利用Django开发部署自己的个人博客(2)视图/路由 # @Other : OS X 10.11.6 # Python 3.6.1 # VSC...
terns = [ url(r'^admin/', admin.site.urls), url(r'^bl
og/', include('myblog.urls')), ] 这样设置路由就是把blog/下边的路由都交给`myblog.usrs.py`中来设置了。我们继续设置一个视图,验证一下我们的路由是否成功 ## 编写视图 视图与路由是对好兄弟,一般都是相互存在的。我们来设置一下`blog`的主页。 先编写`myblog.views.py`中视图代码: from django.http import HttpResponse, HttpResponseRedirect def index(request): return HttpResponse('你好,Django,江哥?') 设置`...
CloudBoltSoftware/cloudbolt-forge
ui_extensions/aws_network_policy/actions/fetch_update_findings.py
Python
apache-2.0
4,209
0.002851
import json import django import urllib3 if __name__ == '__main__': django.setup() from infrastructure.models import Server, CustomField from resourcehandlers.aws.models import AWSHandler from common.methods import set_progress from django.core.serializers.json import DjangoJSONEncoder def fetch_arns_for_findi...
tor('list_findings', ) for page in paginator.paginate(assessmentRunA
rns=at_runs, maxResults=500): if len(page['findingArns']) > 0: findings.add(page['findingArns'][0]) return findings def get_instance_id(finding): """ Given a finding, go find and return the corresponding AWS Instance ID :p...
JioCloud/heat
heat/db/sqlalchemy/migrate_repo/versions/020_stack_action.py
Python
apache-2.0
1,147
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
ONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sqlalchemy def upgrade(migrate_engine): meta = sqlalchemy.MetaData(bind=migrate_engine) stack = sqlalchemy.Table('stack', meta, autoload=True) #...
sqlalchemy.String(length=255)) action.create(stack) def downgrade(migrate_engine): meta = sqlalchemy.MetaData(bind=migrate_engine) stack = sqlalchemy.Table('stack', meta, autoload=True) stack.c.action.drop()
Ladeia/ProjectEuler
Problem439/Python/solution_1.py
Python
mit
655
0.038941
# -*- coding: utf-8 -*- """ Let d(k) be the sum of all divisors of k. We define the function
S(N) = ∑1≤i≤N ∑1≤j≤N d(i·j). For example, S(3) = d(1) + d(2) + d(3) + d(2) + d(4) + d(6) + d(3) + d(6) + d(9) = 59. You are given that S(10^3) = 563576517282 and S(10^5) mod 10^9 = 215766508. Find S(10^11) mod 10^9 """ def gd(k): for x in range(1, k +1): if k % x
== 0: yield x def d(k): return reduce(lambda x, y: x + y, gd(k)) def g(n): for x in range(1, n + 1): for y in range(1, n + 1): yield x * y def s(n): dic = {} Sum = 0 for i in g(n): if i not in dic: dic[i] = d(i) Sum += dic[i] return Sum print s(1000)
UniversityRadioYork/lass-pyramid
uryplayer/views.py
Python
bsd-2-clause
3,553
0.000844
"""Views for the URYPlayer submodule of the URY website. --- Copyright (c) 2013, University Radio York. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the...
ss.uryplayer.models @pyramid.view.view_config( route_name='uryplayer' ) def uryplayer(request): """The main URYPlayer page.""" # Currently redirects to podcasts.
# These are kept separate in case we ever branch out to something else under # the URYPlayer branding. raise pyramid.httpexceptions.HTTPFound( location=request.route_url('uryplayer-podcasts') ) @pyramid.view.view_config( route_name='uryplayer-podcasts', renderer='uryplayer/podcasts.jinja2...
rad-lab/simple-phrase-transform
simple_grammar.py
Python
mit
4,526
0.000663
from itertools import permutations, product from copy import deepcopy class SimpleGrammar(object): def __init__(self, grammar_string): self.requirements = {} self.structure = [] self.__parse(grammar_string) def __parse(self, grammar_string): self.grammar_string = grammar_str...
if structural_element_max is None: if structural_element['tag'] in subset.keys(): structural_element_max = len(subset[structural_element['tag']]) else: structural_element_max = 0 index = structural_e
lement['min'] accumulated_words = "" working_subset = deepcopy(subset) while index <= structural_element_max: # Range of how many words I can include here if structural_element['tag'] in working_subset.keys(): if index > 0 and len(working_subset[struct...
mozilla/make.mozilla.org
make_mozilla/base/views/event.py
Python
bsd-3-clause
1,344
0.00744
from django import http from django.forms import ModelForm from django.core.urlresolvers import reverse import bleach import commonware import jingo from funfactory.log import log_cef from mobility.decorators import mobile_template from session_csrf import anonymous_csrf fro
m make_mozilla.base import models from django.conf import settings log = commonware.log.getLogger('playdoh') class EventForm(ModelForm): class Meta: model = models.Event @anonymous_csrf def create(request): print settings.DEFAULT_CHARSET if request.method == 'POST': # If the form has been submi...
pass # Process the data in form.cleaned_data event = form.save() return http.HttpResponseRedirect( reverse('make_mozilla.base.views.event.detail', kwargs={'event_id': event.pk}) ) # Redirect after POST return jingo.render(request, 'event/new.html', {'f...
dscorbett/pygments
tests/__init__.py
Python
bsd-2-clause
176
0
"
"" Pygments test package
~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """
djgagne/hagelslag
hagelslag/evaluation/MulticlassContingencyTable.py
Python
mit
2,908
0.003439
import numpy as np __author__ = 'David John Gagne <djgagne@ou.edu>' def main(): # Contingency Table from Wilks (2011) Table 8.3 table = np.array([[50, 91, 71], [47, 2364, 170], [54, 205, 3288]]) mct = MulticlassContingencyTable(table, n_classes=table.shape[0], ...
ore, True Skill Score) """ n = float(self.table.sum()) nf = self.table.sum(axis=1) no = self.table.sum(axis=0) correct = float(self.table.trace())
return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() / n ** 2) def gerrity_score(self): """ Gerrity Score, which weights each cell in the contingency table by its observed relative frequency. :return: """ k = self.table.shape[0] n = float(self.t...
egh/sparchive
setup.py
Python
gpl-3.0
611
0
from setuptools import setup, find_packages setup(name='sparchive', version="0.1.1", description="simple personal archive",
classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python", ], author='Erik Hetzner', author_email='egh@e6h.org', url='https://bitbucket.org/egh/sparchive', packages=find_packages(exclude=[ 'tests']), entry_points={ ...
}, install_requires=[], test_suite='tests', )
google/makani
analysis/control/flap_limits.py
Python
apache-2.0
6,670
0.008846
# Copyright 2020 Makani Technologies LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
ig.MakeParams('common.all_params') _SERVOS = ['A' + f for f in '124578'] + ['E1', 'E2', 'R1', 'R2'] _FLAPS = _SERVOS[0:6] + ['Elevator'
, 'Rudder'] def GetSimLimits(): servo_limits = [_CONFIG['sim']['servos_sim'][i]['servo_drive'] for i in range(len(_SERVOS))] return {_SERVOS[i]: (servo_limits[i]['ref_model_min_position_limit'], servo_limits[i]['ref_model_max_position_limit']) for i in range(len(...
shadowmint/nwidget
lib/cocos2d-0.5.5/test/test_draw_elbows2.py
Python
apache-2.0
1,141
0.032428
# This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "s, q" tags = "Draw, join" import cocos from cocos.director import director from cocos import draw import pyglet class TestFigur...
xs, ys) ) self.line_to( (xs*2,ys) ) self.line_to( (xs*3,ys*2) ) self.line_to( (xs*3+100,ys*2) ) class TestLayer(cocos.layer.Layer): def __init__(self): super( TestLayer, self ).__init__() self.add( TestFigure() ) self.schedule( lambda x: 0 ) def...
__': main()
dantezhu/yunbk
yunbk/log.py
Python
mit
109
0
# -*- coding: utf-8 -*- import logging from . import co
nstants logger = logging.getLogger(constants.NAME
)
chebykinn/university
circuitry/lab4/convert.py
Python
mit
1,703
0.008221
# -*- coding: utf-8 -*- """ Created on Fri Dec 04 13:10:20 2015 @author: bayevskihk """ import sys def main(argv): number = len(argv) data_addr = 0 last_addr = 0 if(number != 2): return else: try: data_addr = int(argv[0]) last_addr = int(argv[1]) ...
.translate({None: "\n"}) hex_parts = hex_parts.split(); if(len(hex_parts) < 4): break for part in hex_parts: if(len(part) == 0): continue line += part attached += 1 if(attached == 4): attached = 0 ...
line = "" for i in range(addr_last - words): rom_file.write("00000000\n") rom_file.close() return 0 if __name__ == '__main__': main(sys.argv[1:])
SlateScience/MozillaJS
js/src/testing/mozbase/mozprofile/mozprofile/permissions.py
Python
mpl-2.0
12,792
0.002111
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. """ add permissions to the profile """ __all__ = ['MissingPrimaryLocationError', 'MultiplePrimaryLocationsError', ...
host, port = netloc.rsplit(':', 1) except ValueError: host = netloc port = _DEFAULT_PORTS.get(scheme, '80') try: location = Location(scheme, host, port, options) self.add(location, suppress_callback=True) excep...
# ensure that a primary is found if check_for_primary and not self.hasPrimary: raise LocationsSyntaxError(lineno + 1, MissingPrimaryLocationError()) if self.add_callback: self.add_callback(new_locations) class Permissions(object):...
silvahaberl/Jezici-gramatike-automati-
KA.py
Python
unlicense
16,900
0.034099
from util import * import random, string from random import randint import time class KonačniAutomat(types.SimpleNamespace): """Automat koji prepoznaje regularni jezik.""" @classmethod def iz_komponenti(klasa, stanja, abeceda, prijelaz, početno, završna): """Sipser page 35 definition 1.5 - konstrukcija iz petor...
n rječnik brojPonavljanjaStanja = generirajRječnik(lista,duljinaListe) a = KonačniAutomat.izračunavanje(automat,riječ) j = 0 for i in a: break stanjePonavljanja = '' for i in a: j = j +
1 brojPonavljanjaStanja[i] +=1 if brojPonavljanjaStanja[i] == 2 and j<= int(p): stanjePonavljanja = i mjestoNapuhavanja = j-1 break kolikoPuta = 0 count = 0 b = KonačniAutomat.izračunavanje(automat,riječ) for k in b: if k == stanjePonavljanja: kolikoPuta += 1 count = 1 if k !=...
binaryAccess/Empire
lib/modules/collection/file_finder.py
Python
bsd-3-clause
6,095
0.017063
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-FileFinder', 'Author': ['@harmj0y'], 'Description': ('Finds sensitive files on the domain.'), 'Background' : True, 'OutputExt...
f.close() # get just the code needed for the specified function script = helpers.generate_dynamic_powershell_script(moduleCode, moduleName) script += moduleName + " " for option,values in self.options.iteritems(): if option.lower() != "agent": if valu...
if values['Value'].lower() == "true": # if we're just adding a switch script += " -" + str(option) else: script += " -" + str(option) + " " + str(values['Value']) script += ' | Out-String | %{$_ + \"`n\"};"`n...
Wallix-Resilience/LogMonitor
resilience/zookeeper/configure/config.py
Python
gpl-2.0
4,845
0.009494
#!/usr/bin/python from txzookeeper.client import ZookeeperClient from txzookeeper.retry import RetryClient import zookeeper import sys from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA import os from twisted.python import log from twisted.internet import reactor, defer log.startLogging(sys.stdout) class...
.addCallback(_get_value) m.addCallback(_call) m.addErrback(self._err) if not callback: data = self.zk.get(path) data.addCallback(_get_value) data.addErrback(self._err) else: data, diff
= self.zk.get_children_and_watch(path) data.addCallback(_get_value) data.addErrback(self._err) diff.addCallback(_call) diff.addErrback(self._err) def _get_conf_data(self, path, callback = None): """ get and watch data from the configuration tree, usi...
derolf/Plex.ArgusTV.bundle
Contents/Libraries/Shared/mysql/connector/protocol.py
Python
gpl-2.0
25,785
0.000504
# MySQL Connector/Python - MySQL driver written in Python. # Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. # MySQL Connector/Python is licensed under the terms of the GPLv2 # <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most # MySQL Connectors. There are special exceptio...
e that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA "...
mkuron/espresso
doc/tutorials/06-active_matter/EXERCISES/flow_field.py
Python
gpl-3.0
5,548
0.005768
################################################################################ # # # Copyright (C) 2010-2018 The ESPResSo project # # ...
variables 'type' and 'pos' to # these values, respectively. ... mode = ... pos = ... ########################################################################## ## Exercise 2 ## # Create an output directory that is labeled according # to the value of the type and position, use the parameter # 'outdir' to store this...
s = 1000 prod_length = 50 dt = 0.01 system = espressomd.System(box_l=[length, length, length]) system.seed = system.cell_system.get_state()['n_nodes'] * [1234] system.cell_system.skin = 0.3 system.time_step = dt system.min_global_cut = 1.0 ########################################################################## # ...
tommybobbins/PiThermostat
django/hotf/schedule/feeds/__init__.py
Python
gpl-2.0
1,787
0.00056
import itertools from djang
o.conf import settings from django.contrib.syndication.views import Feed, FeedDoesNotExist from django.utils import timezone from schedule.feeds.ical import ICalendarFeed from schedule.models import Calendar class UpcomingEventsFeed(Feed): feed_id = "upcoming
" def feed_title(self, obj): return "Upcoming Events for %s" % obj.name def get_object(self, request, calendar_id): return Calendar.objects.get(pk=calendar_id) def link(self, obj): if not obj: raise FeedDoesNotExist return obj.get_absolute_url() def items(...
shmir/PyTestCenter
testcenter/api/stc_rest.py
Python
apache-2.0
3,868
0.001293
""" :author: yoram@ignissoft.com """ import getpass from random import randint from stcrestclient import stchttp class StcRestWrapper(object): def __init__(self, logger, server, port=80, user_name=getpass.getuser(), session_name=None): """ Init STC REST client. :param server: STC REST API serv...
return self.ls.get(obj_ref, attribute).split() def config(self, obj_ref, **attributes): """ Set or modifies one or more object attributes, or a relation. :param obj_ref: requested object reference. :param attributes: dictionary of {at
tributes: values} to configure. """ self.ls.config(obj_ref, **attributes) def subscribe(self, **arguments): """ Subscribe to statistics view. :param arguments: subscribe command arguments. must arguments: parent, resultParent, configType, resultType + addit...
mmottahedi/neuralnilm_prototype
scripts/e452.py
Python
mit
16,657
0.002401
from __future__ import print_function, division import matplotlib import logging from sys import stdout matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import (Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer, Bidirectiona...
r, 'num_units': (SEQ_LENGTH - 3) * NUM_FILTERS, 'nonlinearity': rectify }, { 'type': ReshapeLayer, 'shape': (N_SEQ_PER_BATCH, SEQ_LENGTH - 3, NUM_FILTERS) }, { 'type': DimshuffleLayer, 'pattern': (0, 2, 1) # (batch,...
DeConv1DLayer, 'num_output_channels': 1, 'filter_length': 4, 'stride': 1, 'nonlinearity': None, 'border_mode': 'full' }, { 'type': DimshuffleLayer, 'pattern': (0, 2, 1) # back to (batch, time, features) } ] ...
mhrivnak/ObservingReports
ajax/current_user_telescopes.py
Python
bsd-3-clause
204
0.004902
from google.appengine.ext import db import models import forms from crud_handler import CRUDHandler class CurrentUserTelescope
s(CRUDHandler): model = models.Telescope f
orm = forms.TelescopeForm
jccaicedo/localization-agent
detection/rcnn/subcatDetector.py
Python
mit
4,558
0.032032
import os,sys from sklearn import svm from sklearn.cluster import KMeans import numpy as np import utils as cu import libLearning as learn import libDetection as det import trainDetector ######################################## ## IMPLEMENTATION OF SINGLE LINEAR DETECTOR ######################################## class ...
trainDetector.readPositivesData(params['positivesFeatures']) if not os.path.is
file(params['labelsFile']): initializeSubcategories(positives,int(params['totalNumberOfSubcategories']),params['labelsFile']) sys.exit() params['modelParams'] = params['modelParams']+'subcategoryLabels:'+params['labelsFile']+'!subcategory:'+params['subcategory']+'!' args = trainDetector.parseModelParams(param...
drxaero/calibre
src/calibre/ebooks/rtf2xml/hex_2_utf8.py
Python
gpl-3.0
22,353
0.005726
######################################################################### # # # # # copyright 2002 Paul Henry Tremblay # # ...
ted in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # #
General Public License for more details. # # # # # ######################################################################### import sys, os, cStringIO ...
gilliM/MFQ
ModisFromQgis/mypymodis/qualitymodis.py
Python
gpl-2.0
6,568
0.001218
#!/usr/bin/env python # class to convert/process modis data # # (c) Copyright Ingmar Nitze 2013 # Authors: Ingmar Nitze, Luca Delucchi # Email: initze at ucc dot ie # Email: luca dot delucchi at iasma dot it # ################################################################## # # This MODIS Python class is licens...
D13A2': ([2], ['QAGrp1']), 'MYD13A2': ([2], ['QAGrp1']), 'MOD13A3': ([2], ['QAGrp1']), 'MYD13A3': ([2], ['QAGrp1']), 'MOD13C1': ([2], ['QAGrp1']), 'MYD13C1': ([2], ['QAGrp1']), 'MOD13C2': ([2], ['QAGrp1']), '...
'MYD11A1': ([1, 5], ['QAGrp2', 'QAGrp2']), 'MOD11A2': ([1, 5], ['QAGrp4', 'QAGrp4']), 'MYD11A2': ([1, 5], ['QAGrp4', 'QAGrp4']), 'MOD11B1': ([1, 5, -2], ['QAGrp2', 'QAGrp2', 'QAGrp3']), 'MYD11B1': ([1, 5, -2], ['QAGrp2', 'QAGrp2', 'QAGrp3']), ...
KMNR/Webstream
webstreamd/webstreamd/clean.py
Python
mit
1,688
0.012441
""" @author Stephen Jackson <scj7t4@mst.edu> Removes recordings from a too early period. """ import subprocess import sys import os from datetime import datetime, timedelta from settings import Settings settings = Settings() def do_directory(p): """ Recurses into directories looking for files. p i...
s.path.join(p,f)): do_file(p,f) elif os.pat
h.isdir(os.path.join(p,f)): do_directory(os.path.join(p,f)) if len(contents) == 0: subprocess.Popen(['rm','-r',p]).wait() def do_file(p,f): """ Checks a file to see if it is old enough to warrant deleing p is the directory it is in f is the name of the file. """ (bn...
HybridF5/nova
nova/tests/unit/cells/test_cells_rpc_driver.py
Python
apache-2.0
8,963
0.000558
# Copyright (c) 2012 Rackspace Hosting # All Rights Reserved. # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/license...
(CellsRPCDriverTestCase, self).setUp() fakes.init(self) self.ctxt = context.RequestContext('fake', 'fake') self.driver = rpc_driver.CellsRPCDriver() def test_start_servers(self): self.flags(rpc_driver_queue_base='cells.intercell42', group='cells') fake_msg_runner = fakes.get...
def __init__(_self, msg_runner): self.assertEqual(fake_msg_runner, msg_runner) self.stubs.Set(rpc_driver, 'InterCellRPCDispatcher', FakeInterCellRPCDispatcher) self.mox.StubOutWithMock(rpc, 'get_server') for message_type in messaging.MessageR...
UFTS-Device/NanoCoin
qa/rpc-tests/create_cache.py
Python
mit
594
0.003367
#
!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/
mit-license.php. # # Helper script to create the cache # (see BitcoinTestFramework.setup_chain) # from test_framework.test_framework import BitcoinTestFramework class CreateCache(BitcoinTestFramework): def setup_network(self): # Don't setup any test nodes self.options.noshutdown = True def ...
ufjfeng/leetcode-jf-soln
python/202_happy_number.py
Python
mit
1,204
0.006645
""" Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the p
rocess until the number equals 1 (where it will stay)
, or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: 19 is a happy number 1**2 + 9**2 = 82 8**2 + 2**2 = 68 6**2 + 8**2 = 100 1**2 + 0**2 + 0**2 = 1 Credits: Special thanks to @mithmatt and @ts for adding this prob...
GeoscienceAustralia/amazonia
test/unit_tests/test_asg.py
Python
apache-2.0
8,542
0.002693
import troposphere.elasticloadbalancing as elb from amazonia.classes.asg import Asg from amazonia.classes.asg_config import AsgConfig from amazonia.classes.block_devices_config import BlockDevicesConfig from amazonia.classes.simple_scaling_policy_config import SimpleScalingPolicyConfig from network_setup import get_net...
cooldown=120), SimpleScalingPolicyConfig(name='medium - load', description='When under medium CPU load for five minutes, add one instance, ' 'wait 45 seconds', metric_name='CP...
tilization', comparison_operator='GreaterThanOrEqualToThreshold', threshold='25', evaluation_periods=1, period=300, scaling_adjustment=1, ...
blooparksystems/odoo
addons/stock/res_config.py
Python
gpl-3.0
10,890
0.003581
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from openerp.osv import fields, osv from openerp.tools.translate import _ class res_company(osv.osv): _inherit = "res.company" _columns = { 'propagation_minimum_delta': fields.integer('Minimum Delta for ...
one): company_id = super(res_company, self).create(cr, uid, vals, context=context) self.create_transit_location(cr, uid, company_id, vals['name'], context=context) return company_id _defaults = { 'propagation_minimum_delta': 1, } class stock_config
_settings(osv.osv_memory): _name = 'stock.config.settings' _inherit = 'res.config.settings' def set_group_locations(self, cr, uid, ids, context=None): """ This method is automatically called by res_config as it begins with set. It is used to implement the 'one group or another' ...
certsocietegenerale/FIR
fir_notifications/methods/jabber.py
Python
gpl-3.0
4,038
0.003219
import markdown2 from django.conf import settings import xmpp from django import forms from fir_notifications.methods import NotificationMethod from fir_notifications.methods.utils import request from fir_plugins.links import registry as link_registry from django.utils.translation import gettext_lazy as _ class Cli...
if not self._ensure_connection(): print("Cannot contact the XMPP server") return for user, templates in users.items(): jid = self._get_jid(user) if not self.enabled(event, user, paths) or jid is None: continue template = self._get_temp...
sage = xmpp.protocol.Message(jid, body=params['short_description'].encode('utf-8'), subject=params['subject'].encode('utf-8'), typ='chat') html = xmpp.Node('html', {'xmlns': 'http://jabber.org/protocol/xhtml-im'}) text = u"<body xmlns='http://www.w3.or...
thefactory/marathon-python
marathon/util.py
Python
mit
2,499
0.0012
# collections.abc new as of 3.3, and collections is deprecated. collections # will be unavailable in 3.9 try: import collections.abc as collections except ImportError: import collections import datetime import logging try: import json except ImportError: import simplejson as json import re def get_l...
'): return self.default(obj.json_repr(minimal=True)) if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') if isinstance(obj, collections.Iterable) and not isinstance(obj, str): try: return {k: self.default(v) for k, v i...
for e in obj if (e or e in (False, 0))] return obj def to_camel_case(snake_str): words = snake_str.split('_') return words[0] + ''.join(w.capitalize() for w in words[1:]) def to_snake_case(camel_str): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) return re.sub('([a-z0-9])([A-Z])', r...
openstack/octavia
octavia/api/drivers/driver_agent/driver_listener.py
Python
apache-2.0
5,587
0
# Copyright 2018 Rackspace, US Inc. # Copyright 2019 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 # # Unle...
stener(exit_event): _cleanup_socket_file(CONF.driver_agent.status_socket_path) server = ForkingUDSServer(CONF.driver_agent.status_socket_path, StatusRequestHandler) server.timeout = CONF.driver_agent.status_request_timeout server.max_children = CONF.driver_agent.status_ma...
shutdown...') # Can't shut ourselves down as we would deadlock, spawn a thread threading.Thread(target=server.shutdown).start() LOG.info('Driver status listener shutdown finished.') server.server_close() _cleanup_socket_file(CONF.driver_agent.status_socket_path) def stats_listener(exit_event): ...
arksega/etcd-demo
app/webapp.py
Python
mit
499
0.006012
#!/bin/python3 from flask import render_template from flask import Flask import urllib.reques
t import json app = Flask(__name__) def imleader(): with urllib.request.urlopen('http://localhost:2379/v2/stats/self') as f: data = json.loads(f.read().decode('utf-8')) return data['state'] == 'StateLeader' @app.route('/') def index(): return render_template('index.html', imleader=imleader()) if...
# vim: ts=4 sw=4 et
eikevons/yorik-photos
photos/views.py
Python
mit
8,028
0.002242
## ## Copyright (c) 2014 Jan Eike von Seggern ## from functools import wraps from math import ceil from time import time from flask import render_template, session, redirect, url_for, flash, escape, abort, send_file, request, jsonify, send_from_directory from werkzeug import check_password_hash from .application imp...
print(' ', us.images[chksum]) us.dbimport(Photo) us.clear() return redirect(url_for('list')) @app.route('/_upload_images', methods=('GET', 'POST')) @logged_in def upload_images(): session_id = '{0}::{1}'.format(session['userid'], time()) session['upload_session'] = session_id us = UploadSes...
file(f, f.filename) us.finish_uploads() images = [{'chksum': chksum, 'date': im['date'].strftime('%d.%m.%Y %H:%M:%S')} for chksum, im in us.images.items()] ret = {'session': session_id, 'images': images} print('XX', ret) return jsonify(**ret) @app.route('/preview/<chks...
Ramblurr/ephemvpn
ephemvpn/timehelpers.py
Python
bsd-3-clause
2,759
0.004349
import datetime import time # # From the django project # https://github.com/django/django/blob/4a103086d5c67fa4fcc53c106c9fdf644c742dd8/django/utils/timesince.py # Copyright (c) Django Software Foundation and individual contributors. # All rights reserved. def ungettext(a,b,count): if count: return b ...
return a def timesince(d, now=None, reversed=False): """ Takes two datetime objects
and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" a...
hzlf/openbroadcast
website/apps/atracker/admin.py
Python
gpl-3.0
1,072
0.005597
"""Admin classes for the ``object_events`` app.""" from django.contrib import admin from .models import Event, EventType from lib.admin.actions import export_as_csv_action class EventTypeAdmin(admin.ModelAdmin): list_display = ['title', ] class EventAdmin(admin.ModelAdmin): list_display = ['user', 'content_...
_content_object__name', 'event_type__title', 'created'])] def content_object(self, obj):
return obj.content_object content_object.short_description = 'Content object' def user_email(self, obj): return obj.user.email user_email.short_description = 'User' def type_title(self, obj): return obj.event_type.title type_title.short_description = 'Type' admin.site.regi...
drix00/pysemeels
tests/hitachi/eels_su/test_ana_file.py
Python
apache-2.0
3,171
0.000946
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. py:currentmodule:: pysemeels.hitachi.eels_su.test_ana_file .. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca> Tests for the module :py:mod:`pysemeels.hitachi.eels_su.ana_file`. """ ####################################################################...
rent_module_path(__file__, "../../../test_data/hitachi/eels_su/30kV_7eV.ana") if is_bad_file(self.ana_file_path): pytest.skip("File not found: {}".format(self.ana_file_p
ath)) def tearDown(self): """ Teardown method. """ unittest.TestCase.tearDown(self) def testSkeleton(self): """ First test to check if the testcase is working with the testing framework. """ # self.fail("Test if the testcase is working.") ...
CloudI/CloudI
src/service_api/python/jsonrpclib/jsonrpclib/utils.py
Python
mit
3,412
0
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the...
if an object
is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """ Before Python 3.4, enumerations didn't exist. :param...
simonzhangsm/voltdb
examples/metrocard/exportServer.py
Python
agpl-3.0
6,191
0.004361
#!/usr/bin/env python # This file is part of VoltDB. # Copyright (C) 2008-2018 VoltDB Inc. # # 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 limitatio...
gi/ """ import sys, os from time import ctime from urlparse import parse_qs try: from t
wilio.rest import TwilioRestClient except ImportError: raise ImportError("Add Twilio module if you want to try sending text or email messages on export \"alerts\"\nOtherwise remove this import and method below.") from wsgiref.simple_server import make_server def checkPhoneNum(phone): # Twilio wants a leading ...
atumanov/ray
examples/rl_pong/driver.py
Python
apache-2.0
7,324
0
# This code is copied and adapted from Andrej Karpathy's code for learning to # play Pong https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5. from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import os import ...
ng_add = 0 for t in reversed(range(0, r.size)): # Reset the sum, since this was a game boundary (pong specific!). if r[t] != 0: running_add = 0 runn
ing_add = running_add * gamma + r[t] discounted_r[t] = running_add return discounted_r def policy_forward(x, model): h = np.dot(model["W1"], x) h[h < 0] = 0 # ReLU nonlinearity. logp = np.dot(model["W2"], h) p = sigmoid(logp) # Return probability of taking action 2, and hidden state. ...
mdhunter/twitter-to-wordcloud
filter_corpus.py
Python
mit
2,888
0.003809
#!/usr/bin/env python3 # Filters one or more input text files, building a collection of words from # the corpora, and filtering t
hem # # Copyright 2016 Mathew Hunter import argparse import nltk import os import re # default regex that filters out links, numbers, and single characters default_regex = "^(?!http|\d)\w{2,}" # Filters the specified corpus def filter_corpus_data(string_data, stopwords=[], use_nltk_default=True): # Tokenize an...
tokens = tokenizer.tokenize(string_data) # Filter filtered_words = filter_corpus_words(tokens, stopwords, use_nltk_default) return " ".join(filtered_words) # Filters the referenced files to produce a filtered corpus def filter_corpus_files(filenames, stopwords=[], use_nltk_default=True): # Proces...
hawesie/strands_social
card_image_tweet/scripts/tweet_card.py
Python
mit
2,961
0.014184
#! /usr/bin/env python import rospy import sys from time import sleep import actionlib import yaml from random import randint #from threading import Timer import strands_tweets.msg import image_branding.msg from std_msgs.msg import String from sensor_msgs.msg import Image #from cv_bridge import CvBridge, CvBridge...
et_result() tweetgoal.text = text tweetgoal.with_photo = True tweetgoal.photo = br_ph.branded_image self.client.send_g
oal(tweetgoal) #tweettext=card_image_tweet.msg.Tweet() #tweettext.text = text #tweettext.photo = br_ph.branded_image #self.tw_pub.publish(tweettext) self.client.wait_for_result() ps = self.client.get_result() print ps ...
MTgeophysics/mtpy
legacy/quality.py
Python
gpl-3.0
445
0.004494
""" mtpy/processing/q
uality.py Functions for the analysis of time series data quality. Output can be visualised with the help of mtpy/imaging/plotquality.py @UofA, 2013 (LK) """ #================================================================= import numpy as np import re import sys import os import os.path as op impor
t copy import mtpy.utils.exceptions as MTex #=================================================================