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
our-city-app/oca-backend
src/shop/cron.py
Python
apache-2.0
827
0
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
RRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @@license_version:1.7@@ import webapp2 from shop.jobs import clean_unverified_signups class CleanupUnverifi
edSignupRequests(webapp2.RequestHandler): def get(self): clean_unverified_signups.job()
device42/servicenow_to_device42_sync
starter.py
Python
mit
2,360
0.013136
#!/usr/bin/python """ README This script is deprecated. Please use https://github.com/device42/servicenow_device42_mapping This script reads CIs from Servicenow and uploads them to Device42. It has 2 modes: 1. Full migration - when the TIMEFRAME is set to 0 2. Synchronization - when the TIMEFRAME...
"Accept":"application/json"} TABLES = ['cmdb_ci_server' , 'cmdb_ci_computer', 'cmdb_ci_app_server', 'cmdb_ci_database', 'cmdb_ci_email_server', 'cmdb_ci_ftp_server', 'cmdb_ci_directory_server', 'cmdb_ci_ip_server'] # ===== Other ===== # DEBUG = True # print to STDOUT DRY_RUN = False ...
MEFRAME = 0 # Value represents hours. If set to 0, script does full migration, if set to any other value, # script syncs changes back from till now(). now() refers to current localtime. if __name__ == '__main__': snow = ServiceNow(D42_URL, D42_USER, D42_PWD, USERNAME, PASSWORD, BA...
JeffPaine/subaru_search
subaru/spiders/subaru_spider.py
Python
mit
3,059
0.002942
import urlparse from scrapy.spider import BaseSpider from scrapy.selector import Selector from scrapy.http import Request from ..items import Car # Add the model(s) below you want to search for # e.g. MODELS = ['Outback'] MODELS = [] # Enter the domain name(s) here you have permission to retrieve data from # e.g. DO...
d car # If there's a next page
link, parse it for cars as well next_links = sel.xpath('//*[@rel="next"]/@href').extract() if len(next_links) > 0: query = next_links[0] url = urlparse.urlparse(response.url) base = urlparse.urlunsplit([url.scheme, url.netloc, url.path, None, None]) next_u...
pkdevbox/trac
trac/dist.py
Python
bsd-3-clause
22,240
0.000899
# -*- coding: utf-8 -*- # # Copyright (C) 2011 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.org/wiki/TracLicense. # # This software consists o...
on': {'doc': 4}, 'BoolOption': {'doc': 4}, 'IntOption': {'doc': 4}, 'FloatOption': {'doc': 4}, 'ListOption': {'doc': 6}, 'ChoiceOption': {'doc': 4}, 'PathOption': {'doc': 4}, 'ExtensionOption': {'doc': 5}, 'OrderedExtensionsOption': {'
doc': 6}, } _DEFAULT_CLEANDOC_KEYWORDS = ( 'ConfigSection', 'Option', 'BoolOption', 'IntOption', 'FloatOption', 'ListOption', 'ChoiceOption', 'PathOption', 'ExtensionOption', 'OrderedExtensionsOption', 'cleandoc_', ) def extract_python(fileobj, keywords, comment_tags, options):...
ColdMatter/EDMSuite
EDMScripts/OldScripts/MonitorRFDischargesScanSynthAmp.py
Python
mit
1,182
0.032995
# This loop monitors the rf Discharges for a particular amplitude, then repeats for other amplitudes # n from DAQ.Environment import * def scanRF(LowestAmp, HighestAmp, step, numScans): # setup AmpList = [] fileSystem = Environs.FileSystem file = \ fileSystem.GetDataDirectory(\ fileSystem.Paths["scanMaster...
erateNextDataFileName() print("Saving as " + file + "_" + "MeasuredRF1Amp" + "*.zip") print("") # start looping r = range(int(10*LowestAmp), int(10*Highes
tAmp), int(10*step)) for i in range(len(r)): print "hc:rf1 Amplitude -> " + str(float(r[i])/10) hc.SetGreenSynthAmp(float(r[i])/10) # hc.GreenSynthOnAmplitude = double(r[i]/10) hc.EnableGreenSynth( False ) hc.EnableGreenSynth( True ) hc.UpdateRFPowerMonitor() rfAmpMeasured = hc.RF1PowerCentre hc.Step...
jnnk/pyethereum
pyethereum/blocks.py
Python
mit
32,057
0.000655
import time import rlp import trie import db import utils import processblock import transactions import logging import copy import sys from repoze.lru import lru_cache # logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() INITIAL_DIFFICULTY = 2 ** 17 GENESIS_PREVHASH = '\00' * 32 GENESIS_COINBASE =...
s_used=0, timestamp=0, extra_data='', nonce='', trans
action_list=[], uncles=[], header=None): self.prevhash = prevhash self.uncles_hash = uncles_hash self.coinbase = coinbase self.difficulty = difficulty self.number = number self.min_gas_price = min_gas_price self.gas_limit = gas_l...
nwiizo/workspace_2017
pipng/imagescale-c.py
Python
mit
4,916
0.002035
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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)...
.copied, re
sults.scaled) difference = results.todo - (results.copied + results.scaled) if difference: message += "skipped {} ".format(difference) message += "using {} coroutines".format(concurrency) if canceled: message += " [canceled]" Qtrac.report(message) print() if __name__...
aptivate/django-spreadsheetresponsemixin
setup.py
Python
gpl-3.0
1,365
0.001465
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() LICENSE = open(os.path.join(os.path.dirname(__file__), 'LICENSE.txt')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup...
opment Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', ...
2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'], )
HBEE/odoo-addons
sale_restrict_partners/__openerp__.py
Python
agpl-3.0
1,762
0.001135
# -*- coding: ut
f-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This progra
m 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 # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful...
Eveler/libs
__Python__/ufms_blanks/appy3/gen/mixins/ToolMixin.py
Python
gpl-3.0
65,134
0.00281
# ------------------------------------------------------------------------------ import os, os.path, sys, re, time, random, types, base64 from appy import Object import appy.gen from appy.gen import Search, UiSearch, String, Page from appy.gen.layout import ColumnLayout from appy.gen import utils as gutils from appy.ge...
--------------------------------------------------------------------- class ToolMixin(BaseMixin): _appy_meta_type = 'Tool' xhtmlEncoding = 'text/html;charset=UTF-8' def getPortalType(self, metaTypeOrAppyClass): '''Returns the name of the portal_type that is based on p_metaTypeOrAppyType....
stance(metaTypeOrAppyClass, str): res = gutils.getClassName(metaTypeOrAppyClass, appName) if res.find('_wrappers') != -1: elems = res.split('_') res = '%s%s' % (elems[1], elems[4]) if res in ('User', 'Group', 'Translation'): res = appName + res return res ...
Daarknes/Gadakeco
src/util/directions.py
Python
gpl-3.0
328
0
from enum import
Enum class Direction(Enum): i
nvalid = (0.0, 0.0) up = (0.0, -1.0) down = (0.0, 1.0) left = (-1.0, 0.0) right = (1.0, 0.0) def x(self): return self.value[0] def y(self): return self.value[1] def __str__(self): return str(self.value)
EmreAtes/spack
var/spack/repos/builtin/packages/py-readme-renderer/package.py
Python
lgpl-2.1
1,901
0.001052
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
###################################### from spack import * class PyReadmeRenderer(PythonPackage): """readme_renderer is a library for rendering "readme" descriptions for Warehouse.""" homepage = "
https://github.com/pypa/readme_renderer" url = "https://pypi.io/packages/source/r/readme_renderer/readme_renderer-16.0.tar.gz" version('16.0', '70321cea986956bcf2deef9981569f39') depends_on('python@2.6:2.8,3.2:3.3') depends_on('py-setuptools', type='build') depends_on('py-bleach', type=('buil...
environmentalomics/iso-to-image
uploader/test/test_sanitise_machine_name.py
Python
mit
1,066
0.020657
#!/usr/bin/env python3 # encod
ing: UTF-8 import unittest from vCloudOVFMunger import sanitise_machine_name # Test my basic st
ring sanitiser. This needs no setup, files, or network stuff. # python -m unittest test.test_sanitise_machine_name class XMLTests(unittest.TestCase): def setUp(self): self.alltests = [ 'same-string' ,'same-string', 'lOWER cASE' ,'lower-case', 'L0@d$@ jµnk' ,'l0...
thegoonies/tools
sopel-modules/grep-logs.py
Python
mit
2,449
0.003675
import re, os, datetime from sopel import module from sopel.config.types import StaticSection, ValidatedAttribute, FilenameAttribute DEFAULT_CHANLOGS_DIR = os.getenv("HOME") + "/chanlogs" DEFAULT_LINE_PATTERN = re.compile(r"^([^\s]*) <([^>]*)> (.*)$") class GrepLogsSection(StaticSection): dir = FilenameAttribu...
if pattern.search(msg): bot.say("On {}, {} said: {}".format(date.strftime("%c"), nick, msg)) found += 1 except Exception as e: continue if found == 0: bot.reply("No entries found matching '{}'".format(pattern_str...
smistad/FAST
source/FAST/Examples/Python/stream_from_webcamera.py
Python
bsd-2-clause
428
0.004673
## @example stream_from_webcamera.py # This example will stream images from your webcamera and run it through
a simple edge detection filter (LaplacianOfGaussian) # and display it in real-time. import fast streamer = fast.CameraStreamer.create() filter = fast.LaplacianOfGaussian.create().connect(streamer) renderer
= fast.ImageRenderer.create().connect(filter) window = fast.SimpleWindow2D.create().connect(renderer).run()
Atoku/siku
samples/beaufort.py
Python
gpl-2.0
14,677
0.025346
'''Siku scenario Sea ice element simple free drift example Creates a (large) polygon in polar region and sets some basic winds in still water. No interaction with any boundaries, just a free float of the polygon in the area and output in KML format of its locations. Be sure that siku module is in y...
scosity' : 1.0,#1.0,#1 'rotatability' : 0.750,#0.75 'tan
gency' : -0.00003,#-0.00003 'elasticity' :-50000000.0,#-5000000.0, 'bendability' : 1.0,#1.0, 'solidity' : 0.05,#0.05, 'tensility' : 0.30,#0.615, ...
gunan/tensorflow
tensorflow/python/util/nest_test.py
Python
apache-2.0
54,367
0.003532
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
f", "g"), "h"))) structure = (NestTest.PointXY(x=4, y=2), ((NestTest.PointXY(x=1, y=0),),)) flat = [4, 2, 1, 0] self.assertEqual(nest.flatten(structure), flat) restructured_from_flat = nest.pack_sequence_as(structure, flat) self.assertEqual(restructured_from_flat, structure) sel...
estructured_from_flat[0].y, 2) self.assertEqual(restructured_from_flat[1][0][0].x, 1) self.assertEqual(restructured_from_flat[1][0][0].y, 0) self.assertEqual([5], nest.flatten(5)) self.assertEqual([np.array([5])], nest.flatten(np.array([5]))) self.assertEqual("a", nest.pack_sequence_as(5, ["a"])) ...
citrix-openstack-build/python-keystoneclient
keystoneclient/tests/v3/test_endpoints.py
Python
apache-2.0
3,490
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
def test_list_public_interface(self): interface = 'public' expected_path = 'v3/%
s?interface=%s' % (self.collection_key, interface) self.test_list(expected_path=expected_path, interface=interface) def test_list_admin_interface(self): interface = 'admin' expected_path = 'v3/%s?interface=%s' % (self.collection_key, interface) self.test_list(expected_path=expected_...
mpkato/mobileclick
tests/summary_test.py
Python
mit
3,680
0.003261
# -*- coding:u
tf-8 -*- import unittest import nose from mobileclick import Iunit, Intent, Summary, SummaryError class SummaryTestCase(unittest.TestCase): def setUp(self): self.qid = 'MC2-E-0001' self.i1 = Intent(self.qid, '%s-INTENT000
1' % self.qid, 'Link') self.i2 = Intent(self.qid, '%s-INTENT0002' % self.qid, 'Link') self.u1 = Iunit(self.qid, '%s-0001' % self.qid, 'A') self.u2 = Iunit(self.qid, '%s-0002' % self.qid, 'A') self.u3 = Iunit(self.qid, '%s-0003' % self.qid, 'A') self.u4 = Iunit(self.qid, '%s-0004'...
arnaudsj/titanium_mobile
support/module/builder.py
Python
apache-2.0
7,110
0.03488
#!/usr/bin/env python # -*- coding: utf-8 -*- # # module builder script # import os, sys, shutil, tempfile, subprocess, platform template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) support_dir = os.path.join(template_dir, 'support') sdk_dir = os.path.dirname(template_dir) android_suppo...
t_args = [script, name, moduleid, dir, platform] if is_android(platform): create_project_args.append(android_sdk.get_android_sdk())
run_python(create_project_args) gen_project_dir = os.path.join(dir, name) gen_resources_dir = os.path.join(gen_project_dir, 'Resources') # copy in our example source copy_resources(os.path.join(project_dir,'example'), gen_resources_dir) # patch in our tiapp.xml tiapp = os.path.join(gen_project_dir...
marvinlenk/subsystem_entropy_epsplots
pyplot_eps/ent_eps.py
Python
bsd-2-clause
6,836
0.00395
import numpy as np import os from mpEntropy import mpSystem import matplotlib as mpl from matplotlib.pyplot import cm import matplotlib.pyplot as plt import matplotlib.mlab as mlab from scipy.stats import norm from scipy.signal import savgol_filter from scipy.optimize import curve_fit # This is a workaround until scipy...
in_index:max_index], ent_array[min_index:max_index, 1], color='r') if sysVar.boolPlotAverages: tavg = savgol_filter(ent_array[:, 1], fwidth, ford) plt.plot(step_array[loavgind:], tavg[loavgind:], linewidth=avgsize, linestyle=avgstyle, color='black') plt.xlabel(r'$J
\,t$') plt.ylabel(r'$S\textsubscript{sys}$') a = plt.axes([.5, .35, .4, .4]) plt.semilogy(step_array[inlay_log_min_index:inlay_log_max_index], np.abs(avg - ent_array[inlay_log_min_index:inlay_log_max_index, 1]), color='r') plt.ylabel(r'$|\,\overline{S}\textsubscript{sys} - S\textsubscript{sys}(t)|$') plt.y...
mitchcapper/mythbox
resources/lib/mysql-connector-python/python2/examples/unicode.py
Python
gpl-2.0
2,921
0.003766
#!/usr/bin/env python # -*- coding: utf-8 -*- # MySQL Connector/Python - MySQL driver written in Python. # Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. # MySQL Connector/Python is licensed under the terms of the GPLv2 # <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most...
ral Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys, os import mysql.connector """ Example using MySQL Connector/P...
is to work you need to make sure your terminal can output unicode character correctly. Check if the encoding of your terminal is set to UTF-8. """ def main(config): output = [] db = mysql.connector.Connect(**config) cursor = db.cursor() # Show the unicode string we're going to use unistr = u"\...
disqus/Diamond
src/collectors/snmpraw/snmpraw.py
Python
mit
6,089
0.000493
# coding=utf-8 """ The SNMPRawCollector is designed for collecting data from SNMP-enables devices, using a set of specified OIDs #### Configuration Below is an example configuration for the SNMPRawCollector. The collector can collect data any number of devices by adding configuration sections under the *devices* hea...
({ 'oids': {}, 'path_prefix': 'servers', 'path_suffix': 'snmp', }) return default_config def _precision(self, value): """ Return the precision of the number """ value = str(value) decimal = value.rfind('.') if decim...
elf.skip_list.append((device, oid)) if reason is not None: self.log.warn('Muted \'{0}\' on \'{1}\', because: {2}'.format( oid, device, reason)) def _get_value_walk(self, device, oid, host, port, community): data = self.walk(oid, host, port, community) if data is...
kanishka-linux/AnimeWatch
AnimeWatch-Debian-PyQt5/create_deb.py
Python
gpl-3.0
1,480
0.032432
import os import sys import shutil import subprocess BASEDIR,BASEFILE = os.path.split(os.path.abspath(__file__)) print(BASEDIR,BASEFILE,os.getcwd()) par_dir,cur_dir = os.path.split(BASEDIR) src_dir = os.path.join(par_dir,'AnimeWatch-PyQt5') deb_config_dir = os.path.join(BASEDIR,'DEBIAN') control_file = os.path.join(...
_dir = None exec_file = os.path.join(BASEDIR,'anime-watch') desk_file = os.path.join(BASEDIR,'AnimeWatch.desktop') for i in lines: i = i.strip() if i.startswith('Version:'): version_num = i.replace('Version:','',1).strip() dest_dir = os.path.join(BASEDIR,'AnimeWatch-'+version_num) break usr_share = os.path.jo...
sr_share_animewatch = os.path.join(dest_dir,'usr','share','AnimeWatch') if dest_dir: if os.path.exists(dest_dir): shutil.rmtree(dest_dir) os.makedirs(dest_dir) os.makedirs(usr_share) os.makedirs(usr_bin) shutil.copytree(deb_config_dir,os.path.join(dest_dir,'DEBIAN')) shutil.copy(exec_file,usr_bin) shutil.copy...
tequa/ammisoft
ammimain/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64/Lib/site-packages/jedi/evaluate/iterable.py
Python
bsd-3-clause
31,484
0.00127
""" Contains all classes and functions to deal with lists, dicts, generators and iterators in general. Array modifications ******************* If the content of an array (``set``/``list``) is requested somewhere, the current module will be checked for appearances of ``arr.append``, ``arr.insert``, etc. If the ``arr`...
builtin_context, method, builtin_func): self._builtin_context = builtin_context self._method = method self._builtin_func = builtin_func def py__call__(self, params): return self._method(self._builtin_context) def __getattr__(self, name): return getattr(self._builtin_fun...
ictFilter): """ A filter for methods that are defined in this module on the corresponding classes like Generator (for __next__, etc). """ class SpecialMethodName(AbstractNameDefinition): api_type = 'function' def __init__(self, parent_context, string_name, callable_, builtin_context...
alex/flanker
flanker/mime/message/errors.py
Python
apache-2.0
223
0
class MimeError(Exception): pass class DecodingError(MimeError): """Thrown when there is
an encoding error.""" pass class EncodingError(MimeError):
"""Thrown when there is an decoding error.""" pass
ylow/SFrame
oss_src/unity/python/sframe/util/metric_mock.py
Python
bsd-3-clause
1,457
0.019218
''' Copyright (C) 2016 Turi All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. ''' import logging import pprint class ConsumerMock: def __init__(self): self._num_flushes = 0 def flush(self): self._num_flushes += 1 cla...
self._consumer = ConsumerMock() self._cal
ls = [] self._pp = pprint.PrettyPrinter(indent=2) self._event_limit = event_limit self.logger = logging.getLogger(__name__) def track(self, distinct_id, event_name, properties={}, meta={}): if self._event_limit < 0 or len(_calls) < self._event_limit: self._calls.append( {'method':'track', ...
kvs6rj/cs3240-labdemo
helper.py
Python
mit
61
0.032787
__autho
r__ = 'k-sthan(II)' def greeting(msg):
print(msg)
nephthys/insidetags
functions.py
Python
agpl-3.0
5,173
0.010632
#-*- encoding: utf-8 -*- """ Copyright (c) 2010 Camille "nephthys" Bouiller <aftercem@gmail.com> InsideTags 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 License, or (at your opti...
hashtags = '' if tags: tags = tags.replace(',', '') new_tags = list() for tag in tags.split(): new_tags.append('#%s' % tag) hashtags = ' '.join(new_tags) if len(tweet) > 140: title = truncate_chars(title, 140-4-len(url)) tweet = '%s %s' % (title...
Api(username=TWITTER_LOGIN, password=TWITTER_PASS) api.PostUpdates(tweet) return url def twitterfy(text): ''' Parse links, @replies and #hashtags Source : http://teebes.com/blog/17/simple-python-twitter-rss-feed-parser ''' text = re.sub(r'(http://(\w|\.|/|\?|=|%|&)+)', \ lam...
grensjo/borg-summon
test/test_config_parser.py
Python
mit
1,894
0.000528
import pytest from unittest.mock import patch from borg_summon import config_parser from .util import mock_globbing, mock_m
ultiple_opens def test_merge(): d1 = { 'a': 'a', 'b': { 'c': 'c', 'd': [1, 2, 3], 'e': [1, 2, 3], }, 'c': { 'd': 3, }, 'd': 3, } d2 = { 'b': { ...
, 'b': { 'c': 'C', 'd': [1, 2, 3, 3, 4, 5], 'e': 0, }, 'c': 0, 'd': 'd', 'g': 'g', } config_parser.merge(d1, d2) assert str(d1) == str(res) def test_cyclic_include(): mock_globbing() m_...
stdweird/aquilon
tests/broker/test_del_disk.py
Python
apache-2.0
2,362
0.00127
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
-type", "type-does-not-exist"] out = self.badrequesttest(command) self.matchoutput(out, "type-does-not-exist is not a valid controller type", command) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestDelDisk) un...
.TextTestRunner(verbosity=2).run(suite)
paulopinda/simplemooc
simplemooc/courses/migrations/0002_auto_20160625_1845.py
Python
gpl-2.0
454
0.002203
# -*- coding: utf-8 -*- # Generated by Django
1.9 on 2016-06-25 18:45 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='course', options={'ordering...
ame'], 'verbose_name': 'Curso', 'verbose_name_plural': 'Cursos'}, ), ]
mileswwatkins/billy
billy/models/feeds.py
Python
bsd-3-clause
5,523
0.000362
import re import urlparse import datetime from django.template.defaultfilters import truncatewords from billy.core import mdb as db, feeds_db, settings from .base import Document from .metadata import Metadata class FeedEntry(Document): collection = feeds_db.entries def __init__(self, *args, **kw): ...
continue summary = re.sub(entity_string, replacer, summary) hyperlinked_spans.append(match.span())
# For entity_strings, us modelinstance.display_name strings. _entity_display_names = [] for _id in _entity_ids: collection_name = entity_types[_id[2]] + 's' collection = getattr(billy_db, collection_name) if collection_name == 'legislators': ...
molliewebb/aston
aston/tracefile/AgilentMS.py
Python
gpl-3.0
11,532
0.002168
# -*- coding: utf-8 -*- import os.path as op import gzip import io import struct from datetime import datetime from xml.etree import ElementTree import numpy as np import scipy.sparse from aston.resources import cache from aston.trace.Trace import AstonSeries, AstonFrame from aston.tracefile.TraceFile import TraceFile...
cols = np.empty(tot_pts, dtype=int) vals = np.empty(tot_pts, dtype=np.int32) times = np.empty(nscans) for scn in range(nscans): npos = f.tell() + 2 * struct.unpack('>H', f.read(2))[0] # the samp
ling rate is evidentally 60 kHz on all Agilent's MS's times[scn] = struct.unpack('>I', f.read(4))[0] / 60000. f.seek(f.tell() + 12) npts = rowst[scn + 1] - rowst[scn] mzs = struct.unpack('>' + npts * 'HH', f.read(npts * 4)) # there's some bug in the numpy im...
r3tard/BartusBot
lib/parsedatetime/tests/TestComplexDateTimes.py
Python
apache-2.0
3,487
0.009464
""" Test parsing of complex date and times """ import unittest, time, datetime import parsedatetime as pdt class test(unittest.TestCase): @pdt.tests.assertEqualWithComparator def assertExpectedResult(self, result, check, **kwargs): return pdt.tests.compareResultByTimeTuplesAndFlags(result, check, **...
ssertExpectedResult(self.cal.parse('08/25/2006 5pm', start), (target, 3)) self.assertExpectedResult(self.cal.parse('5pm on 08.25.2006', start), (target, 3)) self.assertExpectedResult(self.cal.parse('5pm August 25, 2006', start), (target,
3)) self.assertExpectedResult(self.cal.parse('5pm August 25th, 2006', start), (target, 3)) self.assertExpectedResult(self.cal.parse('5pm 25 August, 2006', start), (target, 3)) self.assertExpectedResult(self.cal.parse('5pm 25th August, 2006', start), (target, 3)) self.assertExpectedResu...
hanzz/spectrum
spectrumctl/spectrum/__init__.py
Python
gpl-2.0
883
0.00453
# -*- coding: utf
-8 -*- # # This file is
part of spectrumctl. See spectrumctl.py for a description. # # Copyright (C) 2009, 2010 Mathias Ertl # # Spectrumctl 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 you...
bverdu/onDemand
onDemand/plugins/zigbee/light.py
Python
agpl-3.0
95
0.021053
'''
Created on 19 nov. 2015 @author: Bertrand Verdu ''' if __name__ == '__main__': pass
eamoncaddigan/Leverage
setup.py
Python
agpl-3.0
1,490
0.000671
import os from setuptools import find_packages,
setup from pip.req import parse_requirements with open(os.path.join(os.path.dirname(__file__), 'README.md')
) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) # parse_requirements() returns generator of pip.req.InstallRequirement objects install_reqs = parse_requirements('requirements.txt', session=False) # reqs is...
commaai/openpilot
selfdrive/hardware/tici/test_agnos_updater.py
Python
mit
595
0.011765
#!/usr/bin/env python3 import json import os import unittest impo
rt requests AGNOS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))) MANIFEST = os.path.join(AGNOS_DIR, "agnos.json") class TestAgnosUpdater(unittest.TestCase): def test_manifest(self): with open(MANIFEST) as f: m = json.load(f) for img in m: r = requests.head(img['url']) r....
ent-Type'], "application/x-xz") if not img['sparse']: assert img['hash'] == img['hash_raw'] if __name__ == "__main__": unittest.main()
brandonmbare/csbuild
csbuild/_gui.py
Python
mit
88,329
0.0338
# coding=utf-8 import functools import re import stat import sys if sys.version_info >= (3,0): import io StringIO = io.StringIO else: import cStringIO StringIO = cStringIO.StringIO import csbuild from . import log try: from PyQt5 import QtCore, QtGui, QtWidgets QMainWindow = QtWidgets.QMainWindow QApplication =...
= False self.renderParent = renderParent self.lastUpdate = 0 def setChildrenShowing(self, showing): self.m_childrenShowing = showing def childrenShowing(self): return self.m_childrenSh
owing def setStartTime(self, startTime): self.startTime = startTime self.lastUpdate = time.time() def setBuildEnd(self, buildEnd): self.buildEnd = buildEnd def setLinkStart(self, linkStart): self.linkStart = linkStart def setLinkQueueStart(self, linkQueueStart): self.linkQueueStart = linkQueueStart ...
niavok/perroquet
utils/reindent.py
Python
gpl-3.0
8,897
0.001236
#! /usr/bin/env python # Released to the public domain, by Tim Peters, 03 October 2000. """reindent [-d][-r][-v] path ... -d Dry run. Analyze, but don't make any changes to, files. -r Recurse. Search for all .py files in subdirectories too. -v Verbose. Print informative msgs; else no output. Change ...
lname) and not os.path.islink(fullname)) or name.lower().endswith(".py")): check(fullname) return if verbose: print "checking", file, "...", try: f = open(file) except IOError, msg: errprint("%s: I/O Error: %s" % (f...
print "But this is a dry run, so leaving it alone." if not dryrun: bak = file + ".bak" if os.path.exists(bak): os.remove(bak) os.rename(file, bak) if verbose: print "renamed", file, "to", bak f = open(file, ...
chrisbarr/bilious-rutabaga
bucket_lister/__init__.py
Python
mit
204
0.009804
from boto.s3.connection import S3Connection def main(): conn = S3Co
nnection() buc
kets = conn.get_all_buckets() for b in buckets: print b.name if __name__ == "__main__": main()
AustereCuriosity/astropy
astropy/io/misc/pickle_helpers.py
Python
bsd-3-clause
3,779
0.000265
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from ...extern import ...
The filename
or file into which the `object` should be pickled. If a file object, it should have been opened in binary mode. usecPickle : bool If True (default), the :mod:`cPickle` module is to be used in place of :mod:`pickle` (cPickle is faster). This only applies for python 2.x. protocol : int or...
wvangeit/AllenSDK
doc_template/examples/data_api_client_ex2.py
Python
gpl-3.0
197
0
from gene_acronym_query
import GeneAcronymQuery query = GeneAcronymQuery() gene_info = query.get_data('ABAT') for gene in gene_info: print "%s (%s)" % (gene['name'], gene['organism']['
name'])
galbramc/gpkit
gpkit/tests/t_model.py
Python
mit
14,190
0.001339
"""Tests for GP and SP classes""" import math import unittest import numpy as np from gpkit import (Model, Monomial, settings, VectorVariable, Variable, SignomialsEnabled, ArrayVariable) from gpkit.geometric_program import GeometricProgram from gpkit.small_classes import CootMatrix from gpkit.feasibi...
0 + 3*x2, [x1 >= 10., x2 >= 15.]) sol = m.solve(solver=self.solver, verbosity=0) self.assertAlmostEqual(sol["cost"]/245., 1, self.ndig) def test_feasibility_gp_(self): x = Variable('x') m = Model(x, [x**2 >= 1, x <= 0.5]) self.assertRaises(RuntimeWarning, m.solve, verbosity=...
fm = feasibility_model(m, "max") sol1 = fm.solve(verbosity=0) fm = feasibility_model(m, "product") sol2 = fm.solve(verbosity=0) self.assertTrue(sol1["cost"] >= 1) self.assertTrue(sol2["cost"] >= 1) def test_terminating_constant_(self): x = Variable('x') ...
freedomboxtwh/Plinth
plinth/__init__.py
Python
agpl-3.0
750
0
# # This file is part of Plinth. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
anty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program.
If not, see <http://www.gnu.org/licenses/>. # """ Plinth package init file """ __version__ = '0.13.1'
bioxfu/circRNAFinder
src/SeqAnnoDownloadBuild.py
Python
gpl-3.0
7,557
0.025275
#! /usr/bin/env python import argparse, re, os parser = argparse.ArgumentParser(description = 'Download genome/transcript sequences and gene annotations') parser.add_argument('species', choices=['hg19','mm10','TAIR10'], help='choose a species (Human, Mouse, Arabidopsis)') parser.add_argument('-d', '--download', action...
tf.build)' % (args.species, args.species) gtf_build(args.species+'.gtf', args.species+'.gtf.buil
d') else: print 'please specify -g/--genome or -t/--transcriptome or -a/--annotation' else: print 'please specify -d/--download or -b/--build'
nfedera/rg3-youtube-dl
youtube_dl/compat.py
Python
unlicense
21,183
0.001275
from __future__ import unicode_literals import binascii import collections import email import getpass import io import optparse import os import re import shlex import shutil imp
ort socket import subprocess import sys import itertools import xml.etree.ElementTree try: import urllib.reque
st as compat_urllib_request except ImportError: # Python 2 import urllib2 as compat_urllib_request try: import urllib.error as compat_urllib_error except ImportError: # Python 2 import urllib2 as compat_urllib_error try: import urllib.parse as compat_urllib_parse except ImportError: # Python 2 ...
MDSLab/s4t-iotronic
iotronic/common/keystone.py
Python
apache-2.0
5,025
0
# coding=utf-8 # # 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 # di...
region_name=CONF.keystone.region_name, auth_url=auth_url) except ksexception.Unauthorized: raise exception.KeystoneUnauthorized() except ksexception.AuthorizationFailure as err: raise exception.KeystoneFailure(_('Could not authorize in Keystone:' ...
) def get_keystone_url(auth_url, auth_version): """Gives an http/https url to contact keystone. Given an auth_url and auth_version, this method generates the url in which keystone can be reached. :param auth_url: a http or https url to be inspected (like 'http://127.0.0.1:9898/'). :param...
LeastAuthority/txkube
src/txkube/_memory.py
Python
mit
25,882
0.001468
# Copyright Least Authority Enterprises. # See LICENSE for details. """ An in-memory implementation of the Kubernetes client interface. """ from json import loads import attr from pyrsistent import InvariantException, PClass, field, pset from zope.interface import Interface, implementer from twisted.python.url im...
) class AdHocAgency(object): """ ``AdHocAgency`` implements some object changes which I observed to happen on a real Kubernetes server while I was working on various parts of txkube. No attempt at completeness attempted. The system for selecting changes to implement is to run into im
portant inconsistencies between this and a real Kubernetes while developing other features and then fix those inconsistencies. Perhaps in the future this will be replaced by something with less of an ad hoc nature. """ model = attr.ib() def before_create(self, state, obj): return o...
dhodhala88/Bosch1
weblate/trans/tests/test_models.py
Python
gpl-3.0
23,236
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # 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, eithe...
) def create_ts(self, suffix=''): return self._create_subproject( 'ts', 'ts{0}/*.ts'.format(suffix), ) def create_iphone(self): return self._create_subproject( 'strings', 'iphone/*.lproj/Localizable.strings', ) def create_...
'android/values/strings.xml', ) def create_json(self): return self._create_subproject( 'json', 'json/*.json', ) def create_json_mono(self): return self._create_subproject( 'json', 'json-mono/*.json', 'json-mono/en...
eduNEXT/edx-platform
lms/djangoapps/instructor_task/migrations/0003_alter_task_input_field.py
Python
agpl-3.0
396
0
# Generated by Django
1.11.21 on 2019-07-01 12:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instructor_task', '0002_gradereportsetting'), ] operations = [
migrations.AlterField( model_name='instructortask', name='task_input', field=models.TextField(), ), ]
collinstocks/eventlet
tests/greenpool_test.py
Python
mit
15,085
0.000133
import gc import os import random import eventlet from eventlet import hubs, greenpool, event, pools from eventlet.support import greenlets as greenlet, six import tests def passthru(a): eventlet.sleep(0.01) return a def passthru2(a, b): eventlet.sleep(0.01) return a, b def raiser(exc): raise...
ious send at all def resume(): return 'resumed' e2 = pool.spawn(resume) self.assertEqual(e2.wait(), 'resumed') # we should be able to get out the thing we put in there, too self.assertEqual(tp.get(), 'wakeup') gt.wait() def test_spawn_n_2(self): ...
] def foo(a): r.append(a) gt = p.spawn(foo, 1) self.assertEqual(p.free(), 1) gt.wait() self.assertEqual(r, [1]) eventlet.sleep(0) self.assertEqual(p.free(), 2) # Once the pool is exhausted, spawning forces a yield. p.spawn_n(foo, 2) ...
JockeTF/fimfarchive
tests/tasks/conftest.py
Python
gpl-3.0
2,907
0
""" Common task fixtures. """ # # Fimfarchive, preserves stories from Fimfiction. # Copyright (C) 2020 Joakim Soderlund # # 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 t...
def __init__(self): """ Constructor. """ self.stories: Dict[int, Story] = dict() def add(self, key, date, flavors=(), data=Empty): """ Adds a story to the fetcher. """ meta = { 'id': key, 'title': f't{key}', 'date_...
hapters': [ {'id': key}, ], } if data is Empty: text = f'd{key}' data = text.encode() story = Story( key=key, fetcher=self, meta=meta, data=data, flavors=flavors, ) ...
nutszebra/ddp
illust2vecNC.py
Python
mit
4,789
0.019661
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import argparse import os, sys, re import random from time import time import cv2 import numpy as np import chainer from chainer import cuda import chainer.functions as F import overwrite from chainer.functions import caffe """ off...
[u'conv2_1'], [u'conv2_1']), (u'pool2', [u'conv2_1'], [u'pool2']), (u'conv3_1', [u'pool2'], [u'conv3_1']), (u'relu3_1', [u'conv3_1'], [u'conv3_1']), (u'conv3_2', [u'conv3_1'], [u'conv3_2']), (u'relu3_2', [u'conv3_2'], [u'conv3_2']), (u'pool3', [u'conv3_2'], [u'pool3']), (u'conv4_1', [u'pool3'], [u'conv
4_1']), (u'relu4_1', [u'conv4_1'], [u'conv4_1']), (u'conv4_2', [u'conv4_1'], [u'conv4_2']), (u'relu4_2', [u'conv4_2'], [u'conv4_2']), (u'pool4', [u'conv4_2'], [u'pool4']), (u'conv5_1', [u'pool4'], [u'conv5_1']), (u'relu5_1', [u'conv5_1'], [u'conv5_1']), (u'conv5_2', [u'conv5_1'], [u'conv5_2']), (u'relu5...
UdK-VPT/Open_eQuarter
mole/extensions/prop_buildings/oeq_HHRS.py
Python
gpl-2.0
1,148
0.008711
# -*- coding: utf-8 -*- import os,math from qgis.core import NULL from mole import oeq_global from mole.project import config from mole.extensions import OeQExtension from mole.stat_corr import rb_contemporary_base_uvalue_by_building_age_lookup def calculation(self=None, parameters={},feature = None): from math i...
', layer_name= 'Average Heating Hours', extension_filepath=os.path.join(__file__), colortable = os.path.join(os.path.splitext(__file__)[0] + '.qml'), field_id='HHRS', source_type='none', par_in=[], sourcelayer_name=config.data_layer_name, targetlayer_name=config.data_layer_name, acti...
rs", evaluation_method=calculation) extension.registerExtension(default=True)
nens/model-databank
model_databank/conf.py
Python
gpl-3.0
1,241
0
from django.conf import settings from appconf import AppConf class ModelDatabankAppConf(AppConf): """App specific settings. Overridable in global settings. DATA_PATH: path to the real mercurial repositories; these should never be manipulated directly. Active repositories are symlinked in the ...
MAX_REVISIONS_PER_PAGE: maximum number of revisions per page. """
DATA_PATH = "/tmp/model_databank_repositories" SYMLINK_PATH = "/tmp/model_databank" UPLOAD_PATH = "/tmp/uploads" ZIP_EXTRACT_PATH = "/tmp/extracted_zip_files/" DOWNLOAD_PATH = "/tmp/downloads" REPOSITORY_URL_ROOT = 'http://127.0.0.1:8012' MAX_REVISIONS = 500 MAX_REVISIONS_PER_PAGE = 100 ...
yanheven/nova
nova/tests/functional/v3/test_deferred_delete.py
Python
apache-2.0
1,610
0
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
# 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 nova.tests.functional.v3 import test_servers class DeferredDeleteSampleJsonTests(test_servers.S
erversSampleBase): extension_name = "os-deferred-delete" def setUp(self): super(DeferredDeleteSampleJsonTests, self).setUp() self.flags(reclaim_instance_interval=1) def test_restore(self): uuid = self._post_server() response = self._do_delete('servers/%s' % uuid) r...
cloud-io/CloudUp
src/admin_views.py
Python
mit
2,370
0.007173
from db_utils import deleteLinksByHost from db_utils import deleteHost from db_utils import addNewHost from db_utils import getAllHosts from error_message import showErrorPage from error_message import ErrorMessages import utils import webapp2 from google.appengine.api import users from google.appengine.ext import ndb...
injaEnvironment() class AddHost(webapp2.RequestHandler): def get(self): """ descripion: adds a new host to the database, and redirect to '/' params: name - host name interval - pinging interval for all the links belonging to the host.
response: redirect to '/admin' """ name = self.request.get('name') if name is None or len(name) == 0: showErrorPage(self, ErrorMessages.invalidHostName()) return if ndb.Key('Host', name).get() is not None: showErrorPage(self, ErrorMessages.duplicatingHostName()) retu...
classner/barrista
tests.py
Python
mit
108,780
0.000276
"""Unittests for the barrista project.""" # pylint: disable=F0401, C0330, C0302, C0103, R0201, R0914, R0915, W0212 # pylint: disable=no-name-in-module, no-member import unittest import logging logging.basicConfig(level=logging.WARN) try: import cv2 # pylint: disable=W0611 CV2_AVAILABLE = True except ImportEr...
predict_inputs=['data'],
predict_input_shapes=[[10, 3]]) layers = [] conv_params = {'Convolution_kernel_size': 3, 'Convolution_num_output': 32, 'Convolution_pad': 1} layers.append(ConvolutionLayer(**conv_params)) layers.append(ReLULayer()...
uggla/alexandria
alexandria/drivers.py
Python
apache-2.0
4,848
0.010111
# coding=utf-8 import pprint import config import json import urllib import requests class Driver(object): def __init__(self): self.driver_type = self.__class__.__name__ # Get credentials from conf files for CMDB pass def get_driver_type(self): return self.driver_type ...
config.alexandria.conf_file.get_driver_parameters("itop", "endpoint") request = '{"operation":"core/create","comment":"Synchronization from Alexandria","class":"Server","output_fields":"id,name,ram", "fields":{"org_id": "3","name":"' + ci.data["Name"] + '","ram":"' +
format((ci.data["MemorySummary"])["TotalSystemMemoryGiB"]) + '","serialnumber":"' + ci.data["SerialNumber"] + '"}}' urlparam = {'version' : '1.0', 'auth_user' : username, 'auth_pwd' : password, 'json_data' : request } ...
warmerdam/plcompositor
oev_tools/ev_mosaic_viewer.py
Python
apache-2.0
9,675
0.007649
from gtk import * import sys import gview import string import gvutils import GtkExtra import time import os import gviewapp import gvplot import gdal sys.path.append('.') import ev_profile from quality_hist_tool import QualityHistogramROITool LYR_GENERIC = 0 LYR_LANDSAT8 = 1 LYR_SOURCE_TRACE = 2 LYR...
ustment = GtkAdjustment(0.0, 0.0, 1.0, 0.05, 0.05, 0.05) self.min_adjustment.connect('value-changed',self.adjustment_cb) self.min_slider = GtkHScale(self.min_adjustment) self.min_slider.set_digits(3) hbox.pack_start(self.min_slider) self.min_entry = GtkEntry(maxlen=8)
self.min_entry.connect('activate',self.entry_cb) self.min_entry.connect('leave-notify-event',self.entry_cb) self.min_entry.set_text('0.0') hbox.pack_start(self.min_entry,expand=FALSE) # ------ Quality Scale Max ------- hbox = GtkHBox(spacing=5) vbox.pack_start(hbox) ...
ncos/lisa
src/lisa_drive/scripts/venv/lib/python3.5/site-packages/pip-10.0.1-py3.5.egg/pip/_vendor/cachecontrol/compat.py
Python
mit
724
0
try: from urllib.parse import urljoin except ImportError: fro
m urlparse import urljoin try: import cPickle as pickle except ImportError: import pickle # Handle the case where the requests module has been patched to not have # urllib3 bundled as
part of its source. try: from pip._vendor.requests.packages.urllib3.response import HTTPResponse except ImportError: from pip._vendor.urllib3.response import HTTPResponse try: from pip._vendor.requests.packages.urllib3.util import is_fp_closed except ImportError: from pip._vendor.urllib3.util ...
jgresula/jagpdf
code/test/apitest/py/defaultfont2.py
Python
mit
952
0.003151
#!/usr/bin/env python # Copyright (c) 2005-2009 Jaroslav Gresula # # Distributed under the MIT license (See accompanying file # LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) # import jagpdf import jag.testlib as testlib def test_main(argv=None): doc = testlib.create_test_doc(argv, 'defaultfont2.pdf') ...
te_save() courier = doc.font_load('standard;name=Courier;size=10') canvas.text_fo
nt(courier) canvas.text(10, 10, 'written in Courier') canvas.state_restore() doc.page().canvas().text(10, 30, 'written in the default font') doc.page_end() doc.page_start(200, 36) doc.page().canvas().text(10, 10, 'written in the default font') doc.page_end() doc.finalize() if __name_...
minlexx/xnovacmd
ui/xnova/xn_page_cache.py
Python
gpl-2.0
4,643
0.002585
import os import pathlib import locale import time from . import xn_logger logger = xn_logger.get(__name__, debug=False) # Incapsulates downloaded pages storage # keeps all downloaded files in ./cache # the file first requested from this cache, # and only if get() returns None, it will be # downloaded over network ...
'Encoding error in
[{0}], skipped: {1}'.format(subitem.name, str(ude))) logger.info('Loaded {0} cached pages.'.format(num_loaded)) # ensure that image cache dir also exists cache_dir = pathlib.Path(self._img_cache_dir) if not cache_dir.exists(): try: cache_dir.mkdir(parents=Tru...
spectrumone/online-shop-template
myshop/cart/cart.py
Python
mit
3,017
0.001326
f
rom decimal import Decimal from django.conf import settings from coupons.models import Coupon from shop.models import Product class Cart(object): def __init__(self, request): """ initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART...
self.session[settings.CART_SESSION_ID] = {} self.cart = cart #store current applied coupon self.coupon_id = self.session.get('coupon_id') def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update it quantity """ produc...
scott-maddox/openbandparams
src/openbandparams/examples/advanced/GaInAsSb_on_GaSb/Plot_Bandgap_vs_Lattice_Constant_of_Quaternary3.py
Python
agpl-3.0
3,726
0.001879
# # Copyright (c) 2013-2014, Scott J Maddox # # This file is part of openbandparams. # # openbandparams 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 License, or # ...
ct(linewidth=0, fc='white', alpha=0.9), textcoords='offset points') for x, y, label in zip(xs, y_L, labels): ax.annotate(label, xy=(x, y), xytext=(-5, 5), ha='right', va='bottom', bbox=dict(linewidth=0, fc=
'white', alpha=0.9), textcoords='offset points') # plot the quaternary indices = numpy.arange(100) fractions = numpy.linspace(0, 1, 100) x = numpy.empty(100, dtype=numpy.float) y_Gamma = numpy.empty(100, dtype=numpy.float) y_X = numpy.empty(100, dtype=numpy.float) y_L = numpy.empty(100, dtype=numpy.flo...
shankari/e-mission-server
emission/incomplete_tests/TestCarbon.py
Python
bsd-3-clause
13,159
0.012387
from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import # Standard imports from future import standard_library standard_library.install_aliases() from builtins import * from past.utils import old_div import unittest import json...
lf.busExpect = 2162.668467546699 self.busCarbon = old_div(267.0,1609) self.airCarbon = old_div(217.0,1609) self.driveCarbon = ol
d_div(278.0,1609) self.busOptimalCarbon = old_div(92.0,1609) self.now = datetime.now() self.dayago = self.now - timedelta(days=1) self.weekago = self.now - timedelta(weeks = 1) for section in self.SectionsColl.find(): section['section_start_datetime'] = self.dayago section['section_end...
praetorian-inc/pentestly
modules/reporting/list.py
Python
gpl-3.0
1,569
0.003824
from recon.core.module import BaseModule import codecs import os class Module(BaseModule): meta = { 'name': 'List Creator', 'author': 'Tim Tomes (@LaNMaSteR53)', 'description': 'Creates a file containing a list of records from the database.', 'options': ( ('table', 'hos...
NULL' % (column) if not self.options['nulls'] else '' unique = 'DISTINCT ' if self.options['unique'] else '' values = (unique, column, table, nulls) query = 'SELECT %s"%s" FROM "%s"%s ORDER BY 1' % values rows = self.query(query) for row in [x[0] for x in rows...
print(row) self.output('%d items added to \'%s\'.' % (len(rows), filename))
mfittere/SixDeskDB
sixdeskdb/davsturns.py
Python
lgpl-2.1
28,687
0.049395
# da vs turns module import numpy as np from scipy import optimize import matplotlib.pyplot as pl import glob, sys, os, time from deskdb import SixDeskDB,tune_dir,mk_dir import matplotlib # ------------- basic functions ----------- def get_divisors(n): """finds the divisors of an integer number""" large_divisors = ...
ngmax+1))#step in angle in rad ampstep=np.abs((s[s>0][1])-(s[s>0][0])) ftype=[('seed',int),('tunex',float),('tuney',float),('turn_max',int),('dawtrap',float),('dastrap',float),('dawsimp',float),('dassimp',float),('dawtraperr',float),('dastraperr',float),('dastraperrep',float),('dastraperrepang',float),('das
traperrepamp',float),('dawsimperr',float),('dassimperr',float),('nturn',float),('tlossmin',float),('mtime',float)] l_turnstep=len(np.arange(turnstep,tmax,turnstep)) daout=np.ndarray(l_turnstep,dtype=ftype) for nm in daout.dtype.names: daout[nm]=np.zeros(l_turnstep) dacount=0 currentdawtrap=0 currenttlos...
karlin13/LzCoinJupJup
JupJup/Present/__init__.py
Python
mit
37
0
fr
om JupJup.Present import col
lector
stesie/PyPC-NC
Control/MainWindow.py
Python
gpl-3.0
11,785
0.02919
from PySide import QtGui, QtCore import os, struct, time class ControlMainWindow(QtGui.QMainWindow): _storeButtonUsed = False _gv = None _parser = None _inter = None _workpiecePos = [ 5, 5, 5 ] _originOffset = [ 0, 0 ] _polarCorrection = [ 1, 0 ] _debounce = None def __init__(self, chatBackend): super(Cont...
self._ui.progress.setMaximum(1) self._ui.progress.setValue(0) @QtCore.Slot() def importGCode(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Import G-Code', '.') if filename[0] == '': return self.importGCodeFromFile(filename[0]) def importGCodeFromFile(self, filename): parser = GCode.GCode...
emoveComments() parser.removeInlineComments() parser.removeBlockSkipLines() parser.normalizeAddressWhitespace() parser.normalizeLeadingZeros() parser.readSequenceNumbers() self._parser = parser @QtCore.Slot() def run(self): if not self._machine.machineStatus().status() & 0x04: reply = QtGui.QMessag...
mejedi/tarantool
test/replication-py/cluster.test.py
Python
bsd-2-clause
13,538
0.001847
import os import sys import re import yaml import uuid import glob from lib.tarantool_server import TarantoolServer ## Get cluster uuid cluster_uuid = '' try: cluster_uuid = yaml.load(server.admin("box.space._schema:get('cluster')", silent = True))[0][1] uuid.UUID('{' + cluster_uuid + '}') print 'o...
ertion if replace _cluster tuple for remote server' print '-----------------------
--------------------------------------' # Test that insert is OK new_uuid = '0d5bd431-7f3e-4695-a5c2-82de0a9cbc95' server.admin("box.space._cluster:insert{{5, '{0}'}}".format(new_uuid)) server.admin("box.info.vclock[5] == nil") # Replace with the same UUID is OK server.admin("box.space._cluster:replace{{5, '{0}'}}".f...
YixuanLi/geo-tweet
twitter-timeline/get_non_locator_timeline.py
Python
gpl-2.0
5,282
0.029156
# -*- coding: utf-8 -*- # __author__: Yixuan LI # __email__: yl2363@cornell.edu import os import json import re from optparse import OptionParser import tweepy import time class UserTimeline: def __init__(self,inputDir,outputDir): self
.inputDir = inputDir self.outputDir = ou
tputDir os.system("mkdir -p %s"%(outputDir)) # Get the names of the files under the input directory and save them in a list self.fileList = os.listdir(inputDir) print self.fileList self.userHash = {} # [key,value] pair to record the unique users in the tweets self.uniqueUserCount = 0 # count unique ...
capoe/espressopp.soap
src/analysis/TotalVelocity.py
Python
gpl-3.0
2,733
0.011343
# Copyright (C) 2014 Pierre de Buyl # Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and...
e()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, analysis_TotalVelocity, system) def compute(self): return self.cxxclass.compute(self) def reset
(self): return self.cxxclass.reset(self) if pmi.isController : class TotalVelocity(Observable): __metaclass__ = pmi.Proxy pmiproxydefs = dict( cls = 'espressopp.analysis.TotalVelocityLocal', pmicall = [ "compute", "reset" ], pmiproperty = ["v"] ...
DeveloperMal/wger
wger/manager/api/resources.py
Python
agpl-3.0
6,864
0.000874
# -*- coding: utf-8 -*- # This file is part of wger
Workout Manager. # # wger Workout Manager 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 License, or # (at your option) any later version. # # wger Workout Manager is distribut...
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 Affero General Public License from tastypie import fields from tastypie.authentication import ( ApiKeyAuthenti...
balazssimon/ml-playground
udemy/Machine Learning A-Z/Part 2 - Regression/Section 5 - Multiple Linear Regression/backward_elimination_manual.py
Python
apache-2.0
1,681
0.030934
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # One hot encoding from sklearn.preprocessing impor...
# Step 5 regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() # Step 3 regressor_OLS.summary() # Step 4 X_opt = X[:,[0,3,5]] # Step 5 regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() # Step 3 regressor_OLS.summary() # Step 4 X_opt = X[:,[0,3]] # Step 5 regressor_OLS = sm.OLS(endog = y, exog = X_o...
OLS.summary() # Finished
v4nz666/7drl2017
RoguePy/UI/__init__.py
Python
gpl-3.0
70
0
from UI import UI from View import View imp
ort Elem
ents import Colors
mosquito/aio-pika
docs/source/rabbitmq-tutorial/examples/3-publish-subscribe/receive_logs.py
Python
apache-2.0
1,094
0
import asyncio from aio_pika import connect, IncomingMessage, ExchangeType loop = asyncio.get_event_loop() async def on_message(message: IncomingMessage): async with message.process(): print("[x] %r" % mess
age.body) async def main(): # Perform connection connection = await connect( "amqp://guest:guest@localhost/", loop=loop ) # Creating a channel channel = awa
it connection.channel() await channel.set_qos(prefetch_count=1) logs_exchange = await channel.declare_exchange( "logs", ExchangeType.FANOUT ) # Declaring queue queue = await channel.declare_queue(exclusive=True) # Binding the queue to the exchange await queue.bind(logs_exchange) ...
halbbob/dff
modules/builtins/info.py
Python
gpl-2.0
5,653
0.012383
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2011 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this...
+= "\n\t\tname: " + str(argument.name()) res += "\n\t\tdesc
ription: " + str(argument.description()) if argument.inputType() == Argument.Empty: res += "\n\t\tno input parameters" else: res += "\n\t\ttype: " + str(typeId.Get().typeToName(argument.type())) res += "\n\t\trequirement: " if argument.requirementType() == Argument.Optional:...
bennybauer/pinax-hello
runtests.py
Python
mit
1,274
0.000785
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "pinax.pinax_hello", "pinax.pinax_hello.tests" ], MIDD...
} }, SITE_ID=1, ROOT_URLCONF=
"pinax.pinax_hello.tests.urls", SECRET_KEY="notasecret", ) def runtests(*test_args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner ...
mathieudesro/toad
tasks/11-tensormrtrix.py
Python
gpl-2.0
4,911
0.007127
# -*- coding: utf-8 -*- from core.toad.generictask import GenericTask from lib.images import Images __author__ = "Mathieu Desrosiers, Arnaud Bore" __copyright__ = "Copyright (C) 2016, TOAD" __credits__ = ["Mathieu Desrosiers", "Arnaud Bore"] class TensorMrtrix(GenericTask): def __init__(self, subject): ...
i) # convert d
iffusion-weighted images to tensor images. def __produceTensors(self, source, encodingFile, iterWLS, mask=None): self.info("Starting DWI2Tensor from mrtrix using weighted linear least squares estimator.") tmp = self.buildName(source, "tmp") target = self.buildName(source, "tensor") ...
imphil/fusesoc
fusesoc/provider/coregen.py
Python
gpl-3.0
1,221
0.002457
import logging import os import shutil from fusesoc.provider.provider import Provider from fusesoc.utils import Launcher logger = logging.getLogger(__name__) class Coregen(Provider): def _checkout(self, local_dir): script_file = self.config.get('script_file') project_file = self.config.get('proj...
dir(local_dir): os.makedirs(local_dir) src_files = [script_file, project_file] if extra_files: src_files += extra_files.split() for f in
src_files: f_src = os.path.join(self.core_root, f) f_dst = os.path.join(local_dir, f) if os.path.exists(f_src): d_dst = os.path.dirname(f_dst) if not os.path.exists(d_dst): os.makedirs(d_dst) shutil.copyfile(f_src, f...
maciekswat/dolfin_1.3.0
site-packages/dolfin/common/plotting.py
Python
gpl-3.0
4,997
0.003602
# Copyright (C) 2008-2012 Joachim B. Haga and Fredrik Valdmanis # # This file is part of DOLFIN. # # DOLFIN is free software: you can redistribute it and/or modify # it under the
terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # DOLFIN is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FIT
NESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>. # # Modified by Martin Sandve Alnaes, 2008. # Modified by Anders Logg, 2008-2010. # #...
zmathe/WebAppDIRAC
Lib/WebHandler.py
Python
gpl-3.0
10,812
0.045135
from DIRAC import gLogger from DIRAC.Core.Security.X509Chain import X509Chain from DIRAC.Core.DISET.ThreadConfig import ThreadConfig from DIRAC.ConfigurationSystem.Client.Helpers import Registry from DIRAC.Core.DISET.AuthManager import AuthManager from WebAppDIRAC.Lib.SessionData import SessionData from WebAppDIRAC.Li...
for k in kwargs: setattr( self, k, kwargs[ k ] ) self.ok = True self.data = data def asyncWithCallback( method ): return tornado.web.asynchronous( method ) def as
yncGen( method ): return tornado.gen.coroutine( method ) class WebHandler( tornado.web.RequestHandler ): __disetConfig = ThreadConfig() __log = False #Auth requirements AUTH_PROPS = None #Location of the handler in the URL LOCATION = "" #URL Schema with holders to generate handler urls URLSCHEMA = ...
rehandalal/standup
standup/apps/api2/decorators.py
Python
bsd-3-clause
480
0
from functools import wraps from flask import current_app
, request from standup.errors import api_error def api_key_required(view): @wraps(view) def wrapper(*args, **kwargs): data = request.args if request.method == 'GET' else request.form api_key = data.get
('api_key', '') if api_key != current_app.config.get('API_KEY'): return api_error(403, 'Forbidden: Invalid API key.') return view(*args, **kwargs) return wrapper
hankcs/HanLP
hanlp/components/mtl/multi_task_learning.py
Python
apache-2.0
38,042
0.00276
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-06-20 19:55 import functools import itertools import logging import os from collections import defaultdict from copy import copy from itertools import chain from typing import Union, List, Callable, Dict, Optional, Any, Iterable, Tuple import numpy as np import torc...
tokenizer=encoder_transform.tokenizer, gradient_accumulation=gradient_accumulation, cache=isinstance(data, str), **config) # if prune: ...
# task_dataset: TransformDataset = task_dataloader.dataset # size_before = len(task_dataset) # task_dataset.prune(prune) # size_after = len(task_dataset) # num_pruned = size_before - size_after # logger.info(f'Pruned [yellow]...
michaelStettler/HISI
HISI/boundaries.py
Python
mit
16,880
0.005746
import numpy as np from scipy import signal import math def norm_matrix(matrix): for i in range(np.shape(matrix)[0]): if np.max(matrix[i]) <= 0: matrix[i] = matrix[i] else: matrix[i] /= np.max(matrix[i]) return matrix def pool_boundaries(boundaries, filter_size, coeff...
1, j:j + 2] -= pool[1, i + 1, j:j + 2] boundaries[2, i:i + 2, j] -= pool[2, i:i + 2, j] boundaries[3, i:i + 2, j + 1] -= pool[3, i:i + 2, j + 1] boundaries[boundaries < 0] = 0 return boundaries def rem_inner_seg_bound(input, boundaries): for i in range(np...
0] == 4: boundaries[0, i, j:j + 2] = 0 boundaries[1, i + 1, j:j + 2] = 0 boundaries[2, i:i + 2, j] = 0 boundaries[3, i:i + 2, j + 1] = 0 def choose_loc(x, y, dir): """ Return the position of the next pixel in function of the direction one want to ...
marrow/schema
marrow/schema/validate/geo.py
Python
mit
1,013
0.0385
from collections.abc import Sequence from numbers import Number from . import Validator, Length, Range, Instance from .compound import
All class Latitude(All): """Validate the given value as a number between -90 and +90 in decimal degrees, representing latitude.""" validators = [ Instance(Number), Range(-90, 90) ] latitude = Latitude() class
Longitude(All): """Validate the given value as a number between -180 and +180 in decimal degrees, representing longitude.""" validators = [ Instance(Number), Range(-180, 180) ] longitude = Longitude() class Position(All): """Validate the given value as any sequence of exactly two elements representing lat...
softcert/vsroom
vsroom/common/customoverview.py
Python
mit
1,942
0.003605
import time import collections from overviewbot import OverviewBot, Window def format_time(timestamp): return time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(timestamp)) class CustomWindow(Window): def __init__(self, input_key, *args, **keys): Window.__init__(self, *args, **keys) self.inpu...
rded(self, _): self._times.popleft() def _firstseen(self): if self._times: return format_time(self._times[0]) return None def _lastseen(self): if self._time
s: return format_time(self._times[-1]) return None class FirstSeen(_Seen): def value(self): return self._firstseen() class LastSeen(_Seen): def value(self): return self._lastseen() class CustomOverviewBot(OverviewBot): def aggregates(self): result = dict(Overvi...
arthurSena/processors
tests/test_hra.py
Python
mit
992
0.004036
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from processors.hra.extractors import _clean_identifie
r from processors.hra.extractors import _url_from_title # Tests def test_clean_identifier(): assert _clean_identifier('NCT12345678', prefix='NCT') == 'NCT12345678' assert _clean_identifier('12345678', prefix='NCT') == 'NCT12345678' assert _clean_identifier('ISRCTN12345678', prefix='ISRCTN') == 'ISRCTN123...
assert _clean_identifier('n/a', prefix='NCT') == None def test_url_from_title(): title = 'Longterm F/U study of BOTOX® in Idiopathic Overactive Bladder patients' expected_url = 'http://www.hra.nhs.uk/news/research-summaries/longterm-fu-study-of-botox-in-idiopathic-overactive-bladder-patients' assert _url_...
noironetworks/heat
heat/tests/openstack/senlin/test_receiver.py
Python
apache-2.0
4,398
0
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
bject): def __init__(self, id='s
ome_id'): self.id = id self.name = "SenlinReceiver" self.cluster_id = "fake_cluster" self.action = "CLUSTER_SCALE_OUT" self.channel = {'alarm_url': "http://foo.bar/webhooks/fake_url"} def to_dict(self): return { 'id': self.id, 'name': self.nam...
ZenifiedFromI2P/antisocial
bootstraps/forms.py
Python
gpl-3.0
426
0.011737
from django import forms attr = {'class': 'form-control'} class GroupSeedForm(forms.Form):
seed = forms.CharField(label='Seed', max_length=1337, initial='none', widget=forms.TextInput(attrs=attr)) class UserSeedForm(forms.Form): pseudonym = forms.CharField(label='Pseudonym', min_length=3, widget=forms.TextInput(attrs=attr)) password = forms.CharField(label='Password', widget=forms.PasswordInput(a...
BillBillBillBill/WishTalk-server
WishTalk/top/api/base.py
Python
mit
10,416
0.009482
# -*- coding: utf-8 -*- ''' Crea
ted on 2012-
7-3 @author: lihao ''' try: import httplib except ImportError: import http.client as httplib import urllib import time import hashlib import json import top import itertools import mimetypes ''' 定义一些系统变量 ''' SYSTEM_GENERATE_VERSION = "taobao-sdk-python-20151214" P_APPKEY = "app_key" P_API = "method" P_SESSION ...
syberkitten/Imap4SearchQueryParser
SearchParser.py
Python
gpl-3.0
16,261
0.011746
__author__ = 'Liam' import types def flag(func): func.is_flag = True return func class BadSearchOp(Exception): def __init__(self, value = "bad search operation"): self.value = value def __str__(self): return "BadSearchOp: %s" % self.value class ImapSearchQueryParser(object): "...
urrentIndex) if argument: self._update_command_list({'body': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "BODY" provided but with no argument in query list') def OP__CC(self,currentIndex=None): argument = self._get_command_argument(cur...
date_command_list({'cc': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "CC" provided but with no argument in query list') @flag def OP__DELETED(self,currentIndex=None): self._update_command_list({'deleted': True}, currentIndex) @flag def OP__D...
Binnette/StreetComplete
app/copyShopDescriptions.py
Python
gpl-3.0
1,324
0.036254
import os import re source_dir = "src/main/res/" target_dir = "../fastlane/metadata/android/" def copy_key_from_strings_xml_to_file(xml, key, filename): match = re.search("<string name=\"" + key + "\">\"?(.*?)\"?</string>", xml, re.DOTALL) if match: with open(filename, "w", encoding='utf8') as file: file.wri...
-9]',components[1]):
return None elif len(components) == 2: return components[1] elif len(components) == 3: return components[1] + "-" + components[2][1:] return None for dirname in sorted(os.listdir(source_dir)): locale = get_locale_from(dirname) if not locale: continue stringsfile = source_dir + dirname + "/strings.xml" i...
suutari/gitexpy
gitexpy/pack.py
Python
gpl-2.0
8,148
0.003436
import binascii import hashlib import mmap import struct import zlib from . import delta from .sixx import byte2int class Error(Exception): """Pack Error""" OBJ_TYPE_COMMIT = 1 OBJ_TYPE_TREE = 2 OBJ_TYPE_BLOB = 3 OBJ_TYPE_TAG = 4 OBJ_TYPE_OFS_DELTA = 6 OBJ_TYPE_REF_DELTA = 7 object_types = { 1: 'commit', ...
(4) != b'PACK': raise Error('Not a packfile: %s' % filename) self.version = struct.unpack('>L', self.__file.read(4))[0] if self.version != 2: raise Error( 'Version %d packfile is not supported: %s' % (self.version, filename)) self.__objectc...
read(4))[0] self.header_length = self.__file.tell() self.data = mmap.mmap( self.__file.fileno(), length=0, access=mmap.ACCESS_READ) self.object_offset_map = {} self.offset_id_map = {} self.offsets = [self.header_length] @property def filename(self): re...
terentjew-alexey/market-analysis-system
mas_tools/classes.py
Python
mit
5,267
0.001899
# -*- coding: utf-8 -*- import numpy as np def signal_to_class(data, n=2, normalize=True): """ Converts a list of signals to a n-dimensional list of classes [buy, .., sell]. Arguments n (int): Number of classes. normalize (bool): It normalizes to unity. False - the signal changes only the...
ass == 0: result = np.append(result, item[0]) elif _class == 1: result = np.append(result, 0.0) elif _class == 2: result = np.append(result, -item[2]) elif n == 6: for item in data: _clas
s = np.argmax(item) if _class == 0: result = np.append(result, 1.0) elif _class == 1: result = np.append(result, 0.66) elif _class == 2: result = np.append(result, 0.33) elif _class == 3: result = np.append(r...
TheClimateCorporation/conda-recipes
basemap/run_test.py
Python
apache-2.0
1,026
0.019493
import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') # from basemap/examples/daynight.py import numpy as np from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from datetime import datetime # example showing how to compute the day/night terminator and shade ...
# map shows through
. Use current time in UTC. date = datetime.utcnow() CS=map.nightshade(date) plt.title('Day/Night Map for %s (UTC)' % date.strftime("%d %b %Y %H:%M:%S")) print('test passed!')
joshishungry/artificial_intel
assignments/lab5/neural_net_tester.py
Python
apache-2.0
2,227
0.00449
#!/usr/bin/env python2.5 # # Unit tester for neural_net.py # import sys from neural_net import train, test,\ make_neural_net_basic,\ make_neural_net_two_layer,\ make_neural_net_challenging,\ make_neural_net_with_weights from neural_net_data import simple_data_sets,\ harder_data_sets,\ ch...
rint "Trained weights:" for w in nn.weights: print "Weight '%s': %f"%(w.get_name(),w.get_value()) print "Testing on %s test-data" %(name) result = test(nn, test_data, verbose=verbose) print "Accuracy: %f"%(result) if __name__=="__main__": t
est_names = ["simple"] if len(sys.argv) > 1: test_names = sys.argv[1:] for test_name in test_names: if test_name == "simple": # these test simple logical configurations main(make_neural_net_basic, simple_data_sets) elif test_name == "two_layer":...