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
kevenli/scrapydd
scrapydd/migrates/versions/018_nodes_is_deleted.py
Python
apache-2.0
458
0.002183
from sqlalchemy im
port * from migrate import * meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine nodes_table = Table('nodes', meta, autoload=True) nodes_table_is_deleted = Column('is_deleted', Integer, default=False) nodes_table_is_deleted.cr
eate(nodes_table) def downgrade(migrate_engine): meta.bind = migrate_engine nodes_table = Table('nodes', meta, autoload=True) nodes_table.c['is_deleted'].drop()
nkgilley/home-assistant
homeassistant/components/bluesound/const.py
Python
apache-2.0
240
0.004167
"""Constants for t
he Bluesound HiFi wireless speakers and audio integrations component.""" DOMAIN = "bluesound" SERVICE_CLEAR_TIMER =
"clear_sleep_timer" SERVICE_JOIN = "join" SERVICE_SET_TIMER = "set_sleep_timer" SERVICE_UNJOIN = "unjoin"
crazy-canux/xomnibus
omnibus/base.py
Python
apache-2.0
6,156
0.000162
#!/usr/bin/env python # -*- coding: utf-8 -*- ###################################################################### # Copyright (C) 2015 Canux CHENG # # All rights reserved # # Name: base.py # Author: Canux [email protected] ...
'If not define, use\ default value.') self.group_parser.add_argument("-F", "--force", action="store_true",
required=False, help="If file exist, rewrite it.", dest="force") self.group_parser.add_argument("-P", "--path", default="%s" % self.path, required=False, ...
google/gae-secure-scaffold-python3
src/securescaffold/factory.py
Python
apache-2.0
3,574
0
# Copyright 2020 Google LLC # # Li
censed 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 # # U
nless 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 under the License. import...
chebhou/Text-from-to-.XML
text_io_xml.py
Python
gpl-2.0
3,503
0.015701
bl_info = { "name" : "text objects to-from xml", "author" : "chebhou", "version" : (1, 0), "blender" : (2, 7, 3), "location" : "file->export->text to-from xml", "discription" : "copys an text objectx from-to xml file", "wiki_url" : " https://github.com/chebhou", "tracker_url" : "https://...
xtNode(obj.data.body) object.appendChild(txt_node) scene.appendChild(object) #write to a file file
_handle = open(filepath,"wb") file_handle.write(bytes(doc.toprettyxml(indent='\t'), 'UTF-8')) file_handle.close() class text_export(Operator, ExportHelper): """write and read text objects to a file""" bl_idname = "export_scene.text_xml" bl_label = "text from-to xml" ...
eli261/jumpserver
apps/settings/serializers.py
Python
gpl-2.0
1,295
0.003089
from rest_framework import serializers class MailTestSerializer(serializers.Serializer): EMAIL_HOST = serializers.CharField(max_length=1024, required=True) EMAIL
_PORT = serializers.IntegerField(default=25) EMAIL_HOST_USER = serializers.Ch
arField(max_length=1024) EMAIL_HOST_PASSWORD = serializers.CharField(required=False, allow_blank=True) EMAIL_FROM = serializers.CharField(required=False, allow_blank=True) EMAIL_USE_SSL = serializers.BooleanField(default=False) EMAIL_USE_TLS = serializers.BooleanField(default=False) class LDAPTestSeri...
sunqm/pyscf
pyscf/mcscf/test/test_n2_df.py
Python
apache-2.0
10,791
0.00834
#!/usr/bin/env python # Copyright 2014-2020 The PySCF Developers. 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 # # U...
ncore = mc.ncore nocc = ncore + mc.ncas eri0 = ao2mo.restore(1, ao2mo.kernel(eri0, mc.mo_coeff), nmo) eris = mc.ao2mo(mc.mo_coeff) self.assertTrue(numpy.a
llclose(eri0[:,:,ncore:nocc,ncore:nocc], eris.ppaa)) self.assertTrue(numpy.allclose(eri0[:,ncore:nocc,:,ncore:nocc], eris.papa)) def test_assign_cderi(self): nao = molsym.nao_nr() w, u = scipy.linalg.eigh(mol.intor('int2e_sph', aosym='s4')) idx = w > 1e-9 mf = scf.density_f...
michaelbrooks/django-stream-analysis
stream_analysis/management/commands/cleanup_streams.py
Python
mit
300
0.003333
from django.core.management.base import BaseCommand from stream_analysis.utils
import cleanup class Command(BaseCommand): """ Removes streaming data we no longer need. """ help = "Removes streaming data we no longer need." def ha
ndle(self, *args, **options): cleanup()
dana-i2cat/felix
vt_manager/src/python/vt_manager/tests/testcreatesync.py
Python
apache-2.0
407
0.012285
from vt_manager.mod
els import * import os import xmlrpc
lib am = xmlrpclib.Server("https://expedient:[email protected]:8445/xmlrpc/plugin") #xml = open("/opt/ofelia/vt_manager/src/python/vt_manager/tests/xmltest.xml", "r").read() xml = open(os.path.join(os.path.dirname(__file__), "xmltest.xml"), "r").read() am.send_sync("https://expedient:[email protected]...
Ziqi-Li/bknqgis
pandas/doc/plots/stats/moments_rolling_binary.py
Python
gpl-2.0
617
0
from moment_plots import * n
p.random.seed(1) ts = test_series() s = ts.cumsum() ts2 = test_series() s2 = ts2.cumsum() s[20:50] = np.NaN s[120:150] = np.NaN fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True) ax0, ax1, ax2 = axes ax0.plot(s.index, s.values) ax0.plot(s2.index, s2.values) ax0.set_title('time series') ax1.plot(s.index, ...
te() fig.subplots_adjust(bottom=0.10, top=0.95) plt.show() plt.close('all')
jesuscript/topo-mpi
topo/projection/basic.py
Python
bsd-3-clause
15,525
0.012367
""" Repository for the basic Projection types, without any special dependencies or requirements. $Id$ """ __version__ = "$Revision$" from copy import copy from numpy import exp,ones,zeros,array,nonzero import param # So all Projections are present in this package from topo.base.projection import Projection from t...
nectionField into a shared abstract parent class. # We have agreed to make this right by adding a constant property that # will be set true if the learning should be active
# The SharedWeightCFProjection class and its anccestors will # have this property set to false which means that the # learning will be deactivated class SharedWeightCFProjection(CFProjection): """ A Projection with a single set of weights, shared by all units. Otherwise s...
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/test/chromedriver/test/webserver.py
Python
gpl-3.0
6,705
0.00865
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import BaseHTTPServer import os import threading class Responder(object): """Sends a HTTP response. Used with TestWebServer.""" def __init__(self, han...
erver(self._OnRequest, server_cert_and_key_path) self._thread = threading.Thread(target=self._server.serve_forever) self._thread.daemon = True self._thread.start() self._path_data_map = {}
self._path_callback_map = {} self._path_maps_lock = threading.Lock() def _OnRequest(self, request, responder): path = request.GetPath().split('?')[0] # Serve from path -> callback and data maps. self._path_maps_lock.acquire() try: if path in self._path_callback_map: body = self...
diogocs1/comps
web/addons/account/tests/test_tax.py
Python
apache-2.0
1,740
0.000575
from openerp.tests.common import TransactionCase class TestTax(TransactionCase): """Tests for taxes (account.tax) We don't really need at this point to link taxes to tax code
s (account.tax.code) nor to companies (base.company) to check computation results. """ def setUp(self): super(TestTax, self).setUp() self
.tax_model = self.registry('account.tax') def test_programmatic_tax(self): cr, uid = self.cr, self.uid tax_id = self.tax_model.create(cr, uid, dict( name="Programmatic tax", type='code', python_compute='result = 12.0', python_compute_i...
NINAnor/QGIS
python/plugins/processing/gui/ConfigDialog.py
Python
gpl-2.0
10,846
0.00083
# -*- coding: utf-8 -*- """ *************************************************************************** ConfigDialog.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com **************************...
tyItem = QStandar
dItem() emptyItem.setEditable(False) rootItem.insertRow(0, [providersItem, emptyItem]) for group in settings.keys(): if group in priorityKeys: continue groupItem = QStandardItem(group) icon = ProcessingConfig.getGroupIcon(group) gr...
kanjie128/test
pymavlink/fgFDM.py
Python
lgpl-3.0
9,572
0.007522
#!/usr/bin/env python # parse and construct FlightGear NET FDM packets # Andrew Tridgell, November 2011 # released under GNU GPL version 2 or later import struct, math class fgFDMError(Exception): '''fgFDM error class''' def __init__(self, msg): Exception.__init__(self, msg) self.message = 'fg...
# 0.0 - 1.0 indicating the amount of stall self.mapping.add('slip_deg', units='degrees') # slip ball deflection # Engine status self.mapping.add('num_engines') # Number of valid engines self.mapping.add('eng_state', self.FG
_MAX_ENGINES) # Engine state (off, cranking, running) self.mapping.add('rpm', self.FG_MAX_ENGINES) # Engine RPM rev/min self.mapping.add('fuel_flow', self.FG_MAX_ENGINES) # Fuel flow gallons/hr self.mapping.add('fuel_px', self.FG_MAX_ENGINES) # Fuel pressure psi self.mapping....
shanghaiyangming/trouter
test/t.py
Python
gpl-3.0
1,035
0.018357
#!/usr/bin/env python # -*- coding: UTF-8 -*- import tornado from multiprocessing import Process from tornado.httpclient import AsyncHTTPClient repeat = 5 def handle_response(response): global repeat repeat -= 1 if response.error: print "err:%s"%(response.error,) else: print response...
49&re_openid=yangming_%d&redpack_id=55067da0479619680980
ff62"%(client_id,) request = tornado.httpclient.HTTPRequest( url, method='GET', connect_timeout = 60, request_timeout = 300 ) client = AsyncHTTPClient() client.fetch(request,handle_response) tornado.ioloop.IOLoop.instance().sta...
lucienfostier/gaffer
python/GafferUI/PathVectorDataPlugValueWidget.py
Python
bsd-3-clause
4,045
0.026452
########################################################################## # # Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. # Copyright (c) 2012, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
lt["leaf"] = Gaffer.Metadata.value( self.getPlug(), "path:leaf" ) result["valid"] = Gaffer.Metadata.value( self.getPlug(), "path:valid" ) bookmarks = Gaffer.Metadata.value( self.getPlug(), "path:bookmarks" ) if bookmarks is not None : result["bookmarks"] = GafferUI.Bookmarks.acquire( self.getPlug(), type( sel...
result.update( self.__deprecatedPathChooserDialogueKeywords ) return result
adam111316/SickGear
lib/chardet/langgreekmodel.py
Python
gpl-3.0
12,867
0.343514
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Ri...
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,0,0,0,3,3,0,3,3,3,0,0,1,2,3,0, 3,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,0,3,2,2,3,3,0,3,3,3,3,3,2,1,3,0,3,2,3,3,2,1,0,0, 0,0,0,0,0,0,0,0,0,0...
2,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,3,0,3,2,3,0,0,3,3,3,0, 3,0,0,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,2,0,3,2,3,0,0,3,2,3,0, 2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,1,2,2,3,3,3,3,3,3,0,2,3,0,3,0,0,0,3,3,0,3,0,2,0,0,2,3,1,0, ...
mmadsen/pytransmission
runtests.py
Python
apache-2.0
709
0.002821
#!/usr/bin/env python # Copyright (c) 2013. Mark E. Madsen <[email protected]> # # This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details. """ Description here """ import unittest if __name__ ==
'__main__': # use t
he default shared TestLoader instance test_loader = unittest.defaultTestLoader # use the basic test runner that outputs to sys.stderr test_runner = unittest.TextTestRunner() # automatically discover all tests in the current dir of the form test*.py # NOTE: only works for python 2.7 and later t...
esquires/lvdb
test/temp2.py
Python
bsd-3-clause
66
0.015152
de
f mult(a, b): return a * b def div(a, b): return a / b
hsr-ba-fs15-dat/python-social-auth
examples/django_me_example/example/settings.py
Python
bsd-3-clause
7,162
0.000279
import sys from os.path import abspath, dirname, join import mongoengine sys.path.insert(0, '../..') DEBUG = True TEMPLATE_DEBUG = DEBUG ROOT_PATH = abspath(dirname(__file__)) ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.d...
, 'social.backends.steam.SteamOpenId', 'social.backends.podio.Podio
OAuth2', 'social.backends.amazon.AmazonOAuth2', 'social.backends.email.EmailAuth', 'social.backends.username.UsernameAuth', 'social.backends.wunderlist.WunderlistOAuth2', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/done/' URL_PATH = '' SOCIAL_AUTH_STR...
g-weatherill/oq-risklib
openquake/calculators/scenario_risk.py
Python
agpl-3.0
5,466
0
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014-2015, GEM Foundation # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the ...
lizations) result = calc.build_dict((L, R), general.Accu
mDict) lt2idx = {lt: i for i, lt in enumerate(riskmodel.loss_types)} for out_by_rlz in riskmodel.gen_outputs( riskinputs, rlzs_assoc, monitor): for out in out_by_rlz: lti = lt2idx[out.loss_type] stats = numpy.zeros((len(out.assets), 4), F64) # this is ugly...
kanzure/pyphantomjs
pyphantomjs/resources.py
Python
gpl-3.0
354,476
0.000014
# -*- coding: utf-8 -*- # Resource object code # # Created: Fri Dec 2 16:03:48 2011 # by: The Resource Compiler for PyQt (Qt v4.7.3) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x09\xbc\ \x2f\ \x2a\x6a\x73\x6c\x69\x6e\x74\x20\x73\x6c\x6f\x70\x7...
x0a\x20\x20\x49\ \x4d\x50\x4c\x49\x45\x44\x20\x57\x41\x52\x52\x41\x4e\x54\x49\x45\ \x53\x20\x4f\x46\x20\x4d\
x45\x52\x43\x48\x41\x4e\x54\x41\x42\x49\ \x4c\x49\x54\x59\x20\x41\x4e\x44\x20\x46\x49\x54\x4e\x45\x53\x53\ \x20\x46\x4f\x52\x20\x41\x20\x50\x41\x52\x54\x49\x43\x55\x4c\x41\ \x52\x20\x50\x55\x52\x50\x4f\x53\x45\x0a\x20\x20\x41\x52\x45\x20\ \x44\x49\x53\x43\x4c\x41\x49\x4d\x45\x44\x2e\x20\x49\x4e\x20\x4e\ \x4f\x20\x45\x5...
rybesh/pybtex
pybtex/database/output/bibtexml.py
Python
mit
3,696
0.001623
# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011 Andrey Golovizin # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, ...
e() ET.TreeBuilder.end(self, tag) self.newline() def element(self, tag, data): self.start(tag, newline=False) self.data(data) self.end(indent=False) class Writer(BaseWriter): """Outputs BibTeXML markup""" name = 'bibtexml' suffixes = '.xml', '.bibtexml' d...
data, stream): def write_persons(persons, role): if persons: w.start('bibtex:' + role) for person in persons: w.start('bibtex:person') for type in ('first', 'middle', 'prelast', 'last', 'lineage'): name =...
Thraxis/pymedusa
sickbeard/blackandwhitelist.py
Python
gpl-3.0
6,272
0.001435
# coding=utf-8 # Author: Dennis Lutter <[email protected]> # # # This file is part of SickRage. # # SickRage 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 opti...
log('Timeout while loading group from AniDB. ' 'Trying next group', logger.DEBUG) except Exception: logger.log('Faile
d while loading group from AniDB. ' 'Trying next group', logger.DEBUG) else: for line in group.datalines: if line[b'shortname']: short_group_list.append(line[b'shortname']) else: ...
asraf209/leetcode
src/3SumClosest/main.py
Python
gpl-3.0
2,156
0.005102
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. # Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c) # The solution set must not contain duplicate triplets. # Solution: # This ...
len(num) result = [1 << 33, -1, -1, -1] # a large number for first in range(size - 2): left = first + 1 right = size - 1 while left < right: curr = num[first] + num[left] + num[right] distance = abs(curr - target) if d...
result = [distance, num[first], num[left], num[right]] if curr < target: left += 1 else: right -= 1 return result[1] + result[2] + result[3] # if __name__ == '__main__': # data = [0,0,0] # target = 1 # s = Soluti...
djanowski/pygmentize
vendor/pygments/tests/test_util.py
Python
mit
5,303
0.001131
# -*- coding: utf-8 -*- """ Test suite for the util module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import unittest from pygments import util class FakeLexer(object): def analyse(text)...
pt({}, 'a', 'true'), True) equals(util.get_bool_opt({}, 'a', 'no'), False) raises(util.OptionError, util.get_bool_opt, {}, 'a', []) raises(util.OptionError, util.get_bool_opt, {}, 'a', 'foo') equals(util.get_int_opt({}, 'a', 1), 1) raises(util.OptionError, util.get_int_opt, {}, ...
util.get_int_opt, {}, 'a', 'bar') equals(util.get_list_opt({}, 'a', [1]), [1]) equals(util.get_list_opt({}, 'a', '1 2'), ['1', '2']) raises(util.OptionError, util.get_list_opt, {}, 'a', 1) def test_docstring_headline(self): def f1(): """ docstring headline...
iproduct/course-social-robotics
09-image-recognition-opencv-dnn/cv2_haar_cascade_demo.py
Python
gpl-2.0
1,513
0.001983
# import numpy as np import cv2 as cv if __name__ == "__main__": faceCascade = c
v.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml') eyeCascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml') # img = cv.imread('sachin.jpg') video_capture = cv.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = video_c...
scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv.CASCADE_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) roi_gray = gray[y:y + h, x:x ...
simpeg/discretize
tutorials/inner_products/4_advanced.py
Python
mit
6,674
0.002248
""" Advanced Examples ================= In this section, we demonstrate how to go from the inner product to the discrete approximation for some special cases. We also show how all necessary operators are constructed for each case. """ #################################################### # # Import Packages # -...
\sigma \nabla \cdot \vec{v}) = \mathbf{\psi_c^T M_c} (\sigma)\mathbf{ D v_f} \;\;\;\; (\psi \;\textrm{at centers and} \; \vec{v} \; \textrm{on faces} ) # # Where :math:`\mathbf{C_{ef}}` is the edges to faces curl operator and # :math:`\mathbf{C_{fe}}` is the faces to edges curl operator: # # .. math:: # (\vec{u} ,...
\;\textrm{on edges and} \; \vec{v} \; \textrm{on faces} )\\ # &= \mathbf{u_e^T M_e} (\sigma) \mathbf{ C_{fe} \, v_f} \;\;\;\; (\vec{u} \;\textrm{on faces and} \; \vec{v} \; \textrm{on edges} ) # # **With the operators constructed below, you can compute all of the # aforementioned inner products.** # # Make basic ...
developerQuinnZ/this_will_work
student-work/JacobJanak/class_lessons/zoo.py
Python
mit
1,060
0.004717
import random class Zoo: noOfAnimals = 0 noOfZoos = 0 def __init__(self, animals, ticketPrice): Zoo.noOfAnimals += len(animals) Zoo.noOfZoos += 1 self.ticketPrice = ticketPrice self.animals = animals def __iter__(self): for animal in self.animals: ...
animals)) self.mate(self.animals[num], self.animals[num2]) def mate(self, male, female): newAnimal = male[0:2] + female[2:] self.animals.append(newAnimal) Zoo.noOfAnimals += 1 print(newAnimal) if __name__ == '__main__': pdxAnimals = ['bat', 'lion', 'goats', 'elepha...
Zoo(vanAnimals, 25) vanZoo.randomMate() print(pdxZoo.noOfAnimals) print(Zoo.noOfAnimals)
desirable-objects/hotwire-shell
hotwire/builtins/pyeval.py
Python
gpl-2.0
4,083
0.008327
# This file is part of the Hotwire Shell project API. # Copyright (C) 2007 Colin Walters <[email protected]> # 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, includin...
and_compile @builtin_hotwire(singlevalue=True, input=InputStreamSchema('any', optional=True), output=OutputStreamSchema('any'), options=[['-f', '--file']]) def py_eval(context, *args): _("""Compile and execute Python expression. Iterable return values (define __it...
eError(_("Too few arguments specified")) locals = {'hot_context': context} if context.current_output_metadata and context.current_output_metadata.type is not None: if context.current_output_metadata.single: try: locals['it'] = context.snapshot_current_output() exc...
kmaehashi/jubamgr
controller/lib/jubamgr/controller/config.py
Python
lgpl-2.1
1,500
0.009333
# -*- coding: utf-8 -*- import json from .entity import * class JubaManagerConfig(object): def __init__(self): self._global_zookeeper = '' self._visors = [] self._clusters = [] self._servers = [] self._proxies = [] @classmethod def from_json(cls, data): # TODO handle errors cfg = ...
.create(x), cfg['proxies']) return obj def lookup(self, process_type, query_id): if process_type == 'server': return filter(lambda x: x.get_id() == query_id, self._servers)[0] elif proce
ss_type == 'proxy': return filter(lambda x: x.get_id() == query_id, self._proxies)[0] elif process_type == 'visor': return filter(lambda x: x.get_id() == query_id, self._visors)[0] elif process_type == 'cluster': return filter(lambda x: x.get_id() == query_id, self._clusters)[0] def get_all...
trhongbinwang/data_science_journey
deep_learning/keras/keras_as_tf_api.py
Python
apache-2.0
2,218
0.006763
# -*- coding: utf-8 -*- """ Created on Fri Mar 17 10:48:09 2017 keras as tf api always use as an tf api In this case, we use Keras only as a syntactical shortcut to generate an op that maps some tensor(s) input to some tensor(s) output, and that's it. @author: hongbin """ import tensorflow as tf from keras import...
# #A Keras model acts the same as a layer, and thus can be called on TensorFlow tensors: from keras.models import Sequential m
odel = Sequential() model.add(Dense(32, activation='relu', input_dim=784)) model.add(Dense(10, activation='softmax')) # this works! x = tf.placeholder(tf.float32, shape=(None, 784)) y = model(x)
gcmalloc/screen-calendar
screen.py
Python
gpl-3.0
5,346
0.001122
#!/usr/bin/env python2 # -*- coding: utf8 -*- # from __future__ import unicode_literals ''' This file is part of FIXME Screen Calendar. FIXME Events 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...
'rrule'), types.NoneType): evt = get_event(cal_name, dt_start, dt_end, e) if evt not in events: events.append(evt) else: for f in get_recurrences(cal_name, dt_start, dt_end, e): if f not in events: ...
name'] = random.getrandbits(32) # Get all events events = [] for cal in cfg.calendars: events += get_calendar(cal) events = sorted(events, key=lambda i: i['timestamp']) # Split according to date range today_start = arrow.get().replace(hour=0, minute=0, second=0) today_end = today_s...
ctrl-alt-d/fpuf
fpuf/utils/urls.py
Python
gpl-3.0
381
0.041995
from django.conf.urls import patterns,
url urlpatterns = patterns('fpuf.utils.views', url(r'^about/$', 'about', name ="varis_about_about" ) , url(r'^missatges/$', 'about', name ="varis_missatges_veure" ) , url(r'^condicions/$', 'condicions'
, name ="varis_condicions_condicions" ) , )
amtriathlon/GoldenCheetah
src/Resources/python/library.py
Python
gpl-2.0
3,658
0.030618
# # Python class library loaded when the interpreter # is installed by PythonEmbed #-------------------------------------------------- # API for accessing GC data #-------------------------------------------------- # basic activity data def __GCactivity(join="repeat", activity=None): rd={} for x in range(0,GC.s...
ity=__GCactivity GC.activityXdata=__GCactivityXdata GC.setChart=__GCsetChart GC.addCurve=__GCsetCurve GC.setAxis=__GCconfigAxis GC.annotate=__GCannotate # orientation GC_HORIZONTAL=1 GC_VERTICAL=2 # line style GC_LINE_NONE=0 GC_LINE_SOLID=1 GC_LINE_DASH=2 GC_LINE_DOT=3 GC_LINE_DASHDOT=4 # constants GC_ALIGN_BOTTOM=0...
CHART_PIE=4 GC.CHART_STACK=5 GC.CHART_PERCENT=6 # Axis type GC.AXIS_CONTINUOUS=0 GC.AXIS_DATE=1 GC.AXIS_TIME=2 GC.AXIS_CATEGORY=3 GC.SERIES_SECS = 0 GC.SERIES_CAD = 1 GC.SERIES_CADD = 2 GC.SERIES_HR = 3 GC.SERIES_HRD = 4 GC.SERIES_KM = 5 GC.SERIES_KPH = 6 GC.SERIES_KPHD = 7 GC.SERIES_NM = 8 GC.SERIES_NMD = 9 GC.SERIE...
arju88nair/projectCulminate
venv/lib/python3.5/site-packages/pylint/test/functional/test_compile.py
Python
apache-2.0
214
0.004673
# pylint: disable=missing-
docstring, unused-variable, pointless-statement, too-few-public-methods class WrapperClass(object): def method(self): var = +4294967296 sel
f.method.__code__.co_consts
uclouvain/OSIS-Louvain
attribution/tests/views/charge_repartition/common.py
Python
agpl-3.0
4,717
0.00212
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
ical_full = AttributionChargeNewFactory( attribution=self.attribution_full, learning_component_year=self.practical_component_full ) self.attribution = AttributionNew.objects.get(id=attribution_id) self.client.force_login(self.person.user) def clean_partim_charges(se...
self.charge_practical.delete() self.charge_lecturing.delete() self.attribution.delete()
finnurtorfa/aflafrettir.is
app/models.py
Python
mit
8,023
0.018576
import hashlib from datetime import datetime from flask import request from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from . import db, login_manager #pylint: disable-msg=E1101 @login_manager.user_loader def load_user(user_id): return User.query.get(in...
rue, autoincrement=True) title = db.Colu
mn(db.String(64)) body = db.Column(db.Text) body_html = db.Column(db.Text) language = db.Column(db.String(4), default='is') timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) category_id = db.Column...
TextusData/Mover
thirdparty/git-1.7.11.3/git-p4.py
Python
gpl-3.0
110,533
0.003655
#!/usr/bin/env python # # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. # # Author: Simon Hausmann <[email protected]> # Copyright: 2007 Simon Hausmann <[email protected]> # 2007 Trolltech ASA # License: MIT <http://www.opensource.org/licenses/mit-license.php> # import optparse, sy...
if isinstance(cmd,basestring): real_cmd = ' '.join(real_cmd) + ' ' + cmd else: real_cmd += cmd return real_cmd def chdir(dir): # P4 uses the PWD environment variab
le rather than getcwd(). Since we're # not using the shell, we have to set it ourselves. This path could # be relative, so go there first, then figure out where we ended up. os.chdir(dir) os.environ['PWD'] = os.getcwd() def die(msg): if verbose: raise Exception(msg) else: sys.s...
enricopal/snowball_decision
decision_algorithm.py
Python
apache-2.0
25,944
0.026287
import numpy as np import random import networkx as nx from operator import itemgetter import pandas as pd import sys import json import optparse ############################################################### #### CONCORDANCE, DISCORDANCE AND CREDIBILITY FUNCTIONS ###### #############################################...
return fact def discrimination_thresh(x):#non constant threshold return a - b*x ############################
############# ############ ALGORITHMS ################# ######################################### #distillation algorithm def compute_scores_2(cred_matrix,altern_list): n = len(altern_list) scores = {} #vector holding the score of each alternative keys = altern_list for i in keys: #initializ...
Puppet-Finland/trac
files/spam-filter/tracspamfilter/filters/registration.py
Python
bsd-2-clause
4,192
0.000954
# -*- coding: utf-8 -*- # # Copyright (C) 2006 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists of vo...
fragments['required'] = \ tag(fragments.get('required', ''), fragment) data.update(f_data) except Exception, e: self.log.exception("Adding registration fields failed: %s",...
# IFilterStrategy methods def is_external(self): return False def test(self, req, author, content, ip): if req.path_info == '/register': karma = 0 checks = [] for check in self.listeners: try: if check.__class__.__name__ ...
jonathanslenders/python-prompt-toolkit
prompt_toolkit/output/base.py
Python
bsd-3-clause
7,955
0
""" Interface for an output. """ from abc import ABCMeta, abstractmethod from typing import Optional, TextIO from prompt_toolkit.data_structures import Size from prompt_toolkit.styles import Attrs from .color_depth import ColorDepth __all__ = [ "Output", "DummyOutput", ] class Output(metaclass=ABCMeta): ...
one: pass def quit_alternate_screen(self) -> None: pass def enable_mouse_support(self) -> None: pass def disable_mouse_support(self) -> None: pass def erase_end_of_line(self) -> None: pass def erase_down(self) -> None: pass def reset_attribut...
ss def enable_autowrap(self) -> None: pass def cursor_goto(self, row: int = 0, column: int = 0) -> None: pass def cursor_up(self, amount: int) -> None: pass def cursor_down(self, amount: int) -> None: pass def cursor_forward(self, amount: int) -> None: pa...
lmazuel/azure-sdk-for-python
azure-mgmt-resource/azure/mgmt/resource/resources/v2016_09_01/models/identity.py
Python
mit
1,517
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:param type: The identity type. Possible values include: 'SystemAssigned' :type type: str or ~a
zure.mgmt.resource.resources.v2016_09_01.models.ResourceIdentityType """ _validation = { 'principal_id': {'readonly': True}, 'tenant_id': {'readonly': True}, } _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'ty...
skosukhin/spack
var/spack/repos/builtin/packages/scons/package.py
Python
lgpl-2.1
1,645
0.000608
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
t under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 PURPO...
e for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spa...
openstack/vitrage
vitrage/tests/unit/datasources/prometheus/test_prometheus_transformer.py
Python
apache-2.0
6,042
0
# Copyright 2018 - Nokia # # 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, sof...
for_instance, instance_entity_uuid, instance_id) # Validate the expected action on the graph - update or delete self._validate_graph_action(wrapper_for_host) self._validate_graph_action(wrapper_for_instance)
def _validate_vertex_props(self, vertex, event): self._validate_alarm_vertex_props( vertex, get_label(event, PLabels.ALERT_NAME), PROMETHEUS_DATASOURCE, event[DSProps.SAMPLE_DATE]) def _generate_event_on_host(self, hostname): # fake query result to be used by the transfo...
wederw/bitcoin
qa/rpc-tests/mempool_coinbase_spends.py
Python
mit
3,823
0.004708
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test re-org scenarios with a mempool that contains transactions # that spend (directly or indirectly) coin...
for node in self.nodes: node.invalida
teblock(new_blocks[0]) self.sync_all() # mempool should be empty. assert_equal(set(self.nodes[0].getrawmempool()), set()) if __name__ == '__main__': MempoolCoinbaseTest().main()
brousch/opencraft
instance/models/server.py
Python
agpl-3.0
9,912
0.001917
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015 OpenCraft <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Soft...
ss ServerQuerySet(models.QuerySet): """ Additional methods for server querysets Also used as the standard manager for the Server model (`Server.objects`) """ def terminate(self, *args, **kwargs): """ Terminate the servers from the queryset """ qs = self.filter(~Q(stat...
ate() return qs def exclude_terminated(self): """ Filter out terminated servers from the queryset """ return self.filter(~Q(status=Server.TERMINATED)) class Server(ValidateModelMixin, TimeStampedModel, LoggerMixin): """ A single server VM """ NEW = 'new' ...
JHUISI/charm
charm/core/engine/protocol.py
Python
lgpl-3.0
10,994
0.011825
# TODO: provide a transition checker that prevents a feedback loop, inconsistent state. # in user db that way user can eliminate store step on the receive side. from charm.core.engine.util import * from charm.toolbox.enum import Enum from math import log, ceil debug = False # standardize responses between client and ...
0 error = error_states # dictionary of party types (each type gets an identifier) self.partyTypes = {} self.party = {} self._serialize = False self.db = {} # initialize the database self.max_size = max_size self.prefix_size = ceil(log(max_size, 256))
def setup(self, *args): # handles the hookup between parties involved Error = True for arg in args: if isinstance(arg, dict): print("Setup of: ", arg['name']) if not self.addInstance(arg): Error = False else: print(ty...
svimanet/IRC-Bob
modules/reminders.py
Python
unlicense
1,220
0.005738
import time import json import os # Returns the list of reminders as dict. # @return reminders - Python Dictionary def get_reminders(): file = "{}/reminders.json".format(os.path.dirname(os.path.realpath(__file__))) with open(file, "r") as data_file: reminders = json.load(data_file) return reminders...
reminders.keys(): reminders[nick].append([msg, date, time]) with open(file, "w+") as data_file: data_file.write(json.dumps(remind
ers, indent=4, sort_keys=True)) else: reminders[nick] = [[msg, date, time]] with open(file, "w+") as data_file: data_file.write(json.dumps(reminders, indent=4, sort_keys=True)) #print("After\n{}\n".format(reminders)) # Iterates over reminders and sends PM to users if time and date....
criteo-forks/graphite-web
webapp/graphite/user_util.py
Python
apache-2.0
1,975
0
"""Copyright 2008 Orbitz WorldWide 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...
uthenticates # this avoids creating a default (expensive!) passw
ord hash at every # default_profile() call. user, created = User.objects.get_or_create( username='default', defaults={'email': '[email protected]', 'password': '!'}) if created: log.info("Default user didn't exist, created it") profile, c...
wcmckee/wcmckee-notebook
webData.py
Python
gpl-2.0
3,474
0.006621
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <headingcell level=1> # Intercity Python API Development # <codecell> from bs4 import BeautifulSoup import requests import pickle loadSite = requests.get('http://www.intercity.co.nz/') siteData = loadSite.content blehData = siteData.split() blehData[0:20] siteD...
savefilz.write(values) saveFilz.close() # <codecell> print linkZite # <codecell> print omgSite.unwrap # <codecell> omgSite.encode # <codecell> savzSite = omgSite.find_all(id=True) # <codecell> sortSite = linkSite[0:30] # <codecell> print daSite.next_element # <codecell> daSite = sortSite[15] # <...
) saveLinkz.write(siteData) saveLinkz.close() # <codecell> openLinkz = open('htmldoc', 'r') openLinkz.read() # <codecell> print omgSite.extract() # <codecell> print omgSite.setup # <codecell> print omgSite.title # <codecell> print omgSite.wrap # <codecell> print omgSite.body # <codecell> print omgSite.hea...
dg7541/MicrolensingLCOGT
LIA/training_set.py
Python
gpl-3.0
12,474
0.00978
# -*- coding: utf-8 -*- """ Created on Thu Jun 28 20:30:11 2018 @author: danielgodinez """ import numpy as np import random from astropy.io import fits from sklearn import decomposition import os from LIA import simulate from LIA import noise_models from LIA import quality_check from LIA import extract_features ...
sian_noise(mag,zp=max_mag+3) except ValueError: continue source_class = ['CV']*len(time) source_class_list.append(source_class) id_num = [2*n_class+k]*len(time) id_list.append(id_num) ...
ract_features.extract_all(mag,magerr,convert=True) stats = [i for i in stats] stats = ['CV'] + [2*n_class+k] + stats stats_list.append(stats) break if j == 9999: raise RuntimeError('Unable to simulate proper CV in 10k tries with...
potash/scikit-learn
sklearn/gaussian_process/gaussian_process.py
Python
bsd-3-clause
35,041
0.000114
# -*- coding: utf-8 -*- # Author: Vincent Dubourg <[email protected]> # (mostly translation, see implementation details) # License: BSD 3 clause from __future__ import print_function import numpy as np from scipy import linalg, optimize from ..base import BaseEstimator, RegressorMixin from ..metrics...
, optional An array with shape (n_features, ) or (1, ).
The parameters in the autocorrelation model. If thetaL and thetaU are also specified, theta0 is considered as the starting point for the maximum likelihood estimation of the best set of parameters. Default assumes isotropic autocorrelation model with theta0 = 1e-1. thetaL : doubl...
ProgVal/pydigmips
tests/test_loaders.py
Python
mit
1,378
0.006531
from unittest import TestCase from pydigmips import instructions, loaders class HexaLoaderTestCase(TestCase): def testAdd(self): i = ['1510', # 000 101 010 001 0000 '1C60', '2C60'] # 001 011 000 110 0000 o = [instructions.Add(5, 2, 1), instructions.Add(7, 0, 6), ...
hexa(i) self.assertEqual(prog, o) def testBle(self): i = ['8EAA'] # 100 011 101 0101010 o = [instructions.Ble(3, 5, 42)] prog = loaders.load_hexa(i) self.assertEqual(prog, o) def testLdi(self): i = ['B0AA'] # 101 100 00 10101010 o = [instructions.Ldi(4, ...
Ja(self): i = ['CE80'] # 110 011 101 0000000 o = [instructions.Ja(3, 5)] prog = loaders.load_hexa(i) self.assertEqual(prog, o) def testJ(self): i = ['EAAA'] # 111 0101010101010 o = [instructions.J(2730)] prog = loaders.load_hexa(i) self.assertEqual(pr...
duane-edgington/stoqs
stoqs/loaders/MolecularEcology/load_dorado2009.py
Python
gpl-3.0
4,550
0.006813
#!/usr/bin/env python ''' Loader for all 2009 Dorado missions written for Monique's notice of bad depths in Dorado389_2009_084_02_084_02_decim.nc. Mike McCann MBARI 15 January 2013 @var __date__: Date of last svn commit @undocumented: __doc__ parser @status: production @license: GPL ''' import os import sys import d...
rate', 'bbp420', 'bbp700', 'fl700_uncorr', 'salinity', 'biolume', 'sepCountList', 'mepCountList', 'roll', 'pitch', 'yaw'] # Mooring M1ts cl.m1ts_base = 'http://elvis.shore.mbari.org/thredds/dodsC/agg/' cl.m1ts_files = ['OS_MBARI-M1_R_TS'] cl.m1ts_parms = [ '...
e.datetime(2009, 12, 31) # Mooring M1met cl.m1met_base = 'http://elvis.shore.mbari.org/thredds/dodsC/agg/' cl.m1met_files = ['OS_MBARI-M1_R_M'] cl.m1met_parms = [ 'WSPD', 'WDIR', 'ATMP', 'SW', 'RELH' ] cl.m1met_startDatetime = datetime.datetime(2009, 1, 1) cl.m1met_endDatetime = datetime.datetime(2009, 12, 31) # Exe...
rajalokan/nova
nova/policies/console_output.py
Python
apache-2.0
1,106
0
# Copyright 2016 Cloudbase Solutions Srl # 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 r...
nd limitations # under the License. from nova.pol
icies import base BASE_POLICY_NAME = 'os_compute_api:os-console-output' console_output_policies = [ base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, 'Show console output for a server', [ { 'method': 'POST', 'path': ...
hack4sec/ws-cli
classes/jobs/FormBruterJob.py
Python
mit
479
0.006263
# -*- co
ding: utf-8 -*- """ This is part of WebScout software Docs EN: http://hack4sec.pro/wiki/index.php/WebScout_en Docs RU: http://hack4sec.pro/wiki/index.php/WebScout License: MIT Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en) Job class for FormBruter module """ from classes.jobs....
'
petemoore/funsize
funsize/balrog.py
Python
mpl-2.0
2,557
0
import os import requests import logging import json import redo log = logging.getLogger(__name__) PLATFORM_MAP = json.load(open( os.path.join(os.path.dirname(__file__), 'data', 'platform_map.json'))) def _retry_on_http_errors(url, auth, verify, params, errors): for _ in redo.retrier(sleeptime=5, max_sleept...
}".format(self.api_root, release,
update_platform, locale) log.info("Connecting to %s", url) req = _retry_on_http_errors( url=url, auth=self.auth, verify=self.verify, params=None, errors=[500]) return req.json()
h4ck3rm1k3/FEC-Field-Documentation
fec/version/v8_0/F9.py
Python
unlicense
2,852
0.000701
import fechbase class Records(fechbase.RecordsBase): def __init__(self): fechbase.RecordsBase.__init__(self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FILER COMMITTEE ID NUMBER', 'number': '2'}, {'name': 'ENTITY TYPE', 'number': '3'}, ...
': '12'}, {'name': 'CITY', 'number': '13'}, {'name': 'STATE', 'number': '14'}, {'name': 'ZIP', 'number': '15'}, {'name': 'INDIVIDUAL EMPLOYER', 'number': '16'}, {'name': 'INDIVIDUAL OCCUPATION', 'number': '17'}, {'name': 'COVERAGE FROM DATE', 'numb...
ATE', 'number': '19'}, {'name': 'DATE OF PUBLIC DISTRIBUTION', 'number': '20'}, {'name': 'COMMUNICATION TITLE', 'number': '21'}, {'name': 'FILER CODE', 'number': '22'}, {'name': 'FILER CODE DESCRIPTION', 'number': '23'}, {'name': 'SEGREGATED BANK ACCOUNT', 'nu...
dsgouda/autorest
Samples/2a-validation/Python/storage/storage_management_client.py
Python
mit
3,693
0.000542
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # --------------------------------------------------------------------------...
d: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. :type subscription_id: str :param str base_url: Service URL """ def __init__( self, credentials, subscription_id, base_url=None)...
lf.config.credentials, self.config) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self.api_version = '2015-06-15' self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self.storage_accounts = StorageAccou...
Metaswitch/calico-nova
nova/tests/unit/test_linuxscsi.py
Python
apache-2.0
5,951
0
# Copyright 2010 OpenStack Foundation # (c) Copyright 2012-2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www...
evice('/dev/sdd') LOG.error("info = %s" % info) self.assertEqual("/dev/mapper/36005076303ffc48e0000000000000101", info["device"]) self.assertEqual("/dev/sdd", info['devices'][0]['device']) self.assertEqual("6", info['devices'][0]['host']) self.assertEqual...
"/dev/sdc", info['devices'][1]['device']) self.assertEqual("6", info['devices'][1]['host']) self.assertEqual("1", info['devices'][1]['channel']) self.assertEqual("0", info['devices'][1]['id']) self.assertEqual("3", info['devices'][1]['lun'])
Kirubaharan/hydrology
ch_591/ch_591_stage_area.py
Python
gpl-3.0
18,373
0.003973
__author__ = 'kiruba' import pandas as pd import matplotlib.pyplot as plt import mpld3 as m from mpl_toolkits.mplot3d import axes3d, Axes3D from matplotlib import rc from scipy.interpolate import griddata import numpy as np from matplotlib import cm from matplotlib.path import * from matplotlib.collections import PolyC...
# This could be adapted to set your features to desired visibility, # e.g. storing the previous values and restoring the values self.set_some_features_visibility(True) zaxis = self.zaxis draw_grid_old = zaxis.axes._draw_grid # disable draw grid zaxis.axes._draw_gri...
mp_planes = zaxis._PLANES if 'l' in self.sides_to_draw : # draw zaxis on the left side zaxis._PLANES = (tmp_planes[2], tmp_planes[3], tmp_planes[0], tmp_planes[1], tmp_planes[4], tmp_planes[5]) zaxis.draw(renderer) ...
turdusmerula/kipartman
kipartman/swagger_client/models/part.py
Python
gpl-3.0
13,785
0.001378
# coding: utf-8 """ Kipartman Kipartman api specification
s OpenAPI spec version: 1.0.0 Contact: -- Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pf
ormat from six import iteritems import re class Part(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is a...
LLNL/spack
var/spack/repos/builtin/packages/xdotool/package.py
Python
lgpl-2.1
1,385
0.004332
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Xdotool(MakefilePackage): """fake keyboard/mouse input, window management, and more""" ...
ol-3.20160805.1.tar.gz" version('3.20160805.1', sha256='35be5ff6edf0c620a0e16f09ea5e101d5173280161772fca18657d83f20fcca8') version('3.20160804.2', sha256='2251671c3c3dadab2b70e08bd87f2de6338c7
b4e64e7e2d2d881fd13f9bff72c') version('3.20160804.1', sha256='7a76ee57515cc767a00a768f1d04c703279d734255a34f8027c29178561fdce9') version('3.20150503.1', sha256='e8326883bd5e91bede7336cbee186e6e9143f40b3fb61c84afc9bb31b87e96d1') depends_on('libxext') depends_on('libxtst') depends_on('libxi') dep...
vivekhaldar/fetch_rss
output_prn.py
Python
gpl-3.0
928
0.001078
# Copyright (C) 2012 Vivek Haldar # # Take in a dict containing fetched RSS data, and output to printable files in # the
current directory. # # Dict looks like: # feed_title -> [list of articles] # each article has (title, body). # # Author: Vivek Haldar <[email protected]> import codecs import escpos from datetime import datetime import textwrap import output class OutputPrn(output.Output): def output(self): articles = s...
for a in articles[f]: title, body = a # Cut body down to 100 words. short_body = ' '.join(body.split()[:100]) prn.bigtext(f + '\n') prn.bigtext(textwrap.fill(title, 32) + '\n') prn.text(textwrap.fill(body, 32)) ...
pku9104038/edx-platform
common/lib/xmodule/setup.py
Python
agpl-3.0
3,169
0.000947
from setuptools import setup, find_packages XMODULES = [ "abtest = xmodule.abtest_module:ABTestDescriptor", "book = xmodule.backcompat_module:TranslateCustomTagDescriptor", "chapter = xmodule.seq_module:SequenceDescriptor", "combinedopenended = xmodule.combined_open_ended_module:CombinedOpenEndedDescri...
scriptor", "error = xmodule.error_module:ErrorDescriptor", "peergrading = xmodule.peer_grading_module:PeerGradingDescriptor", "poll_question = xmodule.poll_module:PollDescriptor", "problem = xmodule.capa_module:CapaDescriptor", "problemset = xmodule.seq_module:SequenceDescriptor", "randomize = x...
odule.seq_module:SequenceDescriptor", "slides = xmodule.backcompat_module:TranslateCustomTagDescriptor", "vertical = xmodule.vertical_module:VerticalDescriptor", "video = xmodule.video_module:VideoDescriptor", "videoalpha = xmodule.video_module:VideoDescriptor", "videodev = xmodule.backcompat_module...
pawciobiel/fgpst-gae
fgpst/utils/pubsub.py
Python
gpl-3.0
1,412
0.000708
import logging from google.appengine.api import channel from . import memc log = logging.getLogger(__name__) PUBSUB_PREFIX = 'pubsub' def _build_group_key(channel_id): return "%s:%s" % (PUBSUB_PREFIX, channel_id) def add_client(channel_id, client_id, time=channel.MAXIMUM_TOKEN_DURATION_MINUTES * 60): g...
token: log.debug("opening channel") token = channel.create_channel(client_id) memc.add_to_group(group_key, client_id, token, time=time) return token def get_all_clients(channel_id): """ @param channel_
id: @return: set({'client-id': 'token'}, ...) """ group_key = _build_group_key(channel_id) log.debug("get_all_clients group_key=%s", group_key) return memc.get_all_from_group(group_key).items() def remove_client_from_channel(channel_id, client_id): return memc.remove_from_group(channel_id, cli...
LeanVel/TakeoutsTimelining
SearchesParser.py
Python
gpl-3.0
857
0.014002
import json import time def parseSearches(searchesFile, begintimeframe = 0, en
dtimeframe = int(time.time())) : searches = json.load(open(searchesFile, 'r')) listOfsearches = [] for search in searches["event"]:
#a query can contain several timestap so special measurments need te be implemented in order to handle it for timeStampDic in search["query"]['id'] : timeStamp = int(timeStampDic["timestamp_usec"]) // 1000000 # time filtering if timeStamp < endtimeframe and timeStamp > b...
karllessard/tensorflow
tensorflow/python/data/kernel_tests/window_test.py
Python
apache-2.0
10,592
0.005004
# Copyright 2018 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...
expected_output = [] num_batches =
(10 - 5) // 3 + 1 for i in range(num_batches): expected_indices = [] expected_values = [] for j in range(5): for k in range(i * 3 + j): expected_indices.append([j, k]) expected_values.append(i * 3 + j) expected_output.append( sparse_tensor.SparseTensorVa...
eufarn7sp/egads-eufar
egads/algorithms/transforms/__init__.py
Python
bsd-3-clause
547
0.003656
""" EGADS transforms algorithms. See EGADS Algorithm Documentation for more info. """ __author__ = "mfreer, ohenry" __date__ = "2017-01-08 11
:42" __version__ = "1.2" import logging try: from interpolation_linear import * from isotime_to_elements import * from isotime_to_seconds import * from seconds_to_isotime import * from time_to_decimal
_year import * logging.info('egads [transforms] algorithms have been loaded') except Exception: logging.error('an error occured during the loading of a [transforms] algorithm')
IllusionRom-deprecated/android_platform_tools_idea
python/testData/quickFixes/AddFieldQuickFixTest/addFieldFromMethod_after.py
Python
apache-2.0
97
0.020619
class
A: def __init__(self): self.x = 1 self.y = None def foo(self
): a = self.y
jncormier24/Templ
templ/parser.py
Python
gpl-3.0
4,028
0.0072
#!/usr/bin/env python3 # This file is a part of Templ # Copyright (C) 2012 Zachary Dziura # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
f node_name in self.nodes: del self.nodes[node.name] else: raise NodeNotFoundError(node_name) def remove_nodes(self, node_name): """Remove all nodes of a given
name from the tree. If no nodes exist in the tree, return a NodeNotFoundError. Parameters: Node_Name - The name of the notes to be removed from the tree. """ class Node: """Element found within parser syntax tree. Nodes encapsulate 3 values: a...
kailIII/emaresa
trunk.pe/report_aeroo_sample/report/parser.py
Python
agpl-3.0
1,951
0.003075
############################################################################## # # Copyright (c) 2008-2011 Alistek Ltd (http://www.alistek.com) All Rights Reserved. # General contacts <[email protected]> # # WARNING: This program as such is intended to be used by professional # programmers who take th...
to the Free Software # Foundation, Inc., 59 Tem
ple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from report import report_sxw from report.report_sxw import rml_parse import lorem import random class Parser(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): ...
mshcruz/LearnPythonTheHardWay
ex40.py
Python
gpl-2.0
484
0.002066
class Song(object): def __init_
_(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right here"]) bulls_on_parade = Song(["T
hey rally around tha family", "With pockets full of shells"]) happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song()
qpfiffer/blackdog
home/migrations/0006_textpointofinterest.py
Python
gpl-2.0
745
0.002685
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-10-14 01:45 from __future__ import unicode_literals f
rom django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0005_instagrampointofinterest_cached_response'), ] operations = [ migrations.CreateModel( name='TextPointOfInterest',
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.TextField()), ('poi', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='home.PointOfInterest')), ], ), ...
fsxfreak/esys-pbi
src/pupil/pupil_src/player/vis_eye_video_overlay.py
Python
mit
12,941
0.017232
''' (*)~--------------------------------------------------------------------------- Pupil - eye tracking platform Copyright (C) 2012-2017 Pupil Labs Distributed under the terms of the GNU Lesser General Public License (LGPL v3.0). See COPYING and COPYING.LESSER for license details. -----------------------------------...
append(self.eye_cap[-1].get_frame()) try: eye_timestamps = list(np.load(ts)) except: pass else: self.eye_world_frame_map.append(correlate_eye_world(eye_timestamps,g_pool.timestamps)) if len(self.eye_cap) == 2: logge...
logger.error("Could not load eye video.") self.alive = False return def unset_alive(self): self.alive = False def init_gui(self): # initialize the menu self.menu = ui.Scrolling_Menu('Eye Video Overlay') self.update_gui() self.g_pool.gui...
asterisk/pjproject
tests/pjsua/scripts-sipp/uac-srtp-sdes-reinv-dtls.py
Python
gpl-2.0
258
0.01938
# $Id$ # import inc_const a
s const PJSUA = ["--null-audio --max-calls=1 --auto-answer=200 --no-tcp --srtp-secure 0 --use-srtp 2 --srtp-keying=0"] PJSUA_EXPECTS = [[0, "SR
TP uses keying method SDES", ""], [0, "SRTP uses keying method DTLS-SRTP", ""] ]
liosha2007/temporary-groupdocs-python3-sdk
groupdocs/models/UpdateQuestionnaireExecutionResult.py
Python
apache-2.0
944
0.006356
#!/usr/bin/env python """ Copyright 2012 GroupDocs. 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 License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License...
GCC15/tcp-chatroom
server/python/core/threads.py
Python
gpl-2.0
5,338
0.000187
"""Threads to be used by the SCRP server""" # Copyright (C) 2015 Zhang NS, Zifan Li, Zichao Li # # 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 o...
Bad request raise BadRequestError except ScrpError as e: logger.e(e) logger.d('Thread terminate') def send_response(self, resp: ScrpResponse):
with self.__send_lock: pass def send_push(self, push: ScrpPush): with self.__send_lock: pass class RequestHandlerThread(threading.Thread): """Handle a given request""" def __init__(self, cht: ClientHandlerThread, req: ScrpRequest): super().__init__() ...
wq2012/SpectralCluster
spectralcluster/spectral_clusterer.py
Python
apache-2.0
8,653
0.004969
"""A spectral clusterer class to perform clustering.""" import numpy as np from spectralcluster import constraint from spectralcluster import custom_distance_kmeans from spectralcluster import laplacian from spectralcluster import refinement from spectralcluster import utils RefinementName = refinement.RefinementName...
"""Constructor of the clusterer. Args: min_clusters: minimal number of clusters allowed (only effective if not None) max_clusters: maximal number of clusters allowed (only effective if not None), can be used together with min_clusters to fix the number of clusters refin...
ne object to automatically search p_percentile laplacian_type: a LaplacianType. If None, we do not use a laplacian matrix stop_eigenvalue: when computing the number of clusters using Eigen Gap, we do not look at eigen values smaller than this value row_wise_renorm: if True, perform row-wise re...
williamFalcon/pytorch-lightning
tests/accelerators/ddp_model.py
Python
apache-2.0
2,010
0.000498
# Copyright The PyTorch Lightning team. # # 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 i...
seed_everything(4321) parser = ArgumentParser(add_help=False) parser = Trainer.add_argparse_args(parser) parser.add_argument("--trainer_method", default="fit") parser.add_argument("--tmpdir") parser.add_argument("--workdir") parser.set_defaults(gpus=2) parser.set_defaults(accelerator="...
aModule() model = ClassificationModel() trainer = Trainer.from_argparse_args(args) if args.trainer_method == "fit": trainer.fit(model, datamodule=dm) result = None elif args.trainer_method == "test": result = trainer.test(model, datamodule=dm) elif args.trainer_method == "fi...
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/db/backends/sqlite3/introspection.py
Python
mit
18,775
0.001704
import re from collections import namedtuple import sqlparse from django.db.backends.base.introspection import ( BaseDatabaseIntrospection, FieldInfo as BaseFieldInfo, TableInfo, ) from django.db.models.indexes import Index FieldInfo = namedtuple('FieldInfo', BaseFieldInfo._fields + ('pk',)) field_size_re = re....
index(')')] # Walk through and look for references to other tables. SQLite doesn't # really have enforced references, but since it echoes out the SQL used # to create the table we can look for REFERENCES statements used there. f
or field_desc in results.split(','): field_desc = field_desc.strip() if field_desc.startswith("UNIQUE"): continue m = re.search(r'references (\S*) ?\(["|]?(.*)["|]?\)', field_desc, re.I) if not m: continue table, column = [s.st...
carloderamo/mushroom
mushroom_rl/distributions/gaussian.py
Python
mit
14,862
0.005517
import numpy as np from .distribution import Distribution from scipy.stats import multivariate_normal from scipy.optimize import minimize class GaussianDistribution(Distribution): """ Gaussian distribution with fixed covariance matrix. The parameters vector represents only the mean. """ def __init...
len(self._mu) @staticmethod def _compute_mu_from_lagrangian(weights, theta, mu, eta): weights_sum = np.sum(weights) mu_new = (weights @ theta + eta * mu) / (weights_sum + eta) return mu_new @staticmethod def _kl_constraint(mu, mu_new, sigma, sigma
_new, sigma_inv, sigma_new_inv, logdet_sigma, logdet_sigma_new, n_dims): return 0.5*(np.trace(sigma_new_inv@sigma) - n_dims + logdet_sigma_new - logdet_sigma + (mu_new - mu).T @ sigma_new_inv @ (mu_new - mu)) @staticmethod def _entropy(logdet_sigma, n_dims): c = n_dims * np.log(2*n...
flux3dp/fluxghost
fluxghost/api/stl_slicing_parser.py
Python
agpl-3.0
13,536
0.002512
import subprocess import logging import os, sys, traceback import urllib from fluxclient import check_platform from .misc import BinaryUploadHelper, BinaryHelperMixin, OnTextMessageMixin logger = logging.getLogger("API.SLICING") StlSlicer = None StlSlicerCura = None def get_default_cura(): return os.environ["c...
else: self.send_error('14', info=set_result) def adva
nced_setting(self, params): bad_lines = self.m_stl_slicer.advanced_setting(params) if bad_lines != []: for line_num, err_msg in bad_lines: self.send_error('7', info='line %d: %s' % (line_num, err_msg)) logger.debug('line %d: %s' % (line_num...
andrewyoung1991/django-restframework-stripe
tests/test_customer.py
Python
bsd-2-clause
4,147
0.001929
from unittest import mock import pytest import stripe from model_mommy import mommy from rest_framework.reverse import reverse from restframework_stripe import models from restframework_stripe.test import get_mock_resource @mock.patch("stripe.Customer.save") @mock.patch("stripe.Customer.retrieve") @pytest.mark.dja...
a_retrieve.return_value = get_mock_resource("Customer") l_create.return_value = new_card a_update.return_value = get_mock_resource("Customer", **updated_data) uri = reverse("rf_stripe:customer-detail", kwargs={"pk": customer.pk}) response = api_client.patch(uri, data=data, format="json") cus...
_db() assert response.status_code == 200, response.data assert 0 < models.Card.objects.filter(owner=customer.owner).count() assert customer.source["email"] == data["email"] @pytest.mark.django_db def test_options(customer, api_client): api_client.force_authenticate(customer.owner) uri = reverse("r...
diofeher/django-nfa
django/core/management/commands/compilemessages.py
Python
bsd-3-clause
2,462
0.004468
import os import sys from optparse import make_option from django.core.management.base import BaseCommand from django.core.management.color import no_style try: set except NameError: from sets import Set as set # For Python 2.3 def compile_messages(locale=None): basedirs = (os.path.join('conf', 'local...
his script should be run from th
e Django SVN tree or your project or app tree, or with the settings module specified.") for basedir in basedirs: if locale: basedir = os.path.join(basedir, locale, 'LC_MESSAGES') for dirpath, dirnames, filenames in os.walk(basedir): for f in filenames: if f.e...
gpotter2/scapy
scapy/contrib/isotp/isotp_native_socket.py
Python
gpl-2.0
14,939
0
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Nils Weiss <[email protected]> # This program is published under a GPLv2 license # scapy.contrib.description = ISO-TP (ISO 15765-2) Native Socket Library # scapy.contrib.status = library import ctypes from ctypes....
mtu, tx_dl, tx_flags) # == Must use native not standard types for packing == # struct can_isotp_ll_options { # # __u8 mtu; /* generated & accepted CAN frame type */ # /* __u8 value :
*/ # /* CAN_MTU (16) -> standard CAN 2.0 */ # /* CANFD_MTU (72) -> CAN FD frame */ # # __u8 tx_dl; /* tx link layer data length in bytes */ # /* (configured maximum payload length) *...
MicBrain/Python-algo-Module
setup.py
Python
apache-2.0
2,077
0.029851
############################## ### ALGO MODULE SETUP TOOL ### ############################## from distutils.core import setup setup(name='algo', version='1.0', python_modules=['alg...
contact: [email protected] LICENSE License for Algo Module is distributed under t
he MIT License. --------------------------------------------------------------------------- --------------------------------------------------------------------------- """ )
JudTown17/solutions-geoprocessing-toolbox
capability/test/test_erg_tools/TestUtilities.py
Python
apache-2.0
1,365
0.003663
#------------------------------------------------------------------------------ # Copyright 2013 Esri # 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...
specific language governing permissions and # limitations under the License. #-------------
----------------------------------------------------------------- # TestUtilities.py # Description: Common objects/methods used by test scripts # Requirements: ArcGIS Desktop Standard # ---------------------------------------------------------------------------- import arcpy import os import sys currentPath = os.path...
jthurst3/newspeeches
parser2.py
Python
mit
1,487
0.019502
# parser2.py # parses sentences from the CSV files # J. Hassler Thurston # RocHack Hackathon December 7, 2013 # Modified December 11, 2013 import nltk from random import choice cfg_file = 'upenn_grammar.cfg' tbank_productions = [] nonterminals = [] rightside = [] def get_initial_rules(): global tbank_productions, n...
-get-a-set-of-grammar-rules-from-penn-treebank-using-python-nltk tbank_productions = [production for sent in nltk.corpus.treebank.parsed_sents() for production in sent.productions()] nonterminals = [production.lhs().__str__() for production in tbank_productions] rightside = [production.rhs().__str__() for production...
_productions) print generate_sample(tbank_grammar) # modified from http://stackoverflow.com/questions/15009656/how-to-use-nltk-to-generate-sentences-from-an-induced-grammar def generate_sample(grammar, items=[nltk.grammar.Nonterminal('S')]): frags = [] if len(items) == 1: print items if isinstance(items[0], nlt...
CompassionCH/compassion-switzerland
website_compassion/controllers/cms_form.py
Python
agpl-3.0
1,098
0
############################################################################## # # Copyright (C) 2019-2020 Compassion CH (http://www.compassion.ch) # @author: Christopher Meier <[email protected]> # # The licence is in the file __manifest__.py # ####################################################################...
tes defined automatically by cms_form. """ from odoo import http from odoo.addons.cms_form.controllers.main import ( CMSFormController, CMSWizardFormController, CMSSearchFormController, ) class UwantedCMSFormController(CMSFormController): @http.route() def cms_form(self, model, model_id=None, **k...
(self, wiz_model, model_id=None, **kw): return http.request.render("website.404") class UnwantedCMSSearchFormController(CMSSearchFormController): @http.route() def cms_form(self, model, **kw): return http.request.render("website.404")
Reagankm/KnockKnock
venv/lib/python3.4/site-packages/mpl_toolkits/axes_grid1/axes_grid.py
Python
gpl-2.0
31,905
0.001254
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import matplotlib.cbook as cbook import matplotlib.pyplot as plt import matplotlib.axes as maxes #import matplotlib.colorbar as mcolorbar from . import colorbar as mcolorbar import matplotlib as mp...
| False ] label_mode "L" [ "L" | "1" | "all" ] axes_class None a type object which must be a subclass of :class:`~matplotlib.axes.Axes` ================ ======== ========================================= """ s...
if ngrids is None: ngrids = self._nrows * self._ncols else: if (ngrids > self._nrows * self._ncols) or (ngrids <= 0): raise Exception("") self.ngrids = ngrids self._init_axes_pad(axes_pad) if direction not in ["column", "row"]: ...
fujy/ROS-Project
src/rbx2/rbx2_arm_nav/scripts/moveit_attached_object_demo.py
Python
mit
4,719
0.008264
#!/usr/bin/env python """ moveit_attached_object_demo.py - Version 0.1 2014-01-14 Attach an object to the end-effector and then move the arm to test collision avoidance. Created for the Pi Robot Project: http://www.pirob
ot.org Copyright (c) 2014 Patrick Goebel. All rights reserved. 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 vers...
eful, 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 at: http://www.gnu.org/licenses/gpl.html """ import rospy, sys import thread, copy import moveit_commander from moveit_com...
ccd-utexas/ProEMOnline
layout.py
Python
mit
7,341
0.016347
# -*- coding: utf-8 -*- """ This scripts sets an initial layout for the ProEMOnline software. It uses the PyQtGraph dockarea system and was designed from the dockarea.py example. Contains: Left column: Observing Log Center column: Plots Right column: Images and Process Log Menu bar """ import pyqtgraph as pg from p...
bserver = QtGui.QLabel('Observer') target = QtGui.QLabel('Target') filt = QtGui.QLabel('Filter') log = QtGui.QLabel('Log') observerEdit = QtGui.QLineEdit() targetEdit = QtGui.QLineEdit() filtEdit = QtGui.QComboBox() filtEdit.addItems(["BG40","u'","g'","r'","i'","z'","Other"])
logEdit = QtGui.QTextEdit() w1.addWidget(observer, 1, 0) w1.addWidget(observerEdit, 1, 1) w1.addWidget(target, 2, 0) w1.addWidget(targetEdit, 2, 1) w1.addWidget(filt, 3, 0) w1.addWidget(filtEdit, 3, 1) w1.addWidget(log, 4, 0) w1.addWidget(logEdit, 4, 1, 6, 1) d1.addWidget(w1) ## Process Log w2 = pg.Layou...
hnarayanan/twist
demo/static/twist.py
Python
gpl-3.0
2,606
0.02878
__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition...
materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) ...
ppend(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try...
Zashel/zrest
zrest/__init__.py
Python
apache-2.0
80
0
from . import
statuscodes fr
om .exceptions import * from . import basedatamodel
samdowd/drumm-farm
pages/migrations/0003_auto_20160515_0618.py
Python
mit
2,802
0.002855
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-05-15 06:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0002_auto_20160512_0259'), ] operations = [ migrations.CreateModel(...
members, 'StaffMember'. You probably need Sam's help if you have a new type of thing to list.", max_length=200, verbose_name=
'name of object listed'), ), migrations.AlterField( model_name='page', name='public', field=models.BooleanField(default=True, verbose_name='Visible to Public'), ), migrations.AlterField( model_name='page', name='url', ...
CSIOM/piPi
src/managers/models.py
Python
gpl-3.0
2,864
0.005587
#!/usr/bin/env python """ This file is part of piPi project. Copyright (C) 2015 CSIOM, http://www.csiom.com Authors: The Csiom Team piPi 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 Li...
arField(max_length=200,help_text="Name of status field") make_active_tag = models.BooleanField(default=False, help_text="Mark me if this state makes project active(started/resumed etc)") make_inactive_tag = models.BooleanField(default=False, help_text="Mark
me if this state makes project inactive(completed/cancelled etc)") class Meta: verbose_name_plural = "Status" def __unicode__(self): return self.state class StatusOfProject(models.Model): """Model class to store status of projects.""" project = models.ForeignKey(ProjectDetails) s...
tazle/pik-laskutin
import-flights.py
Python
gpl-2.0
151
0
from pik.flights import Flight import csv import sys reader = csv.reader(s
ys.stdin) for flight in Flight.generate_f
rom_csv(reader): print flight