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
Depado/MarkDownBlog
app/modules/blog/rss.py
Python
mit
1,049
0.000953
# -*- coding: utf-8 -*- from flask import request, url_for from sqlalchemy import desc from werkzeug.contrib.atom import AtomFeed from . import blueprint from .utils import requested_blog_user, make_external from app.models import Post @blueprint.route("/recent.atom") def rss
_feed(user_slug): blog_user = requested_blog_user(user_slug) if blog_user: feed = AtomFeed( '{user} Recent Articles'.format(user=blog_user.username), feed_url=request.url, url=request.url_root ) posts = blog_user.posts.order_by(desc(Post.pub_date)).lim...
content_type='html', author=post.user.username, url=make_external(url_for("blog.get", user_slug=user_slug, post_slug=post.title_slug)), updated=post.pub_date, published=post.pub_date) return feed.get_response() ...
endlessm/endless-ndn
eos_data_distribution/DirTools/test_class.py
Python
lgpl-3.0
742
0
import pytest from eos_data_distribution import DirTools from gi.repository import GLib ITER_COUNT = 10 class TestClass: @pytest.mark.timeou
t(timeout=3, method='thread') def test_0(self, tmpdir): loop = GLib.MainLoop() self.__called = 0 def cb_changed(M, p, m, f, o, evt, d=None, e=None): print('signal', e, p, f, o, evt, d) assert e == 'created' self.__called += 1 d = tmpdir.mkdir("nd...
d']] [d.mkdir(str(i)) for i in range(ITER_COUNT)] GLib.timeout_add_seconds(2, lambda: loop.quit()) loop.run() assert self.__called == ITER_COUNT
earthenv/mapotron
tile_handler.py
Python
bsd-3-clause
6,062
0.010887
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- import services import webapp2 import logging import cache import json import config_creds import ee_assets from google.appengine.api import images from google.appengine.api import urlfetch EE_TILE_URL = 'https://earthengine.googleapis.com/map/%s/%i/%i/%i?token=%s' cl...
ox = ee.Geometry(geodesic, None, False) logging.info('No tile meta, generating new map from %s ' % (ee_assets.layers[collection_id]["layers"][layer_id]["id"])) image = ee.Image(ee_assets.layers[collection_id]["layers"][layer_id]["id"]) tile_meta = ee_services.getMap( ...
image.mask(image.gt(0)).clip(bbox), ee_assets.layers[collection_id]["layers"][layer_id]["viz_params"], tile_meta_key) services.cacheResult({ "mapid": tile_meta["mapid"], "token":tile_meta["token"]}, ...
cgeoffroy/son-analyze
son-scikit/src/son_scikit/hl_prometheus.py
Python
apache-2.0
2,969
0
# Copyright (c) 2015 SONATA-NFV, Thales Communications & Security # 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 # #...
# other metric against it before the merge result = {} items_itr = prom_data._by_id.items() # pylint: disable=protected-access for id_index, all_metrics in items_itr: acc_ts = [] for elt in all_metrics: metric_name = elt['metric']['__name__']
index, data = zip(*elt['values']) index = [convert_timestamp_to_posix(z) for z in index] this_serie = pandas.Series(data, index=index) this_serie.name = metric_name acc_ts.append(this_serie) dataframe = pandas.concat(acc_ts, join='outer', axis=1) ...
RodFernandes/Python_USP_Curso_Ciencias_da_Computacao_1
bhaskara.py
Python
apache-2.0
506
0.018182
import math a=float(input('Digite o valor de A:')) b=float(input('Digite o valor de B:')) c=float(input('Digite o valor de C
:')) delta=(b**2)-4*a*c if delta < 0: print('esta equação não possui raízes reais') else: xPositivo = (-b + math.sqrt(delta)) / (2 * a) if delta == 0: print('a raiz desta equação é', xPositivo) else: if delta>0:
xNegativo = (-b - math.sqrt(delta)) / (2 * a) print('as raízes da equação são',xNegativo,'e',xPositivo)
astroJeff/dart_board
paper/scripts/acor_plot.py
Python
mit
2,539
0.016148
import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import dart_board from pandas import Series file_root = sys.argv[1] file_in = "../data/" + file_root + "_chain.npy" if len(sys.argv) == 2: delay = 200 else: delay = int(int(sys.argv[2]) / 100) chains =...
# Plot the
autocorrelation of 10 sample chains # for j in np.arange(10): # autocorr = np.zeros(N) # series = Series(data=chains[j,:,k]) # for i in np.arange(N): # autocorr[i] = Series.autocorr(series, lag=int(i*float(xmax-xmin)/N)) # ax[kx,ky].plot(np.linspace(xmin,xmax,N)*factor, auto...
joplen/svgplotlib
svgplotlib/SVG/Parsers.py
Python
bsd-3-clause
4,791
0.011271
#!/usr/bin/python # -*- coding: utf-8 -*- import re class SVGParseError(Exception): pass EOF = object() class Lexer: """ This style of implementation was inspired by this article: http://www.gooli.org/blog/a-simple-lexer-in-python/ """ Float = r'[-\+]?(?:(?:\d*\.\d+)|(?:\d+\.)|(?:\d+...
tespace (?P<value>[-\+]?\d*\.?\d*([eE][-\+]?\d+)?) # match float or int value (?P<unit>.+)? # match any chars \s* # ignore whitespace $ # match end of line """ angle_match = re.compile(angle_pattern, re.X).match def parseAngle(angle): ...
s """ SCALE = { "deg": 1, "grad": 1.11, "rad":57.30 } match = length_match(angle) if match is None: raise SVGParseError("Not a valid angle unit: '%s'" % angle) value = match.group('value') if not value: raise SVGParseError("Not a valid angle unit: '%s'" % an...
jtraver/dev
python/hashlib/md5.py
Python
mit
457
0.006565
#!/usr/bin/python import hashlib # perl ## http:
//stackoverflow.com/questions/9991757/sha256-digest-in-perl #use Digest::MD5 qw(md5_hex); #print md5_hex('[email protected]'), "\n"; perl_result = "cbc41284e23c8c7ed98f589b6d6ebfd6" md5 = hashlib.md5() md5.update('[email protected]') hex1 = md5.hexdigest() if hex1 == perl_result: print "ok" else: print "FA...
"FAIL hex1 = %s" % str(hex1)
datanel/navitia
source/jormungandr/jormungandr/interfaces/v1/Ptobjects.py
Python
agpl-3.0
4,241
0.001179
# coding=utf-8 # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility an...
uest to the responsive locomotion way of traveling! # # LICENCE: 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. # ...
distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with ...
rhefner1/ghidonations
pipeline/models.py
Python
apache-2.0
6,902
0.011011
#!/usr/bin/python2.5 # # Copyright 2010 Google 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...
ult=WAITING) # Retry behavior current_attempt = db.IntegerProperty(default=0, indexed=False) max_attempts = db.IntegerProperty(default=1, indexed=False) next_retry_time = db.DateTimeProperty(indexed=False) retry_message = db.TextProperty() # Root pipeline properties is_root_pipeline = db.BooleanProperty...
anProperty(indexed=False) @classmethod def kind(cls): return '_AE_Pipeline_Record' @property def params(self): """Returns the dictionary of parameters for this Pipeline.""" if hasattr(self, '_params_decoded'): return self._params_decoded if self.params_blob is not None: value_enco...
GoogleCloudPlatform/sap-deployment-automation
third_party/github.com/ansible/awx/awx/main/tests/unit/utils/test_safe_yaml.py
Python
apache-2.0
2,424
0.000413
# -*- coding: utf-8 -*- from copy import deepcopy import pytest import yaml from awx.main.utils.safe_yaml import safe_dump @pytest.mark.parametrize('value', [None, 1, 1.5, []]) def test_native_types(value): # Native non-string types should dump the same way that `yaml.safe_dump` does assert safe_dump(value) ...
'a': 'b', 'c': 'd'}) == '\n'.joi
n([ "!unsafe 'a': !unsafe 'b'", "!unsafe 'c': !unsafe 'd'", "" ]) def test_safe_marking(): assert safe_dump({'a': 'b'}, safe_dict={'a': 'b'}) == "a: b\n" def test_safe_marking_mixed(): assert safe_dump({'a': 'b', 'c': 'd'}, safe_dict={'a': 'b'}) == '\n'.join([ "a: b", ...
RedHatInsights/insights-core
insights/util/streams.py
Python
apache-2.0
3,293
0.001518
""" Module for executing a command or pipeline of commands and yielding the result as a generator of lines. """ import os import shlex import signal from contextlib import contextmanager from subprocess import Popen, PIPE, STDOUT from insights.util import which stream_options = { "bufsize": -1, # use OS defaults...
y stdout "stderr": STDOUT # redirect stderr to stdout for all processes } def reader(stream): for line in stream: yield line.rstrip("\n") timeout_command = [which("timeout"), "-s", str(signal.SIGKILL)] @contextmanager def stream(command, stdin=None, env=os.environ, timeout=None): """ Yiel...
pes. If it's not a list, ``shlex.split`` is applied. stdin (file like object): stream to use as the command's standard input. env (dict): The environment in which to execute the command. PATH should be defined. timeout (int): Amount of time in seconds to give the command ...
brianwc/courtlistener
cl/search/migrations/0009_auto_20151210_1124.py
Python
agpl-3.0
734
0.002725
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('search', '0008_auto_20151117_1526'), ] operations = [ migrations.AlterField(
model_name='docket', name='slug', field=models.SlugField(help_text=b'URL that the document should map to (the slug)', max_length=75, null=True, db_index=False), ), migrations.AlterField( model_name='opinioncluster', name='
slug', field=models.SlugField(help_text=b'URL that the document should map to (the slug)', max_length=75, null=True, db_index=False), ), ]
Azure/azure-sdk-for-python
sdk/synapse/azure-synapse-managedprivateendpoints/azure/synapse/managedprivateendpoints/v2020_12_01/_vnet_client.py
Python
mit
3,611
0.003323
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
path_format_arguments = { 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } http_
request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response def close(self): # type: () -> None ...
skosukhin/spack
var/spack/repos/builtin/packages/py-rope/package.py
Python
lgpl-2.1
1,561
0.000641
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
nd/or modify # it under the terms of the GNU Lesser General Public License (as # pu
blished by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public...
numerigraphe/stock-logistics-barcode
__unported__/base_gs1_barcode/__openerp__.py
Python
agpl-3.0
2,985
0.001006
# -*- coding: utf-8 -*- ############################################################################## # # This module is copyright (C) 2012 Numérigraphe SARL. All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as...
is represented as a 2-dimensions Datamatrix barcode. When those barcodes are read, their content can be decode into multiple values \ using a set of standard "Application Identifiers". For example, most pharmacy \ items have a GS1-Datamatrix barcode containg their GTIN, lot number and \ expiry date. This module does ...
rcodes. Instead, the focus of this module is on decoding the data contained in \ barcodes. To this end, it provides objects to fine-tune the Application Identifiers and the associated data types. Caveat Emptor: when an "Application Identifiers" has variable-length data, \ the barcodes must contain a special character ...
djeof-1/VOXINN
voxinn/procedural/ProceduralTerrain.py
Python
mit
1,201
0.011657
import random from djinn import * import os import sys class ProceduralTerrain: def __init__(self, heightmapList): self.heightmapList = heightmapList def generateHill(self): count = 0 num = 1 randindex = random.randint(0,len(self.hei
ghtmapList)-1) while ind < len(self.heightmapList): if ind == randindex: i = ind for j in range(len(9)): for index in range((9-count)/2): self.heightmapList[i].append(0) for index in range(9 - 2 * ((9 - cou...
m) num += 1 num -= 1 while num != 0: self.heightmapList[i].append(num) num -= 1 for index in range((9-count)/2): self.heightmapList[i].append(0) count -= 2 n...
cleverZY/Helloworld
jizhidezy.py
Python
apache-2.0
513
0.038055
#coding=utf-8 from PIL import Image#需要p
illow库 import glob, os in_dir ='background'#源图片目录 out_dir = in_dir+'_out'#转换后图片目录 if not os.path.exists(out_dir): os.mkdir(out_dir) #图片批处理 def main(): for files in glob.glob(in_dir+'/*'): filepath,filename = os.path.split(files) im = Image.open(files) w,h = im.size im = im.resize((i...
()
baiyubin/python_practice
pegs.py
Python
apache-2.0
2,445
0.001227
# n peg hanoi tower problem, use bfs instead of dfs, and don't have a full # analytical solution import sys import copy def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks): for x in range(len(currentSolution)): i, j = currentSolution[x] stacksAfterSolution[j].append...
rn False return True # DFS cannot work, need to use BFS def moveDiscs(initialStacks, finalStacks, results): import collections solutions = collections.deque() solutions.append([]) K = len(initialStacks) - 1 while len(solutions) > 0: currentSolution = copy.deepcopy(solutions.popleft()...
itialStacks, finalStacks): for x in range(len(currentSolution)): results.append(list(currentSolution[x])) return # add other solutions in queue for i in range(1, K + 1): for j in range(1, K + 1): if j != i and stepLegitimate(stacksAfte...
whutch/cwmud
cwmud/core/commands/movement/secondary.py
Python
mit
2,232
0
# -*- coding: utf-8 -*- """Secondary movement commands.""" # Part of Clockwork MUD Server (https://github.com/whutch/cwmud) # :copyright: (c) 2008 - 2017 Will Hutcheson # :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) from .. import Command, COMMANDS from ...characters import CharacterShell ...
ANDS.register class SouthwestCommand(Command): """A command to allow a character to move southwest.""" def _action(self): char = self.session.char if not char: self.session.send("You're not playing a character!") return if not char.room: self.session...
mmand, "northeast", "ne") CharacterShell.add_verbs(NorthwestCommand, "northwest", "nw") CharacterShell.add_verbs(SoutheastCommand, "southeast", "se") CharacterShell.add_verbs(SouthwestCommand, "southwest", "sw")
jorilallo/coinbase-python
tests/test_model.py
Python
mit
39,379
0.010437
# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import re import unittest2 import warnings import httpretty as hp from coinbase.client import Client from coinbase.client import OAuthClient...
was malformed.") address = request_data.get('address') assert isinstance(address, dict) if label is not None: assert address.get('label') == label if callback_url is not None: assert address.get('callback_url') == callback_url return (200, headers, json.dumps(data)) ac...
nt.id = 'fakeaccountid' hp.register_uri(hp.POST, re.compile('.*'), body=server_response) label, callback_url = ('label', 'http://example.com/') data = {'success': False, 'address': 'foo', 'label': label, 'callback_url': callback_url} with self.assertRaises(APIError)...
EvanK/ansible
test/runner/lib/constants.py
Python
gpl-3.0
379
0.005277
"""Constants used by ansible-test. Imports should not be used in this file.""" # Setting a low soft RLIMIT_NOFILE value will improve the performance of subprocess.Popen on Python 2
.x when close_fds=True. # This will affect all Python subprocesses. It will also affect the current Python process if set before subprocess is imported for the first time. SOFT_RLIMIT_NOF
ILE = 1024
BeerTheorySociety/timetable
docs/conf.py
Python
bsd-3-clause
9,474
0.006122
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # timetable documentation build configuration file, created by # sphinx-quickstart on Tue Aug 16 16:32:24 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # ...
Sailer' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/be
ta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two opti...
sftd/AllBlue-Blender-Tools
ab_addons_tools.py
Python
gpl-2.0
4,848
0.004538
# ab_addons_tools.py Copyright (C) 2012, Jakub Zolcik # # Searches through files in file browser by name. # # ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundati...
donsOperator) bpy.types.INFO_MT_file.prepend(adt_menu_draw) adt_preferences = bpy.context.user_preferences.addons[__name__].preferences # Properties bpy.types.Scene.adt_addons = bpy.props.CollectionProperty(type=ADTAddonItem) bpy.types.Scene.adt_save = bpy.props.BoolProperty('ADT Save Add...
save = bpy.props.BoolProperty('ADT Save Add-ons', default=True, update=adt_save_update) bpy.app.handlers.save_pre.append(adt_save_pre_handler); bpy.app.handlers.load_post.append(adt_load_post_handler) def unregister(): bpy.utils.unregister_class(AddonsToolsPreferences) bpy.utils.unregister_cl...
yarikoptic/NiPy-OLD
nipy/io/imageformats/compat.py
Python
bsd-3-clause
7,618
0.011158
#emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- #ex: set sts=4 ts=4 sw=4 et: ### ### #
## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyNIfTI
package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """The module provides the NiftiImage interface, which is backward-compatible to the previous C-based implementation. """ __docformat__ = 'restructuredtext' import numpy as N from nipy.io....
sgenoud/scikit-learn
sklearn/cluster/dbscan_.py
Python
bsd-3-clause
7,355
0.000272
# -*- coding: utf-8 -*- """ DBSCAN: Density-Based Spatial Clustering of Applications with Noise """ # Author: Robert Layton <[email protected]> # # License: BSD import warnings import numpy as np from ..base import BaseEstimator from ..metrics import pairwise_distances from ..utils import check_random_state d...
[0] # If index order not given, create random order. random_state = check_random_state(random_state) index_order = np.arange(n) random_state.shuffle(index_order) D = pairwise_distances(X, metric=metric) # Calculate neighborhood for all samples. This leaves the original point # in, which need...
ds = [np.where(x <= eps)[0] for x in D] # Initially, all samples are noise. labels = -np.ones(n) # A list of all core samples found. core_samples = [] # label_num is the label given to the new cluster label_num = 0 # Look at all samples and determine if they are core. # If they are then ...
amenonsen/ansible
test/lib/ansible_test/_internal/provider/layout/__init__.py
Python
gpl-3.0
6,980
0.002292
"""Code for finding content.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import abc import collections import os from ... import types as t from ...util import ( ANSIBLE_SOURCE_ROOT, ) from .. import ( PathProvider, ) class Layout: """Description of conte...
not path.endswith(os.path.sep)] # contains only file paths self.__paths_tree = paths_to_tree(self.__paths) self.__files_tree = paths_to
_tree(self.__files) def all_files(self, include_symlinked_directories=False): # type: (bool) -> t.List[str] """Return a list of all file paths.""" if include_symlinked_directories: return self.__paths return self.__files def walk_files(self, directory, include_symlinked_d...
EmpireProject/Empire
lib/modules/powershell/persistence/misc/disable_machine_acct_change.py
Python
bsd-3-clause
2,520
0.013889
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-DisableMachineAcctChange', 'Author': ['@harmj0y'], 'Description': ('Disables the machine account for the target sy
stem ' 'from changing its password automatically.'), 'Background' : False, 'OutputExtension' : None, 'NeedsAdmin' : True, 'OpsecSafe' : True, 'Language' : 'powershell', 'MinLanguageVersi
on' : '2', 'Comments': [] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run m...
VapourApps/va_master
doc_generator/module_info.py
Python
gpl-3.0
937
0.01174
from optparse import OptionParser import sys, inspect, importlib, csv #Gets a class #Returns a list of tuples [('function_name', 'function_doc'), ...] def get_class_methods(cls): methods = inspect.getmembers(cls, predicate = inspect.ismethod) methods = [(x[0], x[1].__doc__) for x in methods]
return methods #Gets a list of tuples [('class', 'ClassName')], ...] #Returns a dic
tionary {'ClassName': [('function_name', 'function_doc'), ...] def get_class_dict(cls_list): all_methods = {c[1]: get_class_methods(c[0]) for c in cls_list} return all_methods def dict_to_table(cls_name, cls_dict): table = ['|'.join(*func) for func in cls[cls_name]] table = ['Function | Documentation...
bbaltz505/iotkit-libpy
tests/test_alerts.py
Python
bsd-3-clause
543
0.001842
import iotkitclient import unittest from config import * # Test vars newaccount = "Test101" class TestAlerts(unittest.TestCase): def login(self): iot = iotkitclient.Client(host=hostname, proxies=proxies) iot.login(username, password) return iot # Connec
tion tests def test_list_alerts(self): iot = self.login() acct = iotkitclient.Account(iot) acct.get_account(newaccount) js = acct.
list_alerts() iotkitclient.prettyprint(js) self.assertEqual(0, len(js))
npp/npp-api
data/management/commands/load_cffr.py
Python
mit
12,123
0.007754
from django import db #from django.core.management.base import NoArgsCommand from django.core.management.base import BaseCommand, CommandError from django.db.models import Sum from data.models import CffrRaw, CffrProgram, CffrState, State, County, Cffr, CffrIndividualCounty, CffrIndividualState from django.db import co...
''',[year_current]) #finally, aggregate raw cffr data to the county level & insert it cursor.execute(''' INSERT INTO data_cffr (year, state_id, county_id, cffrprogram_id, amount, amount_per_capita, create_date, update_date) SELECT ...
adjusted)/pop.total,2) , NOW() , NOW() FROM data_cffrraw c JOIN data_state s ON c.state_code = s.state_ansi JOIN data_county co ON c.county_code = co.county_ansi ...
GridProtectionAlliance/ARMORE
source/webServer/domains/network.py
Python
mit
2,712
0.015487
# # # # # # network.py # # This file is used to serve up # RESTful links that can be # consumed by a frontend system # # University of Illinois/NCSA Open Source License # Copyright (c) 2015 Information Trust Institute # All rights reserved. # # Developed by: # # Information Trust Institute # University of Illinois # ht...
his list of conditions and the following # disclaimers in the documentation and/or other materials provided with the # distribution. # # Neither the names of Information Trust Institute, University of Illinois, nor # the names of its contributors may be used to endorse or promote products derived # from this Software w...
IED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS # 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 # ...
HeatherHillers/RoamMac
src/configmanager/editorwidgets/__init__.py
Python
gpl-2.0
1,068
0.003745
from PyQt4.QtCore import pyqtSignal from PyQt4.QtGui import QWidget from configmanager.editorwidgets.checkwidget import CheckboxWidgetConfig from configmanager.editorwidgets.datewidget import DateWidgetConfig from configmanager.editorwidgets.imagewidget import ImageWidgetConfig from configmanager.editorwidgets.textwid...
"Image": ImageWidgetConfig, "List": ListWidgetConfig, "MultiList" : ListWidgetConfig, "Text" : TextWidgetConfig, "TextBlock": TextBlockWidgetConfig, "Number": NumberWidgetConfig, "Number(Double)": NumberW...
nWidgetConfig}
soxfmr/ant
vendor/yougetsignal.py
Python
gpl-3.0
794
0.04534
# -*- coding: utf-8 -*- import requests import json from provider import send URL = 'http://domains.yougetsignal.com/domains.
php' KEY_REMOTE_ADDR = 'remoteAddress' KEY_RESERVE_KEY = 'key' KEY_RESERVE_UNDERLINE = '_' KEY_DOMAIN_ARRAY = 'domainArray' def retrieve(target, ip): retval = [] try: result = send(URL, payload = { KEY_REMOTE_ADDR : target, KEY_RESERVE_KEY : '', KEY_RESERVE_UNDERLINE : '' }, headers...
omainList: for domain in domainList: # Construct as ['example.com', ''] retval.append(domain[0]) except Exception as e: print e return retval
starduliang/haha
autoapp.py
Python
bsd-3-clause
266
0
# -*- coding: utf-8 -*- """Create an application instance.""" from flask.helpers import get_debug_fla
g from haha.app import create_app from haha.settings i
mport DevConfig, ProdConfig CONFIG = DevConfig if get_debug_flag() else ProdConfig app = create_app(CONFIG)
alviano/wasp
python_libraries/heuristics/heuristic-instructions.py
Python
apache-2.0
2,804
0.008559
import wasp def onConflict(): """ Optional. A conflict happened during the solving """ pass def onDeletion(): """ Optional. The method for deleting clauses is invoked. """ pass def onLearningClause(lbd, size, *lits): """ Optional. When a clause is learnt. :para...
When a loop formula is learnt for an unfounded set. :param lbd: the lbd value of the loop formula :param size: the size of the loop formula :param lits: the literals in the loop formula """ pass def onNewClause(*clause): """ Optional. All clauses left after the simplifications are sent ...
Optional. When the solver performs a restart. """ pass def onUnfoundedSet(*unfounded_set): """ Optional. When an unfounded set is found. :param unfounded_set: all atoms in the unfounded set """ pass def initFallback(): """ Optional. Init the activities of variabl...
bockthom/codeface
codeface/dbmanager.py
Python
gpl-2.0
21,118
0.001799
#! /usr/bin/env python # This file is part of Codeface. Codeface is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY...
else:
self.con.close() raise # Give up after too many retry attempts and propagate the # problem to the caller. Either it's fixed with a different # query, or the analysis fails log.error("DB access failed after ten attempts, giving up") ...
mohsraspi/mhscs14
tobias/pyramid.py
Python
gpl-2.0
163
0.055215
import minecraft as minecraft mc = minecraft.Minecraft.create() p=25 y=-5 n=-25 while p >= 1: mc.setBlocks(p,y,p,n,y,n,45) p = p-1 n = n+1 y = y+1
JuliaLima/Evergreen
build/i18n/tests/testSQL.py
Python
gpl-2.0
1,833
0.002182
#!/usr/bin/env python # # Perform the following tests: # 1. Generate a POT file from a set of marked SQL statements # 2. Generate an SQL file from a translated PO file import filecmp import os import subprocess import testhelper import unittest class TestSQLFramework(unittest.TestCase): basedir = os.path.dirna...
mp/sql2pot.pot') canonsql = os.path.join(basedir, 'data/po2sql.sql') testsql = os.path.join(basedir, 'tmp/testi18n.sql') def setUp(self): testhelper.setUp(self) def tearDown(self): testhelper.tearDown(self) def testgenpot(self): """ Create a POT file from our test ...
t', self.sqlsource, '--output', self.testpot), 0, None, None).wait() # avoid basic timestamp conflicts testhelper.mungepothead(self.testpot) testhelper.mungepothead(self.canonpot) self.assertEqual(filecmp.cmp(self.canonpot, self.testpot), 1) def testgensql(...
jeremiedecock/snippets
python/pyqt/pyqt4/hello_class_for_main_widget.py
Python
mit
2,089
0.004312
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaini
ng 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, distribute,
sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS...
molpopgen/fwdpy11
fwdpy11/demographic_models/IM.py
Python
gpl-3.0
6,028
0.000829
""" This module provides functions to generate demographic events for "isolation-with-migration", or IM, models. """ import attr import numpy as np from fwdpy11.class_decorators import (attr_add_asblack, attr_class_pickle, attr_class_to_from_dict) @attr_add_asblack # @attr_class_...
zero exists. m = fwdpy11.migration_matrix_single_extant_deme(2, 0) # The rows of the matrix change at the split: cm = [ fwdpy11.SetMigrationRates(split_time, 0, [1.0 - m10, m10]), fwdpy11.SetMigrationRates(split_time, 1, [m01, 1.0 - m01]), ] mdict = { "mass_migrations": spli...
"set_growth_rates": growth, "set_migration_rates": cm, "migmatrix": m, } return DemographicModelDetails( model=fwdpy11.DiscreteDemography(**mdict), name="Two deme isolation-with-migration (IM) model", source={"function": "fwdpy11.demographic_models.IM.two_deme_I...
DavideCanton/Python3
euler/ex7.py
Python
gpl-3.0
182
0.005495
__author__ = 'davide' import itertools as it from euler._utils import genera_primi if __name__
== "__main__": n =
it.islice(genera_primi(), 10000, 8359265) print(next(n))
arth-co/shoop
shoop_tests/core/test_sales_unit.py
Python
agpl-3.0
775
0
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from decimal import Decimal from shoop.core.models.units import SalesUnit ...
.quantity_step == Decimal("0.1") assert SalesUn
it(decimals=1).allow_fractions assert SalesUnit(decimals=10).quantity_step == Decimal("0.0000000001") assert SalesUnit(decimals=2).round("1.509") == Decimal("1.51") assert SalesUnit(decimals=0).round("1.5") == Decimal("2")
yfauser/ansible-modules-extras
notification/flowdock.py
Python
gpl-3.0
6,028
0.003981
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2013 Matt Coddington <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
d message categorization required: false link: description: - (inbox only) Link associated with the message. This will be used to link the message subject in Team Inbox
. required: false validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. required: false default: 'yes' choices: ['yes', 'no'] version_added: 1.5.1 requirements: [ ]...
cortedeltimo/SickRage
sickbeard/notifiers/slack.py
Python
gpl-3.0
3,220
0.002174
# coding=utf-8 # Author: Patrick Begley<[email protected]> # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
.NOTIFY_SNATCH] + ': ' + ep_name) def notify_download(self, ep_name):
if sickbeard.SLACK_NOTIFY_DOWNLOAD: self._notify_slack(common.notifyStrings[common.NOTIFY_DOWNLOAD] + ': ' + ep_name) def notify_subtitle_download(self, ep_name, lang): if sickbeard.SLACK_NOTIFY_SUBTITLEDOWNLOAD: self._notify_slack(common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNL...
Kryz/sentry
tests/sentry/models/tests.py
Python
bsd-3-clause
5,760
0.002604
# coding: utf-8 from __future__ import absolute_import import pytest from datetime import timedelta from django.core import mail from django.core.urlresolvers import reverse from django.db import connection from django.utils import timezone from exam import fixture from sentry.db.models.fields.node import NodeData,...
='Test', team=team) assert project.key_set.exists() is True class LostPasswordTest(TestCase): @fixture def password_hash(self): return LostPasswordHash.objects.create( user=self.user, ) def test_send_recover_mail(self): with self.settings(SENTRY_URL_PREFIX='htt...
outbox[0] assert msg.to == [self.user.email] assert msg.subject == '[Sentry] Password Recovery' url = 'http://testserver' + reverse('sentry-account-recover-confirm', args=[self.password_hash.user_id, self.password_hash.hash]) assert url in msg.body class GroupIsOverResolveA...
JFeaux/pedro
src/cards.py
Python
mit
6,808
0.000147
#!/usr/bin/python import sys from random import shuffle, seed from itertools import product class Card: FACES = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'} SUITS = {'Hearts': 1, 'Diamonds': 2, 'Spades': 3, 'Clubs': 4} COLORS = {'Hearts': 0, 'Diamonds': 0, 'Spades': 1, 'Clubs': 1} def __init__(s...
bid = 5 winning_bidder = -1 order = [i for i in range(first_bidder, 4)] + \ [i for i in range(first_bidder)] for i, j in enumerate(order): print self.players[j] if current_bid < 14: bid = int(raw_input('Bid?\n'))
if bid > current_bid: current_bid = bid winning_bidder = j else: bid = int(raw_input('Bid?\n')) if bid == 14 and i == 3: current_bid = bid winning_bidder = j print current_bid ...
apoelstra/coinjoin
generate-tx.py
Python
cc0-1.0
3,413
0.028714
# Note - to use this script you need Jeff Garzik's pytho
n-bitcoinrpc # https://github.com/jgarzik/python-bitcoinrpc import os import sys; import json; from bitcoinrpc.authproxy import AuthServiceProxy; # SET THESE VALUES rpc_user = "bitcoinrpc"; rpc_pass = "A7Xr149i7F6GxkhDbxWDTbmXooz1UZGhhyUYvaajA13Z"; rpc_host = "localhost"; rpc_port = 8332; donation_minimum = 0; donat...
tionsSpendHerdtWbWy"; # http://stackoverflow.com/questions/626796/how-do-i-find-the-windows-common-application-data-folder-using-python try: from win32com.shell import shellcon, shell config_file = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) + "/Bitcoin/bitcoin.conf" except ImportError:...
cortext/crawtextV2
~/venvs/crawler/lib/python2.7/site-packages/nltk/stem/wordnet.py
Python
mit
1,263
0.000792
# Natural Language Toolkit: WordNet stemmer interface # # Copyright (C) 2001-2012 NLTK Project # Author: Steven Bird <[email protected]> # Edward Loper <[email protected]> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT from nltk.corpus.reader.wordnet import NOUN from...
(word, pos) return min(lemmas, key=len) if lemmas else word def __repr__(self): return '<Wo
rdNetLemmatizer>' if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
oskopek/CryptoIM
tests/unit/common.py
Python
apache-2.0
1,286
0.005443
#!/usr/bin/env python # encoding: utf-8 """ Copyright 2014 CryptoIM Development Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
NDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import random, string def random_string_range(lo, hi): """ Returns a random string of string.printable characters, of length randint(lo, hi) """...
random string of string.printable characters, of the given length """ return random_string_range(length, length) def random_string_limit(limit): """ Returns a random string of string.printable characters, of length randint(1, limit) """ return random_string_range(1, limit)
pauldamian/-casa
acasa/things/dim.py
Python
apache-2.0
1,015
0.008867
import RPi.GPIO as gp from time import sleep from utili
ty import util import constants """ Pin Mapping: Pin 4 - VCC 5V Pin 6 - GND Pin 7 - SYNC - PWM Pin 11 - GATE - Digital """ gm = util.get_sensor_attribute_value(constants.DIMMER, constants.SENSOR_PIN) dimming = 100 AC_LOAD = g
m['gate'] SYNC = gm['sync'] gp.setwarnings(False) def _zero_cross_int(arg): global dimming idle_time = dimming * 0.0001 if idle_time == 0: gp.output(AC_LOAD, True) return elif idle_time == 0.01: gp.output(AC_LOAD, False) return else: gp.outp...
caoxudong/code_practice
leetcode/59_spiral_matrix_ii.py
Python
mit
1,960
0.005102
#!/usr/bin/env python #coding: utf-8 """ https://leetcode.com/problems/spiral-matrix-ii
/ Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For exam
ple, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] """ class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ result = [([0] * n) for i in range(n)] ...
show0k/pypot
pypot/robot/config.py
Python
gpl-3.0
12,375
0.001697
""" The config module allows the definition of the structure of your robot. Configuration are written as Python dictionary so you can define/modify them programmatically. You can also import them form file such as JSON formatted file. In the configuration you have to define: * contr
ollers: For each defined controller, you can specify the port name,
the attached motors and the synchronization mode. * motors: You specify all motors belonging to your robot. You have to define their id, type, orientation, offset and angle_limit. * motorgroups: It allows to define alias of group of motors. They can be nested. """ import logging import numpy import time import json ...
encukou/freeipa
ipaserver/install/krainstance.py
Python
gpl-3.0
11,676
0
# Authors: Ade Lee <[email protected]> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # 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...
promote=False, pki_config_override=None): """Create a KRA instance. To create a clone, pass in pkcs12_info. """ self.fqdn = host_name self.dm_password = dm_password self.admin_groups = ADMIN_GROUPS self.admin_password = admin_password ...
self.clone = True self.master_host = master_host self.pki_config_override = pki_config_override self.subject_base = \ subject_base or installutils.default_subject_base(realm_name) # eagerly convert to DN to ensure validity self.ca_subject = DN(ca_subject) ...
liveaverage/baruwa
src/baruwa/status/migrations/0001_initial.py
Python
gpl-2.0
2,911
0.007901
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'MailQueueItem' db.create_table(u'mailq', ( ('id', self.gf('django.db.models.fi...
('reason', self.gf('django.db.models.fields.TextField')(blank=True)), ('flag', self.gf('django.db.models.fields.IntegerField')(default=0)), )) db.send_create_signal('status', ['MailQueueItem']) def backwards(self, orm): # Deleting model 'MailQueueItem' ...
ble(u'mailq') models = { 'status.mailqueueitem': { 'Meta': {'ordering': "['-timestamp']", 'object_name': 'MailQueueItem', 'db_table': "u'mailq'"}, 'attempts': ('django.db.models.fields.IntegerField', [], {}), 'direction': ('django.db.models.fields.IntegerField', [], {'d...
MichSchli/Mindblocks
controller/viewscreen_controller/viewscreen_listener.py
Python
gpl-3.0
4,045
0.001731
from model.component.component_model import ComponentModel from model.component.component_specification import ComponentSpecification from model.computation_unit.computation_unit_model import ComputationUnitModel from model.graph.graph_model import GraphModel class ViewscreenListener: """ Receives requests fr...
aph_repository, selection_presenter, computation_unit_repository): self.canvas_reposi
tory = canvas_repository self.selection_presenter = selection_presenter self.component_repository = component_repository self.graph_repository = graph_repository self.viewscreen = viewscreen self.computation_unit_repository = computation_unit_repository self.register_obs...
marcharper/Axelrod
axelrod/strategies/axelrod_second.py
Python
mit
3,354
0.000298
""" Additional strategies from Axelrod's second tournament. """ import random from axelrod import Actions, Player, flip_action, random_choice C, D = Actions.C, Actions.D class Champion(Player): """ Strategy submitted to Axelrod's second tournament by Danny Champion. """ name = "Champion" class...
nt_round = len(self.history) expected_length = self.match_attributes['length'] # Cooperate for the first 1/20-th of the game if current_round == 0:
return C if current_round < expected_length / 20.: return C # Mirror partner for the next phase if current_round < expected_length * 5 / 40.: return opponent.history[-1] # Now cooperate unless all of the necessary conditions are true defection...
jasdumas/jasdumas.github.io
post_data/RF_adult_income.py
Python
mit
5,021
0.019319
# import libraries: dataframe manipulation, machine learning, os tools from pandas import Series, DataFrame import pandas as pd import numpy as np import os import matplotlib.pylab as plt from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import cl...
the prediction """ trees=range(25) accuracy=np.zeros(25) for idx in range(len(trees)): classifier=RandomForestClassifier(n_estimators=idx + 1) classifier=classifier.fit(pred_train,tar_train) predictions=classifier.predict(pred_test) accuracy[idx]=sklearn.metrics.accuracy_score(tar_test, predictions) ...
ees, accuracy)
skippyprime/configs
tests/utils.py
Python
apache-2.0
171
0
import collecti
ons ConfigParams = collections.namedtuple( 'ConfigParams', [ 'format', 'hint', 'disposition', 'exten
sion' ] )
elibixby/gcloud-python
gcloud/error_reporting/test_client.py
Python
apache-2.0
5,284
0
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
payload['context']['httpContext']['responseStatusCode'], 500) self.assertEquals( payload['context']['httpContext']['method'], 'GET') self.assertEquals(payload['context']['user'], USER) def test_report(self): CREDENTIALS = _Credentials() target = self._makeOne(p...
logger = _Logger() target.logging_client.logger = lambda _: logger MESSAGE = 'this is an error' target.report(MESSAGE) payload = logger.log_struct_called_with self.assertEquals(payload['message'], MESSAGE) report_location = payload['context']['reportLocation'] ...
theadviceio/executer
tests/cache/test_cache.py
Python
apache-2.0
6,321
0.00443
# from __future__ import absolute_import # from base import * import unittest import os import tempfile import glob import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)) + "/../../")) import cache __version__ = 1.0 __author__ = '[email protected]' tmp_files=[] class TestR...
cache_type=cache_type, file_path=file_path) # cache.update(key=None, value=None, cache_type=None, file_path=None) __cache_store = cache.get_cache_copy() self.assertIsInstance(__cache_store, dict) self.assertIn(cache_type, __cache_store) self.assertIn(key, __cache_store[cache_type...
self.assertIn(file_path, __cache_store[cache_type][key]) self.assertIn('value', __cache_store[cache_type][key][file_path]) self.assertIn('access_time', __cache_store[cache_type][key][file_path]) self.assertEqual(value, __cache_store[cache_type][key][file_path]['value']) self.assertEqu...
vmassuchetto/dnstorm
dnstorm/app/__init__.py
Python
gpl-2.0
383
0
from django.contrib.auth.models import User from actstream import registry from dnstorm.app import models DN
STORM_VERSION = '0.01' DNSTORM_URL = 'http://vmassuchetto.github.io/dnstorm' registry.register(User) registry.register(models.Problem) registry.register(models.Criteria) registry.register(models.Idea) registry.register(models.Al
ternative) registry.register(models.Comment)
StefQM/facedetect
facedetect/rects.py
Python
mit
1,352
0.012574
import cv2 def outlineRect(image, rect, color): if rect is None: return x, y, w, h = rect cv2.rectangle(image, (x, y), (x+w, y+h), color) def copyRect(src, dst, srcRect, dstRect, interpo
lation = cv2.INTER_LINEAR): """Copy part of the source to part of the destination.""" x0, y0, w0, h0 = srcRect x1, y1, w1, h1 = ds
tRect # Resize the contents of the source sub-rectangle. # Put the result in the destination sub-rectangle. dst[y1:y1+h1, x1:x1+w1] = \ cv2.resize(src[y0:y0+h0, x0:x0+w0], (w1, h1), interpolation = interpolation) def swapRects(src, dst, rects, interpolation = c...
MatthewVerbryke/inmoov_ros
inmoov_tools/trainer/trainergui.py
Python
bsd-3-clause
13,132
0.003807
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'trainergui.ui' # # Created: Tue May 24 14:29:31 2016 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Att...
self.txtSpeed.setGeometry(QtCore.QRect(132, 520, 121, 27)) self.txtSpeed.setObjectName(_fromUtf8("txtSpeed")) self.chkPower = QtGui.QCheckBox(self.frame) self.chkPower.setEnabled(False) self.chkPower.setGeometry(QtCore.QRect(30, 500, 97, 22)) self.chkPower.setLayoutDirectio...
ghtToLeft) self.chkPower.setText(_fromUtf8("")) self.chkPower.setObjectName(_fromUtf8("chkPower")) self.txtPosition = QtGui.QLineEdit(self.frame) self.txtPosition.setEnabled(False) self.txtPosition.setGeometry(QtCore.QRect(110, 470, 141, 27)) self.txtPosition.setObjectNam...
rootulp/exercism
python/etl/etl.py
Python
mit
119
0
def
transform(old): return {value.lower(): score for score, values in old.items(
) for value in values}
SUNET/eduid-webapp
src/eduid_webapp/letter_proofing/tests/test_pdf.py
Python
bsd-3-clause
6,870
0.001601
# -*- coding: utf-8 -*- import unittest from collections import OrderedDict from datetime import datetime from six import BytesIO, StringIO from eduid_common.api.testing import EduidAPITestCase from eduid_webapp.letter_proofing import pdf from eduid_webapp.letter_proofing.app import init_letter_proofing_app from e...
(u'GivenName', u'Testaren Test'), (u'MiddleName', u'Tester'), (u'Surname', u'Testsson'), ] ), ), ( u'OfficialAddress',
OrderedDict( [ (u'Address2', u'\xd6RGATAN 79 LGH 10'), (u'Address1', u'LGH 4321'), (u'CareOf', u'TESTAREN & TESTSSON'), (u'PostalCode', u'12345'), ...
FedoraScientific/salome-geom
src/GEOM_SWIG/GEOM_example6.py
Python
lgpl-2.1
1,993
0.003512
# -*- coding: iso-8859-1 -*- # Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your ...
ilder.New(salome.myStudy) ind = 1 circlelist = [] while ind < 6: x1 = 0. + (10. * ind) y1 = 0. z1 = 0. x2 = 10. + (10. * ind) y2 = 20. * (ind+1) z2 = 30. * (ind+1) x3 = 50. + (10. * ind) y3 = 0. * (
ind+1) z3 = -10. * (ind+1) print x1, y1, z1, x2, y2, z2, x3, y3, z3 point1 = geompy.MakeVertex(x1, y1, z1) name1 = "point1_%d"%(ind) id_pt1 = geompy.addToStudy(point1, name1) point2 = geompy.MakeVertex(x2, y2, z2) name2 = "point2_%d"%(ind) id_pt2 = geompy.addToStudy(point2, name2) ...
Smarsh/django
tests/modeltests/custom_methods/models.py
Python
bsd-3-clause
1,885
0.003714
""" 3. Giving models custom methods Any method you add to a model will be available to instances. """ from django.db import models import datetime class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() def __unicode__(self): return self.headline ...
def articles_from_same_day_1(self): return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id) def articles_from_same_day_2(self): """ Verbose version of get_articles_from_same_day_1, which does a custom database query for the sake of demonstration. """ ...
cursor.execute(""" SELECT id, headline, pub_date FROM custom_methods_article WHERE pub_date = %s AND id != %s""", [connection.ops.value_to_db_date(self.pub_date), self.id]) # The asterisk in "(*row)" tells Python to ex...
davidbgk/udata
udata/tests/site/test_site_views.py
Python
agpl-3.0
13,615
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import StringIO from datetime import datetime from flask import url_for from udata.frontend import csv from udata.models import Badge, Site, PUBLIC_SERVICE from udata.core.dataset.factories import DatasetFactory, ResourceFactory from udata.core.organi...
e', header) self.assertIn('description', header) self.assertIn('created_at', header) self.assertIn('last_modified', header) self.assertIn('tags', header) self.assertIn('metric.reuses', header) rows = list(reader) ids = [row[0] for row in rows] self.asser...
lf.assertIn(str(dataset.id), ids) self.assertNotIn(str(hidden_dataset.id), ids) def test_datasets_csv_with_filters(self): '''Should handle filtering but ignore paging or facets''' with self.autoindex(): filtered_datasets = [ DatasetFactory(resources=[ResourceFact...
StrellaGroup/erpnext
erpnext/stock/doctype/serial_no/test_serial_no.py
Python
gpl-3.0
2,291
0.017023
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # ERPNext - web based ERP (http://erpnext.com) # For license information, please see license.txt from __future__ import unicode_literals import frappe, unittest from erpnext.stock.doctype.st...
create_warehouse from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory test_dependencies = ["Item"] test_records = frappe.get_test_records('Serial No') from erpnext.stock.doctype.serial_no.serial_no import *
class TestSerialNo(unittest.TestCase): def test_cannot_create_direct(self): frappe.delete_doc_if_exists("Serial No", "_TCSER0001") sr = frappe.new_doc("Serial No") sr.item_code = "_Test Serialized Item" sr.warehouse = "_Test Warehouse - _TC" sr.serial_no = "_TCSER0001" sr.purchase_rate = 10 self.assertR...
beeftornado/sentry
src/sentry/integrations/pagerduty/integration.py
Python
bsd-3-clause
7,387
0.002572
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ from django.db import transaction from sentry import options from sentry.utils import json from sentry.utils.compat import filter from sentry.utils.http import absolute_uri from s
entry.integrations.base import ( IntegrationInstallation, IntegrationFeatures, IntegrationMetadata, IntegrationProvider, FeatureDescription, ) from sentry.shared_integrations.exceptions import IntegrationError from sentry.m
odels import OrganizationIntegration, PagerDutyService from sentry.pipeline import PipelineView from .client import PagerDutyClient DESCRIPTION = """ Connect your Sentry organization with one or more PagerDuty accounts, and start getting incidents triggered from Sentry alerts. """ FEATURES = [ FeatureDescription...
tlksio/tlksio
talks/migrations/0005_auto_20170402_1502.py
Python
mit
866
0.003464
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-02 15:02 from __future_
_ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talks', '0004_auto_20170326_1755'), ] operations = [ migrations.AlterField( model_name='talk',
name='fav_count', field=models.PositiveIntegerField(default=0, verbose_name='favorite count'), ), migrations.AlterField( model_name='talk', name='view_count', field=models.PositiveIntegerField(default=0, verbose_name='view count'), ), ...
OBIGOGIT/etch
binding-python/runtime/src/test/python/tests/binding/support/TestValidator_float.py
Python
apache-2.0
3,261
0.01012
# Licensed to the Apache Software Foundation (ASF) under one * # or more contributor license agreements. See the NOTICE file * # distributed with this work for additional information * # regarding copyright ownership. The ASF licenses this file * # to you under the Apache License, Version 2.0 (the ...
idator_float.get(n) self.assertEqual(n, v.getNDims()) self.assertEqual(clss, v.getExpectedClass()) self.assertEqual(s, repr(v)) self.assertEqual(True, v.validate(good)) self.assertEqual(False, v.validate(bad)) self.assertEqual(tc, v.checkValue(good)) self.assert...
.assertEqual(n-1, v.elementValidator().getNDims()) if __name__=='__main__': unittest.main()
pwmarcz/django
django/contrib/gis/tests/test_spatialrefsys.py
Python
bsd-3-clause
4,891
0.001636
import unittest from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.tests.utils import (oracle, postgis, spatialite, SpatialRefSys) from django.db import connection from django.test import skipUnlessDBFeature from django.utils import six test_srs = ({ 'srid': 4326, 'auth_name': ('EPSG', ...
ange(3): self.assertAlmostEqual(ellps1[i], ellps2[i], prec[i]) def test_add_entry(self): """ Test adding a new entry in the SpatialRefSys model using the add_srs_entry utility. """ from django.contrib.gis.utils import add_srs_entry add_srs_
entry(3857) self.assertTrue( SpatialRefSys.objects.filter(srid=3857).exists() ) srs = SpatialRefSys.objects.get(srid=3857) self.assertTrue( SpatialRefSys.get_spheroid(srs.wkt).startswith('SPHEROID[') )
theJollySin/mazelib
mazelib/solve/MazeSolveAlgo.py
Python
gpl-3.0
6,364
0.001886
import abc import numpy as np from numpy.random import shuffle class MazeSolveAlgo: __metaclass__ = abc.ABCMeta def solve(self, grid, start, end): """ helper method to solve a init the solver before solving the maze Args: grid (np.array): maze array start (tuple): pos...
corridor then backtrack. These extraneous steps need to be removed. Also, clean up the end points. Args: solution (list): raw maze solution Returns: list:
cleaner, tightened up solution to the maze """ found = True attempt = 0 max_attempt = len(solution) while found and len(solution) > 2 and attempt < max_attempt: found = False attempt += 1 for i in range(len(solution) - 1): fi...
Cinntax/home-assistant
homeassistant/components/scsgate/switch.py
Python
apache-2.0
5,491
0.001093
"""Support for SCSGate switches.""" import logging import voluptuous as vol from homeassistant.components import scsgate from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA from homeassistant.const import ATTR_ENTITY_ID, ATTR_STATE, CONF_NAME, CONF_DEVICES import homeassistant.helpers.config_val...
self._scs_id, message, ) # Nothing changed, ignoring return self._toggled = message.toggled self.schedule_update_ha_state() command = "off" if self._toggled: command = "on" self.hass.bus.fire( ...
scenario switch. This switch is always in an 'off" state, when toggled it's used to trigger events. """ def __init__(self, scs_id, name, logger, hass): """Initialize the scenario.""" self._name = name self._scs_id = scs_id self._logger = logger self._hass = has...
tpugsley/tco2
tco2/config/production.py
Python
bsd-3-clause
4,340
0.001843
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use sendgrid to send emails - Use MEMCACHIER on Heroku ''' from configurations import values # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings...
NFIGURATION # CACHING # Only do this here because thanks to django-pylibmc-sasl and pylibmc # memcacheify is painful to install on windows. try: # See: https://github.com/rdegges/django-heroku-memcacheify from memcacheify import memcacheify CACHES = memcacheify() except Impo...
D CACHING # Your production stuff: Below this line define 3rd party library settings
GNU-Pony/ptools
src/pclean.py
Python
gpl-3.0
3,292
0.005474
#!/usr/bin/env python3 ''' ptools – software package installation tools Copyright © 2013 Mattias Andrée ([email protected]) 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...
+ 'en' if not os.path.lexists(_en): mkdir_p(_en) mv(path('%s/man?/' % path_escape(_man)), _en) filter_locale(i_use_man_locale, pkgdir, None, mandir) _lang = _man + os.sep + i_use_locale_man if os.path.lexists(_lang): mv(os.list
dir(_lang), _man) rmdir(_lang) if len(os.listdir(_man)) == 0: rmdir(_man) if not i_use_doc: rm_r(pkgdir + docdir) filter_locale(i_use_locale, pkgdir, None, localedir) if not i_use_license: _dir = '%s%s%s' % (i_use_license, os.sep, pkgname) if os.path.lexists(_dir): if os.path....
LoLab-VU/pysb
pysb/examples/paper_figures/fig6.py
Python
bsd-2-clause
9,204
0.000869
"""Produce contact map for Figure 5D from the PySB publication""" from __future__ import print_function import pysb.integrate import pysb.util import numpy as np import scipy.optimize import scipy.interpolate import matplotlib.pyplot as plt import os import sys import inspect from earm.lopez_embedded import model #...
, -1) sim_obs_norm = (sim_obs / obs_totals).T # Do the same with the estimated parameters solver.run(params_estimated) sim_est_obs = solver.yobs[obs_names_disp].view(float).reshape(len(solver.
yobs), -1) sim_est_obs_norm = (sim_est_obs / obs_totals).T # Plot data with simulation trajectories both before and after fitting color_data = '#C0C0C0' color_orig = '#FAAA6A' color_est = '#83C98E' plt.subplot(311) plt.errorbar(exp_data['Time'], exp_data['norm_ICRP'], yer...
jaredjennings/snowy
wsgi/snowy/snowy/lib/reversion/managers.py
Python
agpl-3.0
2,511
0.005575
"""Model managers for Reversion.""" try: set except NameError: from sets import Set as set # Python 2.3 fallback. from django.contrib.contenttypes.models import ContentType from django.db import models class VersionManager(models.Manager): """Manager for Version models.""" def get_for_obj...
reated.""" content_type = Co
ntentType.objects.get_for_model(object) return self.filter(content_type=content_type, object_id=unicode(object.pk)).order_by("pk").select_related().order_by("pk") def get_unique_for_object(self,obj): """Returns unique versions associated with the object.""" versions = self.get_for_objec...
bit-trade-one/SoundModuleAP
lib-src/lv2/sratom/waflib/Tools/xlcxx.py
Python
gpl-2.0
1,267
0.056827
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file from waflib.Tools import ccroot,ar from waflib.Configure import conf @conf def find_xlcxx(conf): cxx=conf.find_program(['xlc++_r','xlc++'],var='CXX') cxx=conf.cmd_t...
cxx_common_flags(conf): v=conf.env v['CXX_SRC_F']=[] v['CXX_TGT_F']=['-c','-o'] if not v['LINK_CXX']:v['LINK_CXX']=v['CXX'] v['CXXLNK_SRC_F']=[] v['CXXLNK_TGT_F']=['-o'] v['CPPPATH_ST']='-I%s' v['DEFINES_ST']='-D%s' v['LIB_ST']='-l%s' v['LIBPATH_ST']='-L%s' v['STLIB_ST']=
'-l%s' v['STLIBPATH_ST']='-L%s' v['RPATH_ST']='-Wl,-rpath,%s' v['SONAME_ST']=[] v['SHLIB_MARKER']=[] v['STLIB_MARKER']=[] v['LINKFLAGS_cxxprogram']=['-Wl,-brtl'] v['cxxprogram_PATTERN']='%s' v['CXXFLAGS_cxxshlib']=['-fPIC'] v['LINKFLAGS_cxxshlib']=['-G','-Wl,-brtl,-bexpfull'] v['cxxshlib_PATTERN']='...
PressLabs/silver
silver/api/exceptions.py
Python
apache-2.0
935
0
# Copyright (c) 2017 Presslabs SRL # # 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 writ...
a conflict ' \ 'with the cur
rent state of the resource.'
pi-bot/pibot-pkg
tests/dependencies.py
Python
gpl-3.0
100
0
import time import os import j
son import
requests # Plan is to import and to checkout dependencies:
pmisik/buildbot
master/buildbot/test/unit/test_mq_connector.py
Python
gpl-2.0
3,377
0
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
new_config) @defer.inlineCallbacks def test_reconfigService_change_type(self): self.patchFakeMQ() self.mqconfig['type'] = 'fake' yield
self.conn.setup() new_config = mock.Mock() new_config.mq = dict(type='other') try: yield self.conn.reconfigServiceWithBuildbotConfig(new_config) except AssertionError: pass # expected else: self.fail("should have failed")
SmokinCaterpillar/pypet
doc/source/conf.py
Python
bsd-3-clause
10,941
0.006581
# -*- coding: utf-8 -*- # # pypet documentation build configuration file, created by # sphinx-quickstart on Wed Sep 4 12:12:59 2013. # # This file is execfile()d with the current directory f_set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
rcelink = True # If true, "Created usi
ng Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of ...
geosdude/pyFace
menuWidget.py
Python
gpl-3.0
8,829
0.009061
#!/bin/bash # -*- codign:utf-8 -*- # pyface.menuWidget.Menu_Widget # Coded by Richard Polk #---------------------------------------------------- from Tkinter import * class Menu_Widget: def __init__(self): # Menu metrics frame_height = self.sub_frame_height = self.guiDct['sub_frame_height'] fra...
"self.TkinterHelp(2)"), 'separator', ('About Python', 0, "self.pyVersion()"), ] ), ] # Standard pulldown menus from list for (menuName, key, items) in self.menuLst: widgetname = string.lower(menuName.rep
lace(' ', '_')) self.mbutton = Menubutton(self.menu_frame, name=widgetname, text=menuName, font=self.fonts[7], underline=key) self.widgetLst.append(widgetname) ...
hellrich/JeSemE
pipeline/preprocessing/google/parse_normalized.py
Python
mit
712
0.021067
#produces lemmata! import json import glob import codecs import sys import os if len(sys.argv) != 3: raise Exception("Provide 2 arguments:\n\t1,Source directory with CAB responses\n\t2,Result file") cab_files = sys.argv
[1] result_path = sys.argv[2] with codecs.open(result_path, mode="w", buffering=10000, encoding="utf-8") as result: for cab_file in glob.glob(os.path.join(cab_files, "*")): with codecs.open(cab_file, mode="r", encoding="utf-8") as cab: for line in cab: if "\t" in line: word, analysis = line.split("\t") ...
oot"]["lemma"] if word.lower() != lemma.lower() and not ( ";" in word or ";" in lemma): result.write(word+";"+lemma+"\n")
bikash/omg-monitor
monitor/utils/pingdom.py
Python
gpl-3.0
4,612
0.00477
# The MIT License # # Copyright (c) 2010 Daniel R. Craig # # 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,...
iable=False, http_method=None): urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable) if http_method: self.method = http_method def get_method(self):
if self.method: return self.method return urllib2.Request.get_method(self) def method(self, url, method="GET", parameters=None): if parameters: data = urlencode(parameters) else: data = None method_url = urljoin(self.url, url) ...
pombredanne/bitmath
full_demo.py
Python
mit
6,552
0.001374
#!/usr/bin/env python from __future__ import print_function import logging import time import bitmath import bitmath.integrations import argparse import requests import progressbar import os import tempfile import atexit import random # Files of various sizes to use in the demo. # # Moar here: https://www.kernel.org/p...
downloaded contents * Filter for .xz files only """) for p,bm in bitmath.listdir(DESTDIR, filter='*.xz'): print(p, bm) ###################################################################### print(""" ###################################################################### List downloaded...
st human readable prefix """) for p,bm in bitmath.listdir(DESTDIR, filter='*.gz', bestprefix=True): print(p, bm) ###################################################################### print(""" ################################################################...
portfoliome/foil
foil/deserializers.py
Python
mit
2,317
0
import collections from functools import partial from itertools import chain from types import MappingProxyType from typing import Callable from uuid import UUID import iso8601 from foil.parsers import parse_iso_date as _parse_iso_date def parse_uuid(value): try: value = UUID(value, version=4) except...
s ---------- str_decoders: functions for decoding strings to objects. extra_str_decoders: appends additional string decoders to str_decoders. converters: field / parser function mapping. """ str_decoders = tuple(c
hain(str_decoders, extra_str_decoders)) object_hook = partial(json_decoder_hook, str_decoders=str_decoders, converters=converters) return object_hook
gpodder/panucci
src/panucci/gtkui/gtkplaylist.py
Python
gpl-3.0
15,781
0.003865
# -*- coding: utf-8 -*- # # This file is part of Panucci. # Copyright (c) 2008-2011 The Panucci Project # # Panucci 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...
_OR_BEFORE ): model.move_before( from_iter, to_iter ) to_row = to_row - 1 if from_row < to_row else to_row elif ( position == gtk.TREE_VIEW_DROP_AFTER or position == gtk.TREE_VIEW_DROP_INTO_OR_AFTER ): model.move_after( from_iter, to_iter ) ...
) # don't do anything if we're not actually moving rows around if from_row != to_row: self.player.playlist.move_item( from_row, to_row ) else: self.__log.debug('No drop_data or selection.data available') def update_model(self): path_info =
hudl/redash
tests/models/test_queries.py
Python
bsd-2-clause
13,843
0.001448
# encoding: utf8 from tests import BaseTestCase import datetime from redash.models import Query, Group, Event, db from redash.utils import utcnow class QueryTest(BaseTestCase): def test_changing_query_text_changes_hash(self): q = self.factory.create_query() old_hash = q.query_hash q.quer...
es = list(Query.search("Testing", [other_group.id])) self.assertIn(q1, queries) self.assertNotIn(q2, queries) self.assertNotIn(q3, queries)
def test_returns_each_query_only_once(self): other_group = self.factory.create_group() second_group = self.factory.create_group() ds = self.factory.create_data_source(group=other_group) ds.add_group(second_group, False) q1 = self.factory.create_query(description="Testing sea...
soarlab/FPTuner
examples/micro/jacobi-n2u2.py
Python
mit
916
0.012009
import tft_ir_api as IR n = 2 unrolls = 2 low = 1.0 high = 10.0 A = list() for j in range(n): row = list() for i in range(n): row.append(IR.RealVE("a{}{}".format(i,j), 0, low, high)) A.append(row) b = list() for i in range(n): b.appen
d(IR.RealVE("b{}".format(i), 1, low, high)) x = list() for i in range(n): x.append(IR.FConst(1.0)) g=2 #j k = 0 #j while convergence not reached: # while loop for k in range(unrolls): # replacement
for while loop for i in range(n): # i loop sigma = IR.FConst(0.0) for j in range(n): # j loop if j != i: sigma = IR.BE("+", g, sigma, IR.BE("*", g, A[i][j], x[j])) g += 1 # end j loop x[i] = IR.BE("/", g, IR.BE("-", g, b[i], sigma), A[i][j...
great-expectations/great_expectations
great_expectations/cli/v012/project.py
Python
apache-2.0
3,445
0.001742
import sys import click from great_expectations import DataContext from great_expectations import exceptions as ge_exceptions from great_expectations.cli.v012.cli_messages import SECTION_SEPARATOR from great_expectations.cli.v012.toolkit import load_data_context_with_error_handling from great_expectations.cli.v012.ut...
ontext = DataContext(context_root_dir=target_directory) ge_config_version: int = context.get_config().config_version if int(ge_config_version) < CURRENT_GE_CONFIG_VERSION: upgrade_message: str = f"""The config_version of your great_expectations.yml -- {float(ge_config_version)} --
is outdated. Please consult the V3 API migration guide https://docs.greatexpectations.io/en/latest/guides/how_to_guides/migrating_versions.html and upgrade your Great Expectations configuration to version {float(CURRENT_GE_CONFIG_VERSION)} in order to take advantage of the latest capabilities. """ ...
gallantlab/pycortex
cortex/mapper/volume.py
Python
bsd-2-clause
7,345
0.006535
import numpy as np from scipy import sparse from . import Mapper from . import samplers class VolumeMapper(Mapper): @classmethod def _cache(cls, filename, subject, xfmname, **kwargs): from .. import db masks = [] xfm = db.get_xfm(subject, xfmname, xfmtype='coord') pia = db.get_...
) i101 = np.ravel_multi_index(( ceil[2], floor[1], ceil[0]), shape, mode='clip') i011 = np.ravel_multi_index(( ceil[2], ceil[1], floor[0]), shape, mode='clip')
i110 = np.ravel_multi_index((floor[2], ceil[1], ceil[0]), shape, mode='clip') i111 = np.ravel_multi_index(( ceil[2], ceil[1], ceil[0]), shape, mode='clip') v000 = (1-x)*(1-y)*(1-z) v100 = x*(1-y)*(1-z) v010 = (1-x)*y*(1-z) v110 = x*y*(1-z) v001 = (1-x)*(1-y)*z ...
dhtech/graphite-web
webapp/graphite/events/views.py
Python
apache-2.0
2,759
0.006887
import datetime import time from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.utils.timezone import localtime, now from graphite.util import json from graphite.events import models from graphite.render.attime import parseATTime from django.core.urlresol...
response = HttpResponse( "%s(%s)" % (request.REQUEST.get('jsonp'), json.dumps(fetch(request), cls=EventEncoder)), mimetype='text/javascript') else: response = HttpResponse( json.dumps(fetch(request), cls=EventEncoder), mimetype="appl
ication/json") return response def fetch(request): #XXX we need to move to USE_TZ=True to get rid of localtime() conversions if request.GET.get("from", None) is not None: time_from = localtime(parseATTime(request.GET["from"])).replace(tzinfo=None) else: time_from = datetime.datetime.fro...
aabilio/PyDownTV
Servers/televigo.py
Python
gpl-3.0
2,787
0.00757
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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) a...
ral Public License # alon
g with PyDownTV. If not, see <http://www.gnu.org/licenses/>. # Pequeña descripción de qué canal de tv es el módulo __author__="aabilio" __date__ ="$15-may-2011 11:03:38$" from Descargar import Descargar from utiles import salir, formatearNombre, printt import sys class TeleVigo(object): ''' Clase que...
tokyo-jesus/university
src/python/koans/python3/koans/about_packages.py
Python
unlicense
1,909
0.001048
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This is very different to AboutModules in Ruby Koans # Our AboutMultipleInheritan
ce class is a little more comparable # from runner.koan import * # # Package hierarchy of Python Koans project: # # contemplate_koans.py # koans/ # __init__.py # about_asserts.py # about_attribute_access.py # about_class_attributes.py # about_classes.py # ... #
a_package_folder/ # __init__.py # a_module.py class AboutPackages(Koan): def test_subfolders_can_form_part_of_a_module_package(self): # Import ./a_package_folder/a_module.py from .a_package_folder.a_module import Duck duck = Duck() self.assertEqual(__, duck.name) ...
JacquesLucke/still-lambda
vec2.py
Python
bsd-3-clause
470
0.014894
import math def add(vec_a, vec_b): return [vec_a[0]+vec_b[0], vec_a[1]+vec_b[1]] def sub(vec_a, vec_b): return [vec_a[0]-vec_b[0], vec_a[1]-vec_b[1]] def mul(vec, sca): return [vec[0]*sca, vec[1]*sca] def inner(vec_a, vec_b): return vec_a[0]*vec_b[0]+vec_a[1]*vec_b[1] def abs(vec): return math....
vec) return mul(vec, 1/length) def vecint(vec): return
[int(vec[0]), int(vec[1])]
SEA000/uw-empathica
empathica/gluon/restricted.py
Python
mit
9,911
0.003834
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <[email protected]> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import sys import cPickle import traceback import types import os import logging from storage import S...
%(layer)s\n\n%(traceback)s\n' % ticket_data) def _store_on_disk(self, request, ticket_id, ticket_data)
: ef = self._error_file(request, ticket_id, 'wb') try: cPickle.dump(ticket_data, ef) finally: ef.close() def _error_file(self, request, ticket_id, mode, app=None): root = request.folder if app: root = os.path.join(os.path.join(root, '..'),...