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
jH0ward/psi4
psi4/driver/molutil.py
Python
lgpl-3.0
10,050
0.000299
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2017 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
right portion of the register val = 1 for k in range(nreal - 1, rank, -1): reals[k] = val val = v
al + 1 # boundary condition is promotion into # [nfrag+1 nfrag-1 ...] if (reals[0] > nfrag): break return clusters def molecule_set_attr(self, name, value): """Function to redefine __setattr__ method of molecule class.""" fxn = object.__getattribute__(...
ekelsen/openai-gemm
benchmark.py
Python
mit
4,622
0.021636
#!/usr/bin/env python import numpy as np import pycuda.driver as drv from neon.backends.nervanagpu import NervanaGPU from openai_gemm import matmul ng = NervanaGPU() print drv.Context.get_current().get_device().name() config = ( # m, n, k, AT, BT (row order) ( 16, 1760, 1760, False, False), ...
lse, True), ( 7000, 4096, 4096, False, True), ( 7133, 1760, 1760, True , False), ( 7133, 2048, 2048, True , False), ( 7133, 2560, 2560, True , False), ( 7133, 4096, 4096, True , False), ( 9124, 5124, 1760, False, False), ( 9124, 5124,
2048, False, False), ( 9124, 5124, 2560, False, False), ( 9124, 5124, 4096, False, False), ( 9124, 5124, 1760, False, True), ( 9124, 5124, 2048, False, True), ( 9124, 5124, 2560, False, True), ( 9124, 5124, 4096, False, True), ( 8457, 35, 1760, False, False), ( 8457, 35, 2048, Fa...
cuauv/software
hydrocode/modules/pinger/headingplot.py
Python
bsd-3-clause
1,604
0.001248
import math import queue import time from common import const, plot class HeadingPlot(plot.PlotBase): def plot(self, hdg, elev): try: self._q.put_nowait((hdg, elev)) except queue.Full: pass @staticmethod def _daemon(q): from matplotlib import transforms ...
ransData) text.set_text( '(Elevation: ' + str(int(math.degrees(elev))) + '°)') pyplot.draw() pyplot.show(block=False) except queue.Empty: pass fig.canvas.flush_events() time.sleep(const.GUI_UPDATE_T...
, 0, '') ax1 = fig.add_subplot(111, polar=True, label='deg') ax1.set_yticklabels([]) ax1.set_theta_zero_location('N') ax1.set_theta_direction(-1) ax1.set_facecolor('None') return (ax0, im, text)
peteristhegreat/ioHub
devices/eyeTrackerInterface/HW/EyeTech/QuickLink/reference/pyQuickLink2.py
Python
gpl-3.0
43,079
0.010399
'''Wrapper for QuickLink2.h Generated with: ctypesgen.py -a -l QuickLink2 -o pyQuickLink2.py QuickLink2.h Do not modify this file. ''' __docformat__ = 'restructuredtext' # Begin preamble import ctypes, os, sys from ctypes import * _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds o...
lf, string): if isinstance(string, UserString): return cmp(self.data, string.data) else: return cmp(self.data, string) def __contains__(self, char): return char in self.data def __len__(self): return len(self.data) def __getitem__(self, index): return self.__...
def __add__(self, other): if isinstance(other, UserString): return self.__class__(self.data + other.data) elif isinstance(other, basestring): return self.__class__(self.data + other) else: return self.__class__(self.data + str(other)) def __radd__(self...
botswana-harvard/bcpp-subject
bcpp_subject/admin/quality_of_life_admin.py
Python
gpl-3.0
1,552
0
from django.contrib import admin from django.utils.safestring import mark_safe from edc_base.modeladmin_mixins import audit_fieldset_tuple from ..admin_site import bcpp_subject_admin from ..forms import QualityOfLifeForm from ..models import QualityOfLife from .modeladmin_mixins import CrfModelAdminMixin @admin.reg...
nxiety': admin.VERTICAL, } additional_
instructions = mark_safe( '<h5>Note to Interviewer</h5>' 'In this section, read the heading ' '(question) and then each of the 5 possible responses for each ' 'question. Do not read -Do not want to answer-, but record ' 'this if respondent declines to answer.' '<H5><span ...
blackPantherOS/packagemanagement
smartpm/smart/interfaces/qt4/command.py
Python
apache-2.0
3,225
0.004031
#-*- coding: utf-8 -*- # # Copyright (c) 2004 Conectiva, Inc. # # Written by Gustavo Niemeyer <niemeyer@conectiva.com> # # This file is part of Smart Package Manager. # # Smart Package Manager is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # b...
class QtCommandInterface(QtInterface): def __init__(self, ctrl, argv=None): QtInterface.__init__(self, ctrl, argv) self._status = QtStatus() def showStatus(self, msg): self._status.show(msg) while QtCore.QEventLoop().isRunning(): QtGui.QCoreApplication.eventLoop().p...
p.AllEvents) def hideStatus(self): self._status.hide() while QtCore.QEventLoop().isRunning(): QtGui.QCoreApplication.eventLoop().processEvents(QtGui.QEventLoop.AllEvents) def run(self, command=None, argv=None): result = QtInterface.run(self, command, argv) s...
kennedyshead/home-assistant
homeassistant/components/rainforest_eagle/sensor.py
Python
apache-2.0
5,614
0.000713
"""Support for the Rainforest Eagle-200 energy monitor.""" from datetime import timedelta import logging from eagle200_reader import EagleReader from requests.exceptions import ConnectionError as ConnectError, HTTPError, Timeout from uEagle import Eagle as LegacyReader import voluptuous as vol from homea
ssistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( CONF_IP_ADDRESS, DEVICE_CLASS_POWER, ENERGY_KILO_WAT
T_HOUR, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle CONF_CLOUD_ID = "cloud_id" CONF_INSTALL_CODE = "install_code" POWER_KILO_WATT = "kW" _LOGGER = logging.getLogger(__name__) MIN_SCAN_INTERVAL = timedelta(seconds=30) SENSORS = { "instantanous_demand": ("Eagle-2...
micumatei/asciipic
asciipic/api/api_endpoint/user/token.py
Python
mit
2,206
0
"""User EndPoint for AsciiPic.""" import cherrypy from cherrypy import tools from oslo_log import log as logging from asciipic.api import base as base_api from asciipic.db.managers import user from asciipic.common import exception USERS = user.Users LOG = logging.getLogger(__name__) class TokenEndpoint(base_api.Ba...
r
eturn response
pwnieexpress/raspberry_pwn
src/pentest/sqlmap/tamper/concat2concatws.py
Python
gpl-3.0
766
0.003916
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs): """ Replaces instances like 'CONCAT(...
, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL Tested against: * MySQL 5.0 Notes: * Use
ful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(1,2)') 'CONCAT_WS(MID(CHAR(0),0,0),1,2)' """ if payload: payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),") return payload
rcgee/oq-hazardlib
openquake/hazardlib/calc/gmf.py
Python
agpl-3.0
11,435
0
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2012-2016 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 Licen...
:param truncation_level: Float, number of standard deviations for truncation of the intensity distribution, or ``None``. :param correlation_model: Instance of correlation model object. See :mod:`openquake.hazardlib.correlation`. Can be ``None``, in which case non-correla...
rrelation model is not used if ``truncation_level`` is zero. """ # The GmfComputer is called from the OpenQuake Engine. In that case # the rupture is an higher level containing a # :class:`openquake.hazardlib.source.rupture.Rupture` instance as an # attribute. Then the `.compute(gsim, num_events)` m...
okfn/ofs
ofs/__init__.py
Python
mit
107
0
'''OFS. See README.rst
.''' from . import base from .base import OFSException from .fa
ctory import get_impl
oVirt/vdsm
tests/virt/__init__.py
Python
gpl-2.0
887
0
# # Copyright 2017 Red Hat, Inc. # # This program is free software; you can redistribute
it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it wi
ll 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 Softwar...
XianliangJ/collections
ShrewAttack/util/plot_queue.py
Python
gpl-3.0
3,877
0.006706
''' Plot queue occupancy over time ''' from helper import * import plot_defaults parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', help="Queue timeseries output to one plot", required=True, action="store", nargs='+',...
bps on y-axis..", type=int, default=0, action="store", dest="miny") parser.add_argument('--legend', '-l',
help="Legend to use if there are multiple plots. File names used as default.", action="store", nargs="+", default=None, dest="legend") parser.add_argument('--out', '-o', help="Output png file for the plot."...
GoliathLeviathan/SoulCreator
src/Tools/ImageTools.py
Python
gpl-3.0
1,059
0.011418
# -*- coding: utf-8 -*- """ # Copyright Copyright (C) 2012 by Victor victor@caern.de # License This file is part of SoulCreator. SoulCreator 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...
elif gender.lower() == "male" or gender.lower() == "m": return "♂" else:
return "⚥"
statsmodels/statsmodels
statsmodels/graphics/gofplots.py
Python
bsd-3-clause
35,607
0.000056
from statsmodels.compat.python import lzip import numpy as np from scipy import stats from statsmodels.distributions import ECDF from statsmodels.regression.linear_model import OLS from statsmodels.tools.decorators import cache_readonly from statsmodels.tools.tools import add_constant from . import utils __all__ = ...
"Frozen distributions cannot be combined with fit, loc, scale" " or distargs." ) # propertes self._cache = {} if self
._is_frozen: self.dist = dist dist_gen = dist.dist shapes = dist_gen.shapes if shapes is not None: shape_args = tuple(map(str.strip, shapes.split(","))) else: shape_args = () numargs = len(shape_args) arg...
leviroth/praw
praw/models/listing/mixins/rising.py
Python
bsd-2-clause
961
0
"""Provide the RisingListingMixin class.""" from urllib.parse import urljoin from ...base import PRAWBase from ..generator import ListingGenerator class RisingListingMixin(PRAWBase): """Mi
xes in the rising methods.""" def random_rising(self, **generator_kwargs): """Return a ListingGenerator for random rising submissions. Additional keyword arguments are passed in the initialization of :class:`.ListingGenerator`. """ return ListingGenerator( self...
rgs ) def rising(self, **generator_kwargs): """Return a ListingGenerator for rising submissions. Additional keyword arguments are passed in the initialization of :class:`.ListingGenerator`. """ return ListingGenerator( self._reddit, urljoin(self._path, ...
litnimax/addons-yelizariev
mail_partner_lang/__openerp__.py
Python
lgpl-3.0
248
0.028226
{ 'name' : 'Use partner language in mail', 'version' : '1.0.0', 'author' : 'Ivan Yelizariev', 'category' : 'Mail', 'website' : 'https:/
/yelizariev.github.io', 'depends' : ['mail'], 'data':[], 'inst
allable': True, }
Chitrank-Dixit/werkzeug
werkzeug/exceptions.py
Python
bsd-3-clause
18,531
0.000863
# -*- coding: utf-8 -*- """ werkzeug.exceptions ~~~~~~~~~~~~~~~~~~~ This module implements a number of Python exceptions you can raise from within your views to trigger a standard non-200 response. Usage Example ------------- :: from werkzeug.wrappers import BaseRequest ...
ion): """*404* `Not Found` Raise if a resource does not exist and n
ever existed. """ code = 404 description = ( '<p>The requested URL was not found on the server.</p>' '<p>If you entered the URL manually please check your spelling and ' 'try again.</p>' ) class MethodNotAllowed(HTTPException): """*405* `Method Not Allowed` Raise if th...
r41d/flaming-octo-geezus
src/sprites.py
Python
gpl-3.0
1,802
0.027192
#!/usr/bin/env python # -*- coding: utf-8 *-* import pygame from const import * class MultiSprite(object): def __init__(self, path, res_x, res_y=None, offX=0, offY=0, gX=0, gY=0): """path = file path of the Multi sprite. res_x and res_y are the X, Y size of each sub sprite. offX and offY can specify an ...
SetMultiSprite, self).__init__(path, res_x, res_y) class CharSetMultiSprite(MultiSprite): def __init__(self,
path, res_x, res_y=None, offX=0, offY=0, gX=0, gY=0): super(CharSetMultiSprite, self).__init__(path, res_x, res_y, offX, offY, gX, gY)
nVentiveUX/mystartupmanager
mystartupmanager/showcase/apps.py
Python
mit
1,233
0
# Copyright (c) 2016 nVentiveUX # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distri...
NESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
. """Application configuration""" from django.apps import AppConfig class ShowcaseConfig(AppConfig): name = 'mystartupmanager.showcase'
CodethinkLabs/firehose
debian/foo/debfile.py
Python
gpl-2.0
11,901
0.001597
# DebFile: a Python representation of Debian .deb binary packages. # Copyright (C) 2007-2008 Stefano Zacchiroli <zack@debian.org> # Copyright (C) 2007 Filippo Giunchedi <filippo@debian.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publi...
in the md5sums member of control.tar.gz, usually file names relative to the file system root (without heading '/' or './'). The returned keys are Unicode objects if an encoding is specified, otherwise binary. The returned values are always Unicode.""" if not self.has_file(MD5_FI...
encoding=encoding, errors=errors) sums = {} if encoding is None: newline = b'\r\n' else: newline = '\r\n' for line in md5_file.readlines(): # we need to support spaces in filenames, .split() is not enough md5, fname = line.rstrip(newline).s...
tarasane/h2o-3
h2o-py/tests/testdir_misc/pyunit_headers.py
Python
apache-2.0
570
0.017544
import sys sys.path.insert(1, "../../") import h2o, tests def headers(): headers = h2o.import_file(h2o.l
ocate("smalldata/airlines/allyears2k_headers_only.csv")) headers_and = h2o.import_file(h2o.locate("smalldata/airlines/allyears2k.zip")) headers_and.setNames(headers.names) print headers.names print headers_and.names assert headers.names == headers_and.names, "Expected the same column names but got {...
__main__": tests.run_test(sys.argv, headers)
Domatix/account-financial-tools
account_cost_center/models/__init__.py
Python
agpl-3.0
320
0
# -*- coding: utf-8 -*- # Copyright 2015-2017 Onestein (<http://w
ww.onestein.eu>) # License AGP
L-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import account_move_line from . import account_invoice from . import account_invoice_line from . import account_invoice_report from . import account_cost_center
weltliteratur/vossanto
org.py
Python
gpl-3.0
20,210
0.004998
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Process (extract, filter, merge) Vossantos in an org mode file. # # Usage: Without any arguments, extracts all Vossanto canidates from # the given org file. # # Author: rja # # Changes: # 2019-12-18 (rja) # - added field sourceImageLicense # 2019-12-16 (rja) # - added opt...
ttp.+?)? # article URL (\]\[)? # separators for article URL (?P<fid> # full file id (?P<year>\\d{4}) # year /
# separator (?P<month>\\d{2}) # month / # separator (?P<day>\\d{2}) # day / # separator (?P<aid>\\d+) # article id ) # end of full file id (\]\])? # closing markup for article URL ) # end of full art...
lmco/dart
missions/apps.py
Python
apache-2.0
827
0
# -*- coding: utf8 -*- # Copyright 2017 Lockheed Martin Corporation # # 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 o
f 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 la...
ions under the License. # import logging from django.apps import AppConfig from django.conf import settings logger = logging.getLogger(__name__) class MissionsConfig(AppConfig): name = 'missions' verbose_name = 'Missions'
anhstudios/swganh
data/scripts/templates/object/building/player/construction/shared_construction_player_house_tatooine_large_style_01.py
Python
mit
509
0.043222
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMEN
TATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/player/construction/shared_construction_player_house_tatooine_large_style_01.iff" result.attribute_template_id = -1 result.stfName("player_structure","temporary_structure") #### BEGIN M...
aschwaighofer/swift
utils/build_swift/tests/build_swift/test_cache_utils.py
Python
apache-2.0
3,309
0
# This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list o...
count(self): count = self._counter self._counter += 1 return count counter = Counter() self.assert
Equal(counter.count, 0) self.assertEqual(counter.count, 0) # Assert that the count property has been replaced with the constant. self.assertEqual(getattr(counter, 'count'), 0)
vishakh/valkyrie
valkyrie.py
Python
lgpl-3.0
6,166
0.003892
#!/usr/bin/env python2.7 # Uploads Scrypt mining farm status to CouchDB database for detailed logging. # Written by Vishakh. # https://github.com/vishakh/valkyrie # Based on open source code by etkeh <https://github.com/setkeh> import datetime import json import logging import socket import subprocess import sys impo...
hrate = 0.0 total_miners = 0 total_gpus = 0 temperature = None for host, port, name in hosts: try: log.info('Querying %s at %s:%s' % (name, host, port)) currenthost = {} command = 'summary' response = makerpcc...
mmand] = summary command = 'config' response = makerpccall([command], host, port) config = response['CONFIG'] currenthost[command] = config command = 'pools' response = makerpccall([command], host, port) po...
inovtec-solutions/OpenERP
openerp/addons/account_analytic_plans/account_analytic_plans.py
Python
agpl-3.0
24,226
0.008916
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from lxml import
etree from openerp.osv import fields, osv from openerp import tools from openerp.tools.translate import _ class one2many_mod2(fields.one2many): def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None): if context is None: context = {} res = {} for id in...
nimbis/django-shop
shop/urls/rest_api.py
Python
bsd-3-clause
1,168
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url, include from rest_framework import routers from shop.forms.checkout import ShippingAddressForm, BillingAddressForm from shop.views.address import AddressEditView from shop.views.cart import CartViewSet, WatchViewSet from...
uter() # TODO: try with trailing_slash=False router.register(r'cart', CartViewSet, base_name='cart') router.register(r'watch', WatchViewSet, base_name='watch') router.register(r'checkout', CheckoutViewSet, base_name='checkout') urlpatterns = [ url(r'^select_product/?$', ProductSelectView.as_view(), ...
, name='edit-shipping-address'), url(r'^billing_address/(?P<priority>({{\s*\w+\s*}}|\d+|add))$', AddressEditView.as_view(form_class=BillingAddressForm), name='edit-billing-address'), url(r'^', include(router.urls)), ]
Fendoe/open-hackathon-o
open-hackathon-client/src/client/__init__.py
Python
mit
4,490
0.002673
# -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this softw...
n self.__dict__[key] else: return default_value
@staticmethod def from_object(arg): """Convert JSON-like object to Context recursively :returns list of Context if arg is list instance of Context if arg is dict the original arg otherwise """ if isinstance(arg, list): return [Context....
pwollstadt/IDTxl
test/test_idtxl_io.py
Python
gpl-3.0
12,888
0.000078
"""Unit tests for IDTxl I/O functions.""" import os import tempfile import pickle import pytest import numpy as np from pkg_resources import resource_filename from idtxl import idtxl_io as io from idtxl import idtxl_utils as utils from idtxl.data import Data from idtxl.network_comparison import NetworkComparison from i...
e': 'independent', 'n_perm_max_stat': 50, 'n_perm_min_stat': 50, 'n_perm_omnibus': 50, 'n_perm_max_seq': 50, 'alpha_comp': 0.26, 'n_perm_comp': 50, 'tail': 'two', 'permute_in_time': True, 'perm_type': 'random' } comp = NetworkComparison() r...
with unconnected nodes. max_lag = 3 data = Data(seed=SEED) data.generate_mute_data(500, 5) settings = { 'cmi_estimator': 'JidtKraskovCMI', 'noise_level': 0, 'n_perm_max_stat': 21, 'n_perm_min_stat': 21, 'n_perm_max_seq': 21, 'n_perm_omnibus': 21, ...
goal/uwsgi
tests/fileserve_async.py
Python
gpl-2.0
427
0
import sys import mimetypes basedir = sy
s.argv[1] mimetypes.init() def application(environ, start_response): filename = basedir + environ['PATH_INFO'] (content_type, encoding) = mimetypes.guess_type(filename) if not content_type: content_type = 'text/plain' start_response('200 OK', [('Content-Type', content_type)]) fd = open(f...
) yield environ['wsgi.file_wrapper'](fd, 32*1024)
samvartaka/keyak-python
utils.py
Python
mit
1,775
0.024803
# -*- coding: utf-8 -*- # Keyak v2 implementation by Jos Wetzels and Wouter Bokslag # hereby denoted as "the implementer". # Based on Keccak Python and Keyak v2 C++ implementations # by the Keccak, Keyak and Ketje Teams, namely, Guido Bertoni, # Joan Daemen, Michaël Peeters, Gilles Van Assche and Ronny Van Keer # # Fo...
ils/crypto.py # Is constant-time only if both strings are of equal length but given the use-case that is always the case. def constant_time_compare(val1, val2): if len(val1) != len(val2): return False result = 0 for x, y in zip(val
1, val2): result |= ord(x) ^ ord(y) return result == 0
romanofski/programslice
docs/conf.py
Python
gpl-3.0
8,125
0.007142
# -*- coding: utf-8 -*- # # programslice documentation build configuration file, created by # sphinx-quickstart on Fri Jul 27 16:01:51 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
es after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = Fals
e # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, ...
ColumbiaCMB/kid_readout
apps/data_taking_scripts/cooldown/2016-06-09_hpd/sweepstream_r1_on_off.py
Python
bsd-2-clause
5,195
0.00308
""" Measure one resonator per LO frequency. Since each measurement has only one channel, record SingleSweepStreams. """ import time import logging import numpy as np from kid_readout.utils import log from kid_readout.roach import hardware_tools, analog from kid_readout.measurement import acquire, basic from kid_reado...
.file_handler(__file__)) # Parameters magnet
_distance_mm = 220 all_f0_MHz = np.array([2432, 3488, 3629, 3800]) f0_MHz = all_f0_MHz frequency_shift = 1 - 0 f0_MHz *= frequency_shift attenuations = [10, 20, 30, 40, 50, 60] sweep_interval = 32 tone_sample_exponent = 18 sweep_length_seconds = 0.1 stream_length_seconds = 30 lo_round_to_MHz = 2 f_minimum = 10e6 # Kee...
grbot/agd
mamana/templates/TSVtoVCF.py
Python
mit
950
0.015789
#!/usr/bin/env python2.7 import argparse,sys import time as t parser = argparse.ArgumentParser() parser.add_argument("--inTSV", help="") parser.add_argument("--outVCF", help="") args = parser.parse_args() def toVCF(TSV, VCF): ''' :param TSV: :param VCF: :return: ''' out = open(VCF, 'w') f...
if 'CHROM' in line: head = line.strip().split(' ') out.writelines("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n") else: line = line.strip().split('\t')
if len(line) > 1: for i in range(4,len(line)): line[i] = head[i]+'='+line[i] out.writelines('\t'.join([line[0],line[1],'.',line[2],line[3],'.','.',';'.join(line[4:])])+'\n') out.close() toVCF(args.inTSV, args.outVCF)
box/box-python-sdk
boxsdk/object/comment.py
Python
apache-2.0
1,357
0
import json from boxsdk.object.base_object import BaseObject from ..util.api_call_decorator import api_call class Comment(BaseObject): """An object that represents a comment on an item""" _item_type = 'comment' @staticmethod def construct_params_from_message(message: s
tr) -> dict:
message_type = 'tagged_message' if '@[' in message else 'message' return { message_type: message } @api_call def reply(self, message: str) -> 'Comment': """ Add a reply to the comment. :param message: The content of the reply comment. ...
ireapps/coding-for-journalists
4_make_function/completed/call_function_done.py
Python
mit
220
0
# Let's import our Pa
rseMyAddresses function from payday_parser.py from payday_parser_done import ParseMyAddresses # Run the function on the consumer_installment HTML file. ParseMyAddresses('
consumer_installment.html')
ibaidev/gplib
gplib/parameters.py
Python
gpl-3.0
15,692
0
# -*- coding: utf-8 -*- # # Copyright 2018 Ibai Roman # # This file is part of GPlib. # # GPlib 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 ...
rror("Not Implemented. This is an interface.") def save_current_as_optimized(self): """ :return: :rtype: """ raise NotImplementedError("Not Implemented. This is an interface.") def set_params_to_default(self): """ :return: :rtype: """ ...
values(self, trans=False): """ :param trans: :type trans: :return: :rtype: """ raise NotImplementedError("Not Implemented. This is an interface.") def get_current_value(self, trans=False): """ :return: :rtype: """ r...
alonisser/Open-Knesset
simple/constants.py
Python
bsd-3-clause
2,838
0.006321
# -*- coding: utf-8 -* SPECIAL_COMMITTEES_NAMES = [u"הוועדה המשותפת לנושא סביבה ובריאות", ] # some party names appear in the knesset website in several forms. # this dictionary is used to transform them to canonical form. CANONICAL_PARTY_ALIASES = {'עבודה': 'העבודה', 'ליכוד': 'הליכוד', ...
חריות לאומית': 'קדימה', 'יחד (ישראל חברתית דמוקרטית) והבחירה הדמוקרטית': 'מרצ-יחד והבחירה הדמוקרטית', 'יחד והבחירה הדמוקרטית': 'מרצ-יחד והבחירה הדמוקרטית', 'יחד והבחירה הדמוקרטית (מרצ לשעבר)': 'מרצ-יחד והבחירה הדמוקרטית', ...
יחד והבחירה הדמוקרטית', } KNESSET_BASE_LAW_RTF_URL = r"http://www.knesset.gov.il/privatelaw" SECOND_AND_THIRD_READING_LAWS_URL = 'http://www.knesset.gov.il/privatelaw/plaw_display.asp?LawTp=2' PRIVATE_LAWS_URL = r"http://knesset.gov.il/privatelaw/Plaw_display.asp?lawtp=1" KNESSET_LAWS_URL = ...
msegeya/breakout-clone
Game/Bricks/BallSpawningBrick.py
Python
mit
1,231
0.003249
import pygame from Game.Shared import GameConstants from Game.Bricks import Brick from Game.Ball
import Ball class BallSpawningBrick(Brick): def __init__(self, position, game, points=400, color=(150, 150, 150), sprite=pygame.Surface(GameConstants.BRICK_SIZE)): super(BallSpawningBrick, self).__init__(position, game, points=point
s, color=color, sprite=sprite) pygame.font.init() font = pygame.font.Font(None, 16) renderedText = font.render("Extra", True, (0, 0, 0)) textWidth, textHeight = renderedText.get_size() blitX = int(GameConstants.BRICK_SIZE[0] / 2.0) ...
javierdallamore/ioriodb
tools/ioriocli.py
Python
mpl-2.0
8,730
0.003093
#!/usr/bin/env python3 '''ioriodb CLI client to interact with the api from the command line''' from __future__ import print_function import time import json import argparse import iorio def get_arg_parser(): '''build the cli arg parser''' parser = argparse.ArgumentParser(description='Iorio DB CLI') parser...
t from') p_list_buckets.set_defaults(action='list-buckets') p_list_streams.set_defaults(action='list-streams') p_list_streams.add_argument('bucket', help='bucket name') p_listen.set_defaults(action='listen') p_listen.add_
argument('subscriptions', nargs='+', help="subscription descriptiors (bucket:stream or bucket:stream:from)") return parser def parse_args(): '''parse arguments and return them''' parser = get_arg_parser() args = parser.parse_args() return args def parse_data_from_raw(data_raw): '''par...
arcturusannamalai/open-tamil
tamilstemmer/tamil_stemmer.py
Python
mit
131,981
0.003463
# This file automatically generated from the python code generator of # snowball project at https://github.com/shibukawa/snowball by Yoshiki Shibukawa # using the Tamil stemmer description of Damodharan Rajalingam at https://github.com/rdamodharan/tamil-stemmer # # Copyright (c) 2013, Damodharan Rajalingam # # self f...
_2 # [, line 141 self.bra = self.cursor # literal, line 141 if not self.eq_s(2, u"\u0BB5\u0BCB"): raise lab1() # ], line 141 self.ket = self.cursor # <-, line 141 if not se...
b0() except lab1: pass self.cursor = v_1 try: # (, line 142 # and, line 142 v_4 = self.cursor # try, line 142 v_5 = self.cursor try: # literal, line 142 ...
vmalloc/redgreen
redgreen/sleeper.py
Python
bsd-3-clause
960
0.007292
import os import sys import time import itertools def get_sleeper(): if os.isatty(sys.stdout.fileno()): return PrettySleeper() return Sleeper() _PROGRESS_WIDTH = 50 _WATCHING_MES
SAGE = "Watching for changes... " _PROGRESS_BAR = [ _WATCHING_MESSAGE + "".join('>' if offset == position else ' ' for offset in range(_PROGRESS_WIDTH - len(_WATCHING_MESSAGE))) for position in range(_PROGRESS_WIDTH - len(_WATCHING_MESSAGE)) ] _WIPE_STRING = "\b" * _PROGRESS_WIDTH class PrettySleepe
r(object): def __init__(self): super(PrettySleeper, self).__init__() self._bar_iterator = itertools.cycle(_PROGRESS_BAR) def sleep(self, seconds): sys.stdout.write(next(self._bar_iterator)) sys.stdout.flush() sys.stdout.write(_WIPE_STRING) time.sleep(seconds) ...
gangadharkadam/v5_erp
erpnext/patches/v4_2/reset_bom_costs.py
Python
agpl-3.0
544
0.023897
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_liter
als im
port frappe def execute(): frappe.reload_doc('manufacturing', 'doctype', 'bom_operation') for d in frappe.db.sql("""select name from `tabBOM` where docstatus < 2""", as_dict=1): try: bom = frappe.get_doc('BOM', d.name) bom.ignore_validate_update_after_submit = True bom.calculate_cost() bom.save() fr...
kmod/icbd
icbd/compiler/codegen.py
Python
mit
63,826
0.002977
import _ast import collections from cStringIO import StringIO import re import sys import os from icbd.util import ast_utils, cfa from icbd.type_analyzer import builtins, type_checker, type_system from . import closure_analyzer, usage_checker, phi_analyzer from .type_conversion import InferredTypeOutput from .code_em...
0 return r # 2, 2 # v1.decvref(self.em) # v1.decvref(self.em) # v2.decvref(self.em) # v2.decvref(self.em) raise Exception("Couldn't apply any of %s on %s, %s" % (ops, _v1.t, _v2.t)) def _get(self, node): self.em.pl("; %s:" % getattr(node, "lineno...
dent(-2) # Skip generated nodes since they're not in the type inference (TODO are there cases that that could break?) # and skip several classes of things that can't always be converted if not hasattr(node, "not_real") and not isinstance(r.t, (UnboxedFunctionMT, _SpecialFuncMT, PolymorphicFunct...
mugurrus/superdesk-core
superdesk/publish/publish_content.py
Python
agpl-3.0
6,229
0.003532
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import loggi...
uperdesk import get_resource_service from superdesk.
celery_task_utils import get_lock_id from superdesk.errors import PublishHTTPPushClientError from superdesk.lock import lock, unlock from superdesk.celery_app import celery from superdesk.utc import utcnow from superdesk.profiling import ProfileManager from .publish_queue import QueueState logger = logging.getLogger(...
jnoortheen/django-utils-plus
tests/test_app/models.py
Python
mit
1,082
0.000924
from django.db import models # Create your models here. from utils_plus.abstracts import CheckDeletableModelMixin from utils_plus.choices import ChoicesEnum from utils_plus.models import QueryManager from utils_plus.fields import ChoicesEnumField class Title(ChoicesEnum): mr = 'Mr.' ms = 'Ms.' mrs = 'Mrs...
objects = QueryManager() def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=20) created_on = models.DateTimeField(auto_now_add=True) class Book(models.Model): authors = models.ManyToManyField(Author) publisher = models.
ForeignKey(Publisher, on_delete=models.CASCADE) name = models.CharField(max_length=40) created_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() rel_objects = QueryManager(name__icontains='filter').selects('publisher').prefetches('authors').order_by('-id')
montoyjh/catmap
catmap/solvers/integrated_rate_control_solver.py
Python
gpl-3.0
2,678
0.009709
from solver_base import * from copy import copy class IntegratedRateControlSolver(SolverBase): """Class for estimating rates based on the degree of rate control screening method {citation after published}""" def __init__(self,reaction_model=None): SolverBase.__init__(self,reaction_model) v...
rate_control not specified for: '+dname) else: DRCs[dname] = X desc_energies = [] for dname in self.descriptor_names: Ef = self.species_definitions[dname]['formation_energy'][ref_idx] desc_energies.append(Ef) ...
_dict = self.scaler.get_free_energies(desc_energies) self.reference_free_energies = ref_dict self._static_rate_controls = DRCs self._initialized = True Gs = {} for key,G in zip(self.adsorbate_names + self.transition_state_names, params): Gs[key] =...
pythonhacker/icebox
setup.py
Python
lgpl-2.1
639
0.040689
try: from setuptools import setup except ImportError: from distutils.core import setup setup(name = "icebox", version = "0.1", description = "Search, Play and Record Icecast & Shoutcas
t Streams - On the Linux Console", keywords = "media, icecast, shoutcast, radio, icecream, mpg123, player, stream", author = "Anand B Pillai", author_email = "anandpillai@letterboxes.org", url = "http://github.com/pythonhacker/icebox", license = "GPLV2.1", long_description = """""", ...
'icecast'], scripts = ['scripts/icebox'] )
alaudet/raspi-sump
raspisump/alerts.py
Python
mit
4,886
0.001228
'''Send SMTP email alerts in case of sump pump failure.''' # Raspi-sump, a sump pump monitoring system. # Al Audet # http://www.linuxnorth.org/raspi-sump/ # # All configuration changes should be done in raspisump.conf # MIT License -- http://www.linuxnorth.org/raspi-sump/license.html import os import time import smtp...
name(): '''Return the Raspberry Pi's Hostname''' return platform.node() def unit_types(): '''Determine if inches or centimeters''' unit = configs['unit'] if unit == 'imperial': return 'inches' if unit == 'metric': return 'centimeters' def email_content(water_depth): '''...
gh': 'Subject: Sump Pump Alert!', 'subject_low': 'Subject: Low Water Level Alert!', 'message_high': 'Critical! The sump pit water level is', 'message_low': 'Warning! The waterlevel is down to' } if configs['alert_when'] == 'hig...
muffinresearch/amo-validator
validator/validate.py
Python
bsd-3-clause
3,193
0
import json import os import types from . import constants from .constants import PACKAGE_ANY from .errorbundler import ErrorBundle # This is
necessary. Do not remove it unless you know exactly what # you are doing. import loader # noqa import submain def validate(path, format='json', approved_applications=os.path.join(os.path.dirname(__file__),
'app_versions.json'), determined=True, listed=True, expectation=PACKAGE_ANY, for_appversions=None, overrides=None, timeout=-1, compat_test=False, **kw): """ Perform validati...
tonyseek/sqlalchemy-utils
tests/__init__.py
Python
bsd-3-clause
3,454
0
import warnings import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base, synonym_for from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import ( InstrumentedList, coercion_listener, aggregates...
def create_models(self): class User(self.Base): __tablename__ = 'user' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255))
class Category(self.Base): __tablename__ = 'category' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) @hybrid_property def articles_count(self): return len(self.articles) @articles_count.expressi...
zhzhussupovkz/taxi-py
core/tree.py
Python
mit
1,125
0.000889
# -*- coding: utf-8 -*- # Copyright (c) 2015 Zhassulan Zhussupov # Author zhzhussupovkz@gmail.com # Tree class import random class Tree: def __init__(self, world, screen, x, y): self.world, self.pygame = world, world.pygame self.screen = screen model = random.choice(['tree.png', 'tree_1.pn...
if self.world.taxi.gear == 1: self.y += 0.2 elif self.world.taxi.gear == 2: self.y += 0.4 elif self.world.taxi.gear == 3: self.y += 0.5 elif self.world.taxi.gear == 4: self.y += 0.75 def change(self): ...
ge = self.pygame.image.load("./images/houses/" + model)
ewindisch/nova
nova/tests/api/openstack/compute/test_servers.py
Python
apache-2.0
193,825
0.00032
# Copyright 2010-2011 OpenStack Foundation # Copyright 2011 Piston Cloud Computing, Inc. # 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 Li...
import views from nova.api.openstack import extensions from nova.api.openstack import xmlutil from nova import block_device from nova.compute import api as compute_api from nova.compute import flavors from nova.compute import task_states from nova.compute import vm_states from nova import context from nova import db fr...
ova.network.neutronv2 import api as neutron_api from nova.objects import instance as instance_obj from nova.objects import service as service_obj from nova.openstack.common.gettextutils import _ from nova.openstack.common import jsonutils from nova.openstack.common import policy as common_policy from nova.openstack.com...
openearth/delft3d-gt-server
delft3dworker/migrations/0065_auto_20160831_1441.py
Python
gpl-3.0
1,435
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): depen
dencies = [ ("delft3dworker", "0064_merge"), ] operations = [ migrations.AlterField( model_name="scene", name="phase", field=models.PositiveSmallIntegerField( default=0, choices=[ (0, "New"), ...
(2, "Created containers"), (3, "Starting preprocessing..."), (4, "Running preprocessing..."), (5, "Finished preprocessing"), (6, "Idle: waiting for user input"), (7, "Starting simulation..."), ...
amagdas/superdesk
server/apps/tasks.py
Python
agpl-3.0
11,278
0.001773
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from copy i...
if not desk: raise SuperdeskApiError.notFo
undError('Invalid desk identifier %s' % desk_id) calculate_expiry_from = desk task['desk'] = desk_id task['stage'] = desk.get('incoming_stage') destination_stage = get_resource_service('stages').find_one(req=None, _id=desk.get('incoming_stage')) if stage_id: destination_sta...
wmvanvliet/mne-python
mne/io/nirx/_localized_abbr.py
Python
bsd-3-clause
2,966
0
"""Localizations for meas_date extraction.""" # Authors: Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause # This file was generated on 2021/01/31 on an Ubuntu system. # When getting "unsupported locale setting" on Ubuntu (e.g., with localepurge), # use "sudo locale-
gen de_DE" etc. then "
sudo update-locale". """ import datetime import locale print('_localized_abbr = {') for loc in ('en_US.utf8', 'de_DE', 'fr_FR', 'it_IT'): print(f' {repr(loc)}: {{') print(' "month": {', end='') month_abbr = set() for month in range(1, 13): # Month as locale’s abbreviated name locale....
lento/cortex
contrib/IECoreAlembic/python/IECoreAlembic/ABCToMDC.py
Python
bsd-3-clause
3,409
0.041068
########################################################################## # # Copyright (c) 2012-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # ...
xtensions = "mdc", ), ], ) def doOperation( self, args ) : inFile = IECoreAlembic.AlembicInput( args["inputFile"].value ) outFile = IECore.ModelCache( args["outputFile"].value, IECore.IndexedIO.OpenMode.Write ) time = inFile.timeAtSample( 0 ) def walk( alembicInput, modelCache ) : ...
che.writeObject( o ) t = alembicInput.transformAtTime( time ) modelCache.writeTransform( t ) numChildren = alembicInput.numChildren() for i in range( 0, numChildren ) : alembicChild = alembicInput.child( i ) modelCacheChild = modelCache.writableChild( alembicChild.name() ) walk( alembic...
mjsoltysiak/Python
babynames.py
Python
mit
2,709
0.02141
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re """Baby Names exercise Define the extract_names() function below and c...
year_match: year = year_match[0] print year else: print "Year match not found in %s" %(filename) return None """<tr align="right"><td>1</td><td>Michael</td><td>Jessica</td>"""
name_match = re.findall('<tr align="right"><td>(\d+)</td><td>([A-Z][a-z]+)',indata) for match in name_match: #print match name_rank[match[1]] = match[0] name_list.append(year) #print name_rank for name in sorted(name_rank): name_plus_rank_string = str(name)+' '+str(name_rank[name]) ...
arvindkhadri/flask-social
flask_social/providers/twitter.py
Python
mit
3,793
0.001055
# -*- coding: utf-8 -*- """ flask.ext.social.providers.twitter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains the Flask-Social twitter code :copyright: (c) 2012 by Matt Wright. :license: MIT, see LICENSE for more details. """ from __future__ import absolute_import import twitter from f...
response): return response['user_id'] if response else None class Twit
terConnectHandler(ConnectHandler): """The `TwitterConnectHandler` class handles the connection procedure after a user authorizes a connection from Twitter. The connection values are all retrieved from the response, no extra API calls are necessary. """ def __init__(self, **kwargs): super(Twi...
voyagersearch/voyager-py
processing/tasks/report_duplicate_items.py
Python
apache-2.0
22,408
0.002678
# -*- coding: utf-8 -*- # (C) Copyright 2014 Voyager Search # # 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 l...
esB['meanCellHeight'] = rbB.meanCellHeight raster_propertiesA['meanCellHeight'] = rbA.meanCellWidth raster_propertiesB['meanCellHei
ght'] = rbB.meanCellWidth raster_propertiesA['pixelType'] = rbA.pixelType raster_propertiesB['pixelType'] = rbB.pixelType if raster_propertiesA == raster_propertiesB: continue else: equal = 1 else: equal = 1 return equal d...
vivanov1410/pickled-brain
new/beginner/factorial/python/factorial.py
Python
mit
164
0.006098
#!/usr/bin/python imp
ort sys from library import factorial number = int(sys.argv[1]) factorial = factorial(number) print('{0}! = {1
}'.format(number, factorial))
rkmaddox/mne-python
mne/time_frequency/tests/test_stockwell.py
Python
bsd-3-clause
5,639
0
# Authors : Denis A. Engemann <denis.engemann@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License : BSD 3-clause import os.path as op import pytest import numpy as np from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_equal, assert_...
ell base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') raw_fname = op.join(base_dir, 'test_raw.fif') raw_ctf_fname = op.join(base_dir, 'test_ctf_raw.fif') def test_stockwell_ctf(): """Test that Stockwell can be calculated on
CTF data.""" raw = read_raw_fif(raw_ctf_fname) raw.apply_gradient_compensation(3) events = make_fixed_length_events(raw, duration=0.5) evoked = Epochs(raw, events, tmin=-0.2, tmax=0.3, decim=10, preload=True, verbose='error').average() tfr_stockwell(evoked, verbose='error') # sm...
iViolinSolo/DeepLearning-GetStarted
TF-Persion-ReID/test/test_tf_nn_moments.py
Python
apache-2.0
557
0.003591
#!/usr/bin/python # -*- coding: utf-8 -
*- # Author: violinsolo # Created on 08/03/2018 import tensorflow as tf import numpy as np x_shape = [5, 3, 3, 2] x = np.arange(reduce(lambda t, s: t*s, list(x_shape), 1)) print x x = x.reshape([5, 3, 3, -1]) print x.shape X = tf.Variable(x) with tf.Session() as sess: m = tf.nn.moments(X, axes=[0]) # m...
print(sess.run(m, feed_dict={X: x}))
PythonicPenguins/bangazon_api
bangazon/bangazon_api/models.py
Python
mit
3,851
0.001298
from django.db import models from datetime import datetime class Customer(models.Model): """ purpose: expose all customer data author: Meg Ducharme """ first_name = models.CharField(max_length=55) last_name = models.CharField(max_length=55) date_account_created = models.CharField(max_lengt...
s Product(models.Model): """ purpose: expose al
l product types and add relationship to product type class author: Meg Ducharme """ price = models.FloatField() name = models.CharField(max_length=70) description = models.CharField(max_length=255) date_created = models.DateTimeField() product_type = models.ForeignKey(ProductType, related_na...
jwren/intellij-community
python/testData/intentions/joinIfAssignmentExpressionInInnerCondition.py
Python
apache-2.0
38
0
if x: if y := fo
o(): pass
openstack/ironic
ironic/tests/unit/api/test_proxy_middleware.py
Python
apache-2.0
2,349
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
able_proxy_headers_parsing', True, group='oslo_middleware') self.app = self._make_app() response = self.get_json('/', path_prefix="", headers=self.proxy_headers) href = response["default_version"]["links"][0]["h
ref"] self.assertTrue(href.startswith("https://mycloud.com/ironic")) def test_proxy_headers_disabled(self): """Test proxy headers middleware disabled by default""" response = self.get_json('/', path_prefix="", headers=self.proxy_headers) href = respo...
luispedro/imread
imread/tests/test_jpeg.py
Python
mit
1,272
0.007862
import pytest import numpy as np from imread import imread, imsave from . import file_path import glob _filename = 'imread_testing_file.jpg' @pytest.fixture(autouse=True) def _remove_files(): yield from os import unlink from glob import glob filelist = glob("*.jpg") for f in filelist: try:...
(float) - data)) data = np.arange(256*256*3) data %= 51 data = data.reshape((256,256,3)) data = data.astype(np.uint8) imsave('imread_def.jpg', data) imsave('imread_def91.jpg', data, opts={'jpeg:quality': 91} ) readback = imread('imread_def.jpg') readback91 = imread('imread_def91.jpg...
assert pixel_diff(readback91) < pixel_diff(readback)
tiancj/emesene
emesene/gui/qt4ui/widgets/ChatOutput.py
Python
gpl-3.0
3,318
0.000603
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # #...
return if not href.startswith("file://"): Desktop.open(href) return def clear(self, source="", target="", target_display="",
source_img="", target_img=""): '''clear the content''' QtGui.QTextBrowser.clear(self) self._chat_text = QtCore.QString('') gui.base.OutputText.clear(self) def add_message(self, msg, scroll): if msg.type == "status": msg.message = Plus.msnplus_strip(msg.message) ...
Mistobaan/tensorflow
tensorflow/contrib/distributions/python/ops/half_normal.py
Python
apache-2.0
5,678
0.003346
# Copyright 2017 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 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 permi...
=================================================================== """The Half Normal distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.fram...
beernarrd/gramps
gramps/plugins/textreport/detancestralreport.py
Python
gpl-2.0
41,493
0.001639
# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2002 Bruce J. DeGrasse # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2007-2012 Brian G. Matherly # Copyright (C) 2008 James Friedmann <jfriedmannj@gmail.com> # Copyright (C) 2009 Benny Malengier <b...
lue('listc') self.list_children_spouses = get_value('listc_spouses') self.includenotes = get_value('incnotes') use_call = get_value('usecall'
) blankplace = get_value('repplace') blankdate = get_value('repdate') self.calcageflag = get_value('computeage') self.dupperson = get_value('omitda') self.verbose = get_value('verbose') self.childref = get_value('desref') self.addimages = get_value('incphotos') ...
gratbrav/torrentbug
src/TF_BitTornado/BitTornado/BT1/StorageWrapper.py
Python
mit
37,256
0.006174
# Written by Bram Cohen # see LICENSE.txt for license information from BitTornado.bitfield import Bitfield from sha import sha fro
m BitTornado.clock import clock from traceback import print_exc from random import randrange try: True except: True = 1 False = 0 try: from bisect import insort except: def insort(l, item): l.append(item) l.sort() DEBUG = False STATS_INTERVAL = 0.2 def dummy_status(fractionDone = ...
t: def __init__(self, l = []): self.d = {} for i in l: self.d[i] = 1 def __len__(self): return len(self.d) def includes(self, i): return self.d.has_key(i) def add(self, i): self.d[i] = 1 def extend(self, l): for i in l: self.d[i...
HendrikVE/riotam-backend
riotam_backend/common/ModuleCache.py
Python
lgpl-2.1
1,659
0.001808
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ * Copyright (C) 2017 Hendrik van Essen * * This file is subject to the terms and conditions
of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. """ import os import sys from shutil impo
rt copytree, copyfile # append root of the python code tree to sys.apth so that imports are working # alternative: add path to riotam_backend to the PYTHONPATH environment variable, but this includes one more step # which could be forget CUR_DIR = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT_DIR = os.pa...
DepthDeluxe/dot11sniffer
app/Trilateration_Colin.py
Python
mit
1,799
0.014452
import math class Point: def __init__(self, x, y): self.x = x self.y = y def rssToEstimatedDistance(rss): freq = 2462 # freq of WiFi channel 6 origDBm = -20 # estimate this value loss = abs(origDBm - rss) dist = 10 ** ( ( loss
+ 27.55 - 20 * math.log10(freq) ) / 20 ) return dist def trilaterate(inSources, rss): distances = [] distances.append( rssToEstimatedDistance(rss[0]) ) distances.append( rssToEstimatedDistance(rss[1]) ) distances.append( rssToEstimatedDistance(rss[2]) ) # find the three intersection points ...
(inSources[0], inSources[1], distances[0], distances[1]) tp2 = _findEqualPerp(inSources[0], inSources[2], distances[0], distances[2]) tp3 = _findEqualPerp(inSources[1], inSources[2], distances[1], distances[2]) p = Point( (tp1.x + tp2.x + tp3.x) / 3, (tp1.y + tp2.y + tp3.y) / 3 ) return p def _findEqu...
Linaro/squad
squad/core/migrations/0059_project_important_metadata_keys.py
Python
agpl-3.0
488
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-27
22:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0058_populate_projectstatus_has_me
trics'), ] operations = [ migrations.AddField( model_name='project', name='important_metadata_keys', field=models.TextField(blank=True, null=True), ), ]
leppa/home-assistant
homeassistant/components/rachio/__init__.py
Python
apache-2.0
10,051
0.000099
"""Integration with the Rachio Iro sprinkler system controller.""" import asyncio import logging import secrets from typing import Optional from aiohttp import web from rachiopy import Rachio import voluptuous as vol from homeassistant.components.http import HomeAssistantView from homeassistant.const import CONF_API_...
KEY_ID]}) # Register to listen to th
ese events from the device url = self.rachio.webhook_url auth = WEBHOOK_CONST_ID + self.rachio.webhook_auth new_webhook = self.rachio.notification.postWebhook( self.controller_id, auth, url, event_types ) # Save ID for deletion at shutdown current_webhook_id =...
eduNEXT/edunext-platform
openedx/core/djangoapps/coursegraph/management/commands/dump_to_neo4j.py
Python
agpl-3.0
2,914
0.00103
""" This file contains a management command for exporting the modulestore to neo4j, a graph database. """ import logging from textwrap import dedent from django.core.management.base import BaseCommand from openedx.core.djangoapps.coursegraph.tasks import ModuleStoreSerializer log = logging.getLogger(__name__) cl...
ss Command(BaseCommand): """ Command to dump modulestore data to neo4j Takes the following named arguments: host: the host of the neo4j server https_port: the port on the neo4j server that accepts https requests http_port: the port on the neo4j server that accepts http requests secu...
es http user: the username for the neo4j user password: the user's password courses: list of course key strings to serialize. If not specified, all courses in the modulestore are serialized. override: if true, dump all--or all specified--courses, regardless of when they were last...
aspc/mainsite
aspc/minutes/migrations/0001_initial.py
Python
mit
1,080
0.002778
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='MeetingMinutes', fields=[ ('id', models.AutoFie...
xt=b'The minutes of this meeting in <a href="http://daringfireball.net/
projects/markdown/dingus">Markdown</a>', blank=True)), ], options={ 'ordering': ['date'], 'verbose_name': 'meeting minutes', 'verbose_name_plural': 'meeting minutes', }, bases=(models.Model,), ), ]
Healthjoy/rq-cron
setup.py
Python
mit
475
0.002105
#!/usr/bin/env python from setuptools import setup
setup(name='RQ-Cron', version='1.0.2', description='RQ Cron', author='Andrii Kostenko', author_email='andrey@kostenko.name', packages=['rq_cron', 'rq_cron.scripts'], install_requires=['rq>=0.3.5', 'croniter'], entry_points='''\ [console_scripts] rq-cron = rq_c...
/github.com/Healthjoy/rq-cron', )
abhishek-sehgal954/SVG_Digital_Halftoning
patterning_algorithm/patterning_clustered_dot.py
Python
mit
5,365
0.030568
#This program t
akes a raster image and produces its raster halftone using patterning algorithm. """ For each possible value in the image, we create and display a pattern of pixels that approximates that value. Remembering the concept of spatial i
ntegration, if we choose the appropriate patterns we can simulate the appearance of various intensity levels -- even though our display can only generate a limited set of intensities. For example, consider a 3 x 3 pattern. It can have one of 512 different arrangements of pixels: however, in terms of intensity, not a...
akash1808/nova_test_latest
nova/tests/unit/compute/test_rpcapi.py
Python
apache-2.0
20,820
0.006484
# 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 agr...
if 'host' in kwargs: host = kwargs['host'] elif 'instances' in kwargs: host = kwargs['instances'][0]['host'] else: host = kwargs['instance']['host'] with contextlib.nested( mock.p
atch.object(rpcapi.client, rpc_method), mock.patch.object(rpcapi.client, 'prepare'), mock.patch.object(rpcapi.client, 'can_send_version'), ) as ( rpc_mock, prepare_mock, csv_mock ): prepare_mock.return_value = rpcapi.client if '_return_value' i...
smartczm/python-learn
Old-day01-10/s13-day11/线程/线程池.py
Python
gpl-2.0
823
0.004071
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- # Author: ChenLiang # 线程池 """ """ import queue import threading import time class ThreadPool: def __init__(self, maxsize=5): self.maxsize = maxsize self._q = queue.Queue(maxsize) for i in range(maxsize): self._q.put(threading...
elf): # 定义线程池获取函数 return self._q.get() def add_thread(self): # 定义线程池添加函数 self._q.put(threading.Thread) pool = ThreadPool(5) def task(args, p): print(args) time.sleep
(10) p.add_thread() # 手动增加线程池 for j in range(100): # t等于threading.Thread类 t = pool.get_thread() # 获取线程池 obj = t(target=task, args=(j, pool, )) obj.start()
OpenSourcePolicyCenter/webapp-public
webapp/apps/pages/urls.py
Python
mit
1,175
0
from django.conf.urls import url from .views import (homepage, aboutpage, newspage, gallerypage, hellopage,
embedpage, widgetpage, newsdetailpage, apps_landing_page, border_adjustment_plot, docspage, gettingstartedpage) urlpatterns = [ # url(r'^apps/$', apps_landing_page, name='apps'), url(r'^$', homepage, name='home'), url(r'^about/$', aboutpage, name='about'), url(r'^...
/$', gettingstartedpage, name='gettingstartedpage'), url(r'^hello/$', hellopage, name='hello'), url(r'^gallery/$', gallerypage, name='gallery'), url(r'^news/$', newspage, name='news'), url(r'^news/news-detail$', newsdetailpage, name='newsdetail'), url(r'^gallery/(?P<widget_id>\w+)/$', widgetpage), ...
vandenheuvel/tribler
Tribler/Test/Community/Market/test_ttl.py
Python
lgpl-3.0
1,095
0
import u
nittest from Tribler.community.market.core.ttl import Ttl class TtlTestSuite(unittest.TestCase): """Ttl test cases.""" def setUp(self): # Object creation self.ttl = Ttl(0) self
.ttl2 = Ttl(2) self.ttl3 = Ttl(2) self.ttl4 = Ttl(1) def test_init(self): # Test for init validation with self.assertRaises(ValueError): Ttl(-100) with self.assertRaises(ValueError): Ttl('1') def test_default(self): # Test for default ini...
geodynamics/gale
gLucifer/config/SConfig/Platform.py
Python
gpl-2.0
2,519
0.004367
import os, platform import SCons.Script import SConfig class Platform(SConfig.Node): def __init__(self, scons_env, scons_opts, required=False): SConfig.Node.__init__(self, scons_env, scons_opts, required) self.checks = [self.print_results] # Will be set after successful configuration. ...
tform().find('ppc64') != -1 or \ platform.architecture()[0].find('64') != -1 or \ self.
env['with_64bit']) and \ not self.env['with_32bit']: self.bits = 64 else: self.bits = 32 def check_CC(self): if 'CC' in self.env['ENV']: self.env['CC'] = self.env['ENV']['CC'] self.CC = self.env['CC'] def print_results(self): ...
open-forcefield-group/smarty
smarty/tests/test_smirky_sampler.py
Python
mit
7,993
0.019142
import unittest import smarty from openforcefield.typing.chemistry.environment import * from openforcefield.utils.utils import read_molecules from smarty.sampler_smirky import * from smarty import utils from smarty import score_utils from operator import itemgetter, attrgetter import openeye.oechem from openeye.oechem ...
'Improper','Periodic
TorsionGenerator'), ('None', None)] for (tag, expected) in typetags: sample_tag, edges, sym_odds = sampler.get_type_info(tag) self.assertEqual(sample_tag, expected, msg = "get_force_type(%s) should return %s, but %s was returned instead" % (tag, expected, sample_tag)) ...
riga/luigi
luigi/contrib/dropbox.py
Python
apache-2.0
11,273
0.002839
# -*- coding: utf-8 -*- # # Copyright (c) 2019 Jose-Ignacio Riaño Chico # # 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 a...
ng permissions and limitations under # the License. # import logging import ntpath import os import random import tempfile import time from contextlib import contextmanager from functools import wra
ps import luigi.format from luigi.target import FileSystem, FileSystemTarget, AtomicLocalFile logger = logging.getLogger('luigi-interface') try: import dropbox.dropbox import dropbox.exceptions import dropbox.files except ImportError: logger.warning("Loading Dropbox module without the python package ...
mytliulei/DCNRobot
src/tools/testlink/__init__.py
Python
apache-2.0
877
0.001143
#! /usr/bin/python # -*- coding: UTF-8 -*- # Copyright 2012 TestLink-API-Python-client developers # # 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...
n "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------ from .testlinkerrors import TestLinkError f...
stLinkHelper
Brainbuster/openpli-buildumgebung
openembedded-core/scripts/lib/wic/plugins/source/rawcopy.py
Python
gpl-2.0
2,926
0.001025
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope t...
msger.error("No file specified\n") return src = os.path.join(bootimg_dir, source_params['file']) dst = src if ('skip' in source_params): dst = os.path.join(cr_workdir, source_params['file']) dd_cmd = "dd if=%s of=%s ibs=%s skip=1 conv=notrunc" % \...
kickstart (kB) du_cmd = "du -Lbks %s" % dst out = exec_cmd(du_cmd) filesize = out.split()[0] if int(filesize) > int(part.size): part.size = filesize part.source_file = dst
kincl/oncall
oncall_old/models/event.py
Python
gpl-3.0
1,172
0.003413
from oncall import db class Event(db.Model): __tablename__ = 'events' id = db.Column('id', db.Integer, primary_key=True) user_username = db.Column(db.String(200), db.ForeignKey('users.username')) team_slug = db.Column(db.Integer, db.ForeignKey('teams.slug')) role = db.Column(db.String(200)) sta...
(self.role, self.user.name), user_username=self.user_username, role=self.role) if self.end is not None: r['end'] = self.end.isoformat()
return r def __repr__(self): return '<Event %s %s %s:%s from %s to %s>' % (self.id, self.team_slug, self.role, self.user_username, self.start, self.end)
Ingenico-ePayments/connect-sdk-python2
tests/integration/test_multiline_header.py
Python
mit
1,483
0.003372
import unittest import tests.integration.init_utils as init_utils from ingenico.connect.sdk.request_header import RequestHeader from tests.integration.init_utils import MERCHANT_ID from ingenico.connect.sdk.merchant.products.directory_params import DirectoryParams from ingenico.connect.sdk.factory import Factory from i...
spaces " configuration = init_utils.create_communicator_configuration() meta_data_provider = MetaDataProvider(integrator="Ingenico", additional_request_headers=(RequestHeader("X-GCS-MultiLineHeader", multi_line_header), )) params = DirectoryParam...
iguration, meta_data_provider=meta_data_provider) with Factory.create_client_from_session(session) as client: response = client.merchant(MERCHANT_ID).products().directory(809, params) self.assertGreater(len(response.entries), 0) if __name__ == '__main__': unittest.main()
alown/mypaint
gui/builderhacks.py
Python
gpl-2.0
4,322
0.000694
# -*- encoding: utf-8 -*- # This file is part of MyPaint. # Copyright (C) 2013-2015 by Andrew Chadwick <a.t.chadwick@gmail.com> # # 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.
"""Hacks for loading stuff from GtkBuilder files.""" ## Imports from __future__ import division, print_function import gi from gi.repository import Gtk import lib.xml ## Public functions def add_objects_from_template_string(builder, buffer_, object_ids, params): """Templatizes, parses, merges, and returns ...
xmnlab/minilab
arch/multi_process/producer_consumer/plotter.py
Python
gpl-3.0
1,755
0.00114
from __future__ import print_function, division from matplotlib import pyplot as plt from matplotlib.ticker import EngFormatter import numpy as np class PlotTask(object): data_buffer = {} def __init__(self, channels={}, data_size=1): self.data_size = data_size self.time = np.arange(0, 1, 1/d...
if not group_name in data: continue self.data_buffer[group_name] = data[group_name] i += 1 chart_id = self.chart_n*100 + 10 + i for ch_name, ch_data in data[group_name].items(): ax = plt.subplot(chart_id)
ax.xaxis.set_major_formatter(self.formatter) ax.axis(self.frame_limits) ax.grid() ax.set_xlabel(group_name) if not len(ch_data): ch_data = [0]*len(self.time) print(ch_name, 'NULL DATA') ...
Nettacker/Nettacker
lib/payload/shellcode/opcoder/linux_x86/engine.py
Python
gpl-3.0
24,255
0.003628
#!/usr/bin/env python # -*- coding: utf-8 -*- import binascii from lib.payload.shellcode.stack import engine as stack from core.compatible import version replace_values_static = { 'xor %ebx,%ebx': '31 db', 'xor %ecx,%ecx': '31 c9', 'xor %eax,%ebx': '31 c3', 'xor %ecx,%ebx': '31 cb', 'xor %ebx,%eax...
(',')[ 0])))) if version() ==3: rep = str('81 f3') + str(stack.st(( binascii.a2b_hex((str('0') + str( line.rsplit('$0x')[1].rsplit(',')[ ...
0])).encode('latin-1'))).decode( 'latin-1'))) shellcode = shellcode.replace(line, rep) if '%ecx' in line.rsplit(',')[1]: if len(line.rsplit(',')[0]) >= 14: try: ...
hippysurfer/scout-records
check.py
Python
gpl-2.0
1,171
0.001708
# coding=utf-8 """Online Scout Manager Interface. Usage: check.py [-d] <apiid> <token> check.py (-h | --help) check.py --version Options: -d,--debug Turn on debug output. -h,
--help Show this screen. --version Show version. """ import logging from docopt import docopt import osm from group import Group, OSM_REF_FIELD from update import MAPPING log = logg
ing.getLogger(__name__) DEF_CACHE = "osm.cache" DEF_CREDS = "osm.creds" def _main(osm, auth): #test_section = '15797' group = Group(osm, auth, MAPPING.keys()) if group.missing_adult_references(): log.warn("Missing adult references {!r}".format( group.missing_adult_references())) if...
eiriks/pyvol
pyvol/est/CovEst.py
Python
mit
7,719
0.006737
"""Module containing routines for estimating covariance models. """ import math from pyvol.tseries.Transforms import SeqXform import CovUtils class CovEstimator: """Base class illustrating the API covariance estimators should follow All covariance estimators should subclass this class and override ...
level set of return data. """ self.returnColName = returnColName def Startup(self, query): """Prepare to do estimation on data in a given query. INPUTS: -- query: A Sequence.TimeSeq object with raw data for estimation. ...
------------------------------------------------------- PURPOSE: Prepare to do estimation on data in a given query. Subclasses may override if desired. """ self.returnCol = query.GetColIndex(self.returnColName) def Shutdown...
bweaver2/bzrFlag
bzagents/agent0.py
Python
gpl-3.0
3,861
0.001036
#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is...
sys import math import time from bzrc import BZRC, Command class Agent(object): """Class handles all command and control logic for a teams tanks.""" def __init__(self, bzrc): self.bzrc = bzrc self.constants = self.bzrc.get_constants() self.commands = [] def tick(self, time_diff)...
""Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots, obstacles = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.othertanks = othertanks self.flags = flags self.shots = shots self.enemies = [tank for tank in othertanks if tank.col...
ericls/niji
niji/tasks.py
Python
mit
984
0.002033
# -*- coding: utf-8 -*- from __future__ import absolute_import from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.auth import get_user_model logger = get_task_logger(__name__) @shared_task def notify(sender, to, topic=None, post=None): from nij
i.models import Not
ification, Topic, Post User = get_user_model() if not any([topic, post]): logger.warning('No topic or post provided, ignored') ntf, created = Notification.objects.get_or_create( topic=Topic.objects.filter(pk=topic).first(), post=Post.objects.filter(pk=post).first(), sender=...