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
Magicjarvis/py
testing/root/test_error.py
Python
mit
1,750
0.002286
import py import errno def test_error_classes(): for name in errno.errorcode.values(): x = getattr(py.error, name) assert issubclass(x, py.error.Error) assert issubclass(x, EnvironmentError) def test_picklability_issue1(): e1 = py.error.ENOENT() s = py.std.pickle.dumps(e1) e2...
epr(excinfo.value) def test_checked_call_sup
ports_kwargs(tmpdir): import tempfile py.error.checked_call(tempfile.mkdtemp, dir=str(tmpdir)) try: import unittest unittest.TestCase.assertWarns except (ImportError, AttributeError): pass # required interface not available else: import sys import warnings class Case(unittest.TestCas...
wusung/ipython-notebook-tabs
kyper/nbformat/v40/nbbase.py
Python
apache-2.0
4,854
0.003502
"""Python API for composing notebook elements The Python representation of a notebook is a nested structure of dictionary subclasses that support attribute access (IPython.utils.ipstruct.Struct). The functions in this module are merely helpers to build the structs in the right form. """ # Copyright (c) IPython Develo...
'execute_result', 'display_data'}: output.metadata = NotebookNode() output.data = NotebookNode() # load from args: output.update(from_dict(kwargs)) if data is not None: output.data = from_dict(data)
# validate validate(output, output_type) return output def output_from_msg(msg): """Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output mes...
sijmenvos/Uforia-browser
nodejs/build_index/uf_func/uf_admin.py
Python
gpl-2.0
1,899
0.008952
#!/usr/bin/env python # Copyright (C) 2014 Hogeschool van Amsterdam # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version
. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even t
he implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. import uf_globals from ast import literal_eval import json def parse_admin_config(): """ The admin config file is in full JSON format. """ supmimetable = uf_globals.db...
Schevo/schevo
schevo/expression.py
Python
mit
1,535
0.003909
"""Utilities for forming search expressions based on field classes.""" # Copyright (c) 2001-2009 ElevenCraft Inc. # See LICENSE for details. import sys from schevo.lib import optimize from operator import and_, eq, or_ from schevo.base import Field class Expression(object): def __init__(self, left, op, right...
single_extent_field_equality_criteria() criteria.update(self.right.single_extent_field_equality_criteria()) if len(frozenset(key._extent for key in criteria)) > 1: raise ValueError( 'Not a single-extent field equality intersection criteria.') retur...
riteria.') optimize.bind_all(sys.modules[__name__]) # Last line of module.
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/amazon/ec2_asg_facts.py
Python
bsd-3-clause
13,766
0.001961
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
public-webserver-asg register: asgs failed_when: "{{ asgs.resu
lts | length > 1 }}" ''' RETURN = ''' --- auto_scaling_group_arn: description: The Amazon Resource Name of the ASG returned: success type: string sample: "arn:aws:autoscaling:us-west-2:1234567890:autoScalingGroup:10787c52-0bcb-427d-82ba-c8e4b008ed2e:autoScalingGroupName/public-webapp-production-1" auto...
JoKaWare/WTL-DUI
tools/grit/grit/gather/admin_template_unittest.py
Python
bsd-3-clause
3,990
0.006266
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Unit tests for the admin template gatherer.''' import os import sys if __name__ == '__main__': sys.path.append(os.path.join(o...
ture type="admin_template" name="IDAT_GOOGLE_DESKTOP_SEARCH" file="GoogleDesktop.adm" exclude_from_rc="true" /> <structure type="txt" name="BINGOBONGO" file="README.txt" exclude_from_rc="true" /> </structures> </release> <outputs> <output filen...
sive=True) return grd def testInGrd(self): grd = self.MakeGrd() cliques = grd.children[0].children[0].children[0].GetCliques() self.VerifyCliquesFromAdmFile(cliques) def testFileIsOutput(self): grd = self.MakeGrd() dirname = tempfile.mkdtemp() try: tool = build.RcBuilder() ...
rocky/python2-trepan
trepan/processor/command/set_subcmd/patsub.py
Python
gpl-3.0
1,775
0
# -*- coding: utf-8 -*- # Copyright (C) 2020 Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version....
s/>. # Our local modules from trepan.processor.command import base_subcmd as Mbase_subcmd class SetPatSub(Mbase_subcmd.DebuggerSubcommand): """**set patsub** *from-r
e* *replace-string* Add a substitution pattern rule replacing *patsub* with *replace-string* anywhere it is found in source file names. If a substitution rule was previously set for *from-re*, the old rule is replaced by the new one. In the following example, suppose in a docker container /mnt/project is the mount-p...
heromod/migrid
mig/shared/functionality/lsvgridmembers.py
Python
gpl-2.0
2,788
0.001076
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # lsvgridmembers - simple list of vgrid members for a grid with access # Copyright (C) 2003-2014 The MiG Project lead by Brian Vinter # # This file is part of MiG. # # MiG is free software: you can redistribute it and/or modify # it under the terms o...
as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # MiG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the imp
lied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,...
opendatapress/open_data_press
tests/test_helpers/test_config.py
Python
mit
730
0
# -*- coding: utf-8 -*- import os import unittest from helpers.config import l
oad_config, ConfigurationError class LoadConfigTest(unittest.TestCase):
def test_development_config(self): os.environ['SERVER_SOFTWARE'] = 'Dev-XXX' config = load_config() self.assertIsInstance(config, dict) self.assertTrue(config['debug']) def test_production_config(self): os.environ['SERVER_SOFTWARE'] = 'Live-XXX' config = load_con...
ramaseshan/symptomchecker
symptomcheck/src/profiles/apps.py
Python
gpl-2.0
226
0
from __future__ import unicode_literals from django.apps import AppC
onfig class ProfileConf
ig(AppConfig): name = "profiles" verbose_name = 'User Profiles' def ready(self): from . import signals # noqa
anomen-s/programming-challenges
gopas.cz/python_adv/4_pickle.py
Python
gpl-2.0
580
0
import pickle import shelve jmena = 'Petr,Jan,Tomáš'.split(',') with open('/tmp/jmena.bin', 'wb') as f: pickle.dump(jmena, f) pickle.dump(0x202073612020, f) pickle.dump({k: v for k, v in enumerate(jmena)}, f) with open('/tmp/jmena.bin', 'rb') as f: print(*[pickle.load(f) for
_ in range(3)], sep='\n') print('-' * 30) # shelve uses dbm database with shelve.open('/tmp/shelve.bin') as data: data['jmeno'] = 'Tomáš' data['dict'] = {1: 'erste', 2: 4545} with shelve.open('/tmp/shelve.bin') as data: print(data['jmeno']
) print(data['dict'])
makinacorpus/ionyweb
ionyweb/plugin_app/plugin_links_list/migrations/0003_auto__add_field_plugin_linkslist_title_rule.py
Python
bsd-3-clause
12,269
0.008069
# -*- coding: 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 field 'Plugin_LinksList.title_rule' db.add_column('plugin_links_list_plugin_linkslist', 'title_rule...
, {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank'
: 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'...
spulec/moto
moto/ec2/responses/reserved_instances.py
Python
apache-2.0
1,409
0.004258
from moto.core.responses import BaseResponse class ReservedInstances(BaseResponse): def cancel_reserved_instances_listing(self): if self.is_not_dryrun("CancelReservedInstances"): raise NotImplementedError( "ReservedInstances.cancel_reserved_instances_listing is not yet implemen...
if self.is_not_dryrun("CreateReservedInstances"): raise NotImplementedError( "ReservedInstances.create_reserved_instances_listing is not yet implemented" ) def describe_reserved_instances(self): raise NotImplementedError( "ReservedInstances.describe_reser...
cribe_reserved_instances_listings is not yet implemented" ) def describe_reserved_instances_offerings(self): raise NotImplementedError( "ReservedInstances.describe_reserved_instances_offerings is not yet implemented" ) def purchase_reserved_instances_offering(self): ...
alxgu/ansible
test/units/modules/network/onyx/test_onyx_config.py
Python
gpl-3.0
4,615
0.001517
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
r(TestOnyxConfigModule, self).setUp() self.mock_get_co
nfig = patch('ansible.modules.network.onyx.onyx_config.get_config') self.get_config = self.mock_get_config.start() self.mock_load_config = patch('ansible.modules.network.onyx.onyx_config.load_config') self.load_config = self.mock_load_config.start() self.mock_run_commands = patch('ansi...
thdb-theo/Zombie-Survival
docs/assets/Tools/build_cython.py
Python
mit
483
0
from distutils.core import setup from setuptools import Extension from Cython.Build import cythonize from Cython.Distutils
import build_ext extensions = [ Extension("src.cython_.angle_between", ["src/cython_/angle_between.pyx"]), Extension("src.cython_.collide", ["src/cython_/collide.pyx"]), Extension("tests.experiment.testcy", ["tests/e
xperiment/testcy.pyx"]) ] setup( ext_modules=cythonize(extensions), cmdclass={"build_ext": build_ext}, )
jamesyin96/conference_central
settings.py
Python
apache-2.0
494
0.002024
#!/usr/bin/env python """settings.py U
dacity conference server-side Python App Engine app user settings $Id$ created/forked from conference.py by wesc on 2014 may 24 """ # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '86908364842-sk7dtpvg5of9fr95pmgkndcg9r1t4osv.apps.googleusercontent.co...
replace with Android client ID' IOS_CLIENT_ID = 'replace with iOS client ID' ANDROID_AUDIENCE = WEB_CLIENT_ID
levisimons/CRASHLACMA
CRASHLACMA/twitter_json_parser.py
Python
cc0-1.0
2,983
0.041234
#!/usr/bin/python import json from pprint import pprint import re import urllib import time from geopy import geocoders import Image import os # TODO: handle test cases # testcases: # hollywood & vine, hollywood and vine # order of operations: hashtag, img, address, other text. # hashtag allcaps or lowercase # upload...
# parser useful fields from file of json tweet objects def get_data_from_tweets(self, input_data): g = geocoders.GoogleV3() tweet_data = [] processed_tweets = [] with open(input_data) as f: for line in f: if line.strip(): tweet_data = json.loads(line) tweet = tweet_data["text"]...
w+:\/\/\S+)"," ",tweet).split()) # geocode address to lat/long address, (lat, lng) = g.geocode(tweet_text) # TODO: this is a good place to validate the address for an LA coordinate. # if not LA, toss in a bucket to be human-examined # img uploaded via twitter if tweet_data["ent...
im-auld/moto
tests/test_dynamodb2/test_dynamodb_table_without_range_key.py
Python
apache-2.0
14,869
0.000538
from __future__ import unicode_literals import boto import boto3 from boto3.dynamodb.conditions import Key import sure # noqa from freezegun import freeze_time from boto.exception import JSONResponseError from moto import mock_dynamodb2 from tests.helpers import requires_boto_gte try: from boto.dynamodb2.fields i...
oDBConnection() conn.delete_item.when.called_with(
table_name='undeclared-table', key={"forum_name": {"S": "LOLCat Forum"}}, ).should.throw(JSONResponseError) @requires_boto_gte("2.9") @mock_dynamodb2 def test_query(): table = create_table() item_data = { 'forum_name': 'the-key', 'Body': 'http://url_to_lolcat.gif', 'Se...
Daniex/horizon
openstack_dashboard/api/base.py
Python
apache-2.0
12,076
0.000083
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
elf, other): """Merge another QuotaSet into this one. Existing quotas are not overridden. """ if not isinstance(other, QuotaSet): msg = "Can only add QuotaSet to Qu
otaSet, " \ "but received %s instead" % type(other) raise ValueError(msg) for item in other: if self.get(item.name).limit is None: self.items.append(item) return self def __len__(self): return len(self.items) def __repr__(self)...
eicher31/compassion-modules
mobile_app_connector/models/privacy_statement.py
Python
agpl-3.0
950
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2019 Compassion CH (http://www.compassion.ch) # @author: Emanuel Cino <ecino@compassion.ch> # @author: Théo Nikles <theo.nikles@gmail.com> # # The licence is in the file __manifest__.py #...
): lang = _get_lang(self, params) return {'PrivacyNotice': self.env['compassion.privacy.statement']
.with_context(lang=lang) .sudo().search([], limit=1).text}
Hybrid-Cloud/badam
patches_tool/aws_patch/aws_deps/libcloud/dns/drivers/google.py
Python
apache-2.0
11,423
0.000525
# 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 "License"); you may not ...
ecord(self, zone_id, record_id): """
Return a Record instance. :param zone_id: ID of the required zone :type zone_id: ``str`` :param record_id: ID of the required record :type record_id: ``str`` :rtype: :class:`Record` """ (record_type, record_name) = record_id.split(':', 1) ...
cornell-cup/cs-minibot-platform
python-interface/src/MiniBotFramework/Sound/live_audio_sample.py
Python
apache-2.0
3,940
0.038071
import numpy as np import matplotlib.pyplot as plt #Used for graphing audio tests import pyaudio as pa import wave from time import sleep #Constants used for sampling audio CHUNK = 1024 FORMAT = pa.paInt16 CHANNELS = 1 RATE = 44100 # Must match rate at which mic actually samples sound RECORD_TIMEFRAME = 1.0 #Time in s...
= pa.PyAudio() stream = rec_session.open(format=FORMAT, channels=CHANNELS,rate=RATE,input=True,frames_per
_buffer=CHUNK) print("Start recording") frames = [] # Sample audio frames for given time period for i in range(0, int(RATE/CHUNK*RECORD_TIMEFRAME)): data = stream.read(CHUNK) frames.append(data) # Close the recording session stream.stop_stream() stream.close() rec_session.terminate() #Create the wav fil...
ioef/tlslite-ng
unit_tests/test_tlslite_utils_ecc.py
Python
lgpl-2.1
8,381
0.000716
# Copyright (c) 2014, Hubert Kario # # See the LICENSE file for legal information regarding use of this file. # compatibility with Python 2.6, for that we need unittest2 package, # which is not available on 3.3 or 3.4 try: import unittest2 as unittest except ImportError: import unittest from tlslite.utils.ec...
5\x57\x3c\x1c\x06\x7f' b'\x0a\x06\x4d\x18\xbd\x0c\x81\x4e\xf7\x2a' b'\x8f\x76\xf8\x7f\x9b\x7d\xff\xb2\xf4\x26' b'\x36\x43\x43\x86\x
11\x89')) class TestDecoder(unittest.TestCase): def test_decode_P_256_point(self): point = ecdsa.NIST256p.generator * 379 data = bytearray(b'\x04' b'\x00\x55\x43\x89\x4a\xf3\xd0\x0e\xd7\xd7' b'\x40\xab\xdb\xd7\x5c\x96\xb0\x68\x77\xb7' ...
ruuk/script.module.password.storage
lib/keyring/backends/SecretService.py
Python
gpl-2.0
2,786
0.001077
import logging from ..util import properties from ..util import XDG from ..backend import KeyringBackend from ..errors import (InitError, PasswordDeleteError, ExceptionRaisedContext) try: import secretstorage import secretstorage.exceptions as exceptions except ImportError: pass log = logging.getLogg...
if collection.is_locked(): collection.unlock() if collection.is_locked(): # User dismissed the prompt raise InitError("Failed to unlock the collection!") return collection def get_password(self, service, username): """Get password of the username for...
llection() items = collection.search_items( {"username": username, "service": service}) for item in items: return item.get_secret().decode('utf-8') def set_password(self, service, username, password): """Set password for the username of the service """ ...
dnguyen0304/clare
clare/clare/application/download_bot/handlers.py
Python
mit
1,172
0
# -*- coding: utf-8 -*- from . import exceptions from clare import common from clare.common import messaging from clare.common import retry class NopHandler(messaging.consumer.interfaces.IHandler): def handle(self, record): pass def __repr__(self): repr_ = '{}()' return repr_.format...
andler = handler self._logger = logger def handle(self, record): try: self._handler.handle(record=record) except (exceptions.RoomExpired, retry.exceptions.MaximumRetry) as e: message = common.logging.utilities.format_exception(e=e) self._logger.debug(msg=...
self._logger)
nick-jonas/static-jspm-boiler
main.py
Python
unlicense
662
0.012085
import os import sys # Import the Flask Framework from flask import Flask, request, render_template isDev = os.environ["SERVER_SOFTWARE"].find('Development') == 0
app = Flask( __name__ ) # Note: We don't need to call run() since our application is embedded within # the App Engine WSGI application server. @app.route('/') def home(): return render_template( 'index.html', isDev=isDev ) @app.errorhandler(404) def page_not_found(e): """Return a custom 404 error.""" return ...
@app.errorhandler(500) def page_not_found(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: {}'.format(e), 500
ceholden/yatsm
yatsm/version.py
Python
mit
22
0
__versio
n__ =
'0.7.0'
altosaar/proximity_vi
inferences/proximity_variational_inference.py
Python
mit
5,782
0.006918
import tensorflow as tf import numpy as np import collections import time import util from .variational_inference import VariationalInference from inferences import proximity_statistics fw = tf.contrib.framework layers = tf.contrib.layers dist = tf.contrib.distributions class ProximityVariationalInference(Variatio...
* len(self.q_params) magnitude = self.magnitude if cfg['c/decay'] == 'linear': magnitude = tf.maximum(magnitude, 0.) for name, distance in self.distance.items(): distance_grad = tf.gradients(distance, self.q_params) for i in range(len(self.q_params)): if distance_grad[i] is not No...
update_norm = util.norm(update) fraction = tf.reduce_mean( update_norm / util.norm(self.q_neg_elbo_grad[i] + update)) fraction = tf.Print(fraction, [fraction], 'fraction: ') tf.summary.scalar('_'.join(['c/fraction_grad_d', name, param_name]), ...
barbieauglend/Learning_python
PT/FIPBruteForce.py
Python
unlicense
1,369
0.006574
import ftplib def connect(host, user, password): try: ftp = ftplib.FTP(host) ftp.login(user, password) ftp.quit()
return True except: return False def main(): # Variables targetHostAddress = '10.0.0.24' userName = 'bwayne' passwordsFilePath = 'passwords.txt' # Try to connect using anonymous credentials print('[+] Using anonymous credentials for ' + targetHostAddress) if connect(targe...
log on failed on host ' + targetHostAddress) # Try brute force using dictionary # Open passwords file passwordsFile = open(passwordsFilePath, 'r') for line in passwordsFile.readlines(): password = line.strip('\r').strip('\n') print('Testing: ' + str(password)) if(connect(targe...
nathanross/amiens
qlib/fq.audio_strict_long_hq.py
Python
apache-2.0
2,403
0.013317
#!/usr/bin/python3 # Copyright 2015 Nathan Ross # # 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...
return False bytes_per_second=(s/l) kbps=bytes_per_second*(8/1024.) print('fq`kbps:'+repr(kbps)) target_min_kbps=192 # note that even when set to a cbr, there's going # to sometimes be size variance /below/ that cbr # 0.96x-4 is an initial wild guess of a # generous lower...
n target {}'.format( repr(kbps), ((target_min_kbps*0.96)-4) )) return False return True callback=audio_strict_long_hq #chaneg these constants. GOAL_TARGET_KBPS=192. MIN_MINUTES=20 TARGET_KBPS=((GOAL_TARGET_KBPS*0.96)-4) BYTE_PS_TO_KBPS=(8/1024.) sql='AND totalAudioSize > ' + \ st...
fna/owning-a-home-api
mortgageinsurance/migrations/0003_change_type_va_first_use.py
Python
cc0-1.0
2,743
0.006198
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): for u in orm.Upfront.objects.all(): if u.va_first_use == 'Y': ...
ax_fico': ('django.db.models.fields.IntegerField', [], {}), 'max_loan_amt': ('django.db.models.fields.DecimalField', [], {'max_di
gits': '12', 'decimal_places': '2'}), 'max_ltv': ('django.db.models.fields.DecimalField', [], {'max_digits': '6', 'decimal_places': '3'}), 'min_fico': ('django.db.models.fields.IntegerField', [], {}), 'min_loan_amt': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', '...
gasevi/pyreclab
pypackage/__init__.py
Python
gpl-3.0
881
0.015891
import platform import sys if platform.system() == 'Darwin': native_version = (2, 7, 10, 'final'
, 0) cur_version = sys.version_info if cur_version == native_version: from pyreclab.libpyreclab_native_py import MostPopular, UserAvg, ItemAvg, SlopeOne, UserKnn, ItemKnn, SVD, IFAls, IFAlsConjugateGradient, BprMf else: # brew version from pyreclab.libpyreclab import MostPopular, UserAvg, ItemAvg,...
n, SVD, IFAls, IFAlsConjugateGradient, BprMf __all__ = [ 'MostPopular', 'UserAvg', 'ItemAvg', 'SlopeOne', 'UserKnn', 'ItemKnn', 'SVD', 'IFAls', 'IFAlsConjugateGradient', 'BprMf' ]
joequant/Fudge-Python
fudgemsg/tests/func_tests/test_deeper_msg.py
Python
apache-2.0
4,667
0.006642
#!/usr/bin/env python # # Copyrigh CERN, 2010. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. S
ee 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 # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://w...
nless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # im...
daonb/django-committee
src/committee/tests.py
Python
bsd-3-clause
7,138
0.004483
from datetime import datetime from django.test import TestCase from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth.models import User,Group,Permission from django.contrib.contenttypes.models import ContentType from annotatetext.models import Annotation from actstream.m...
tCommitteeList(self): res = self.client.get(reverse('committee-list')) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'committees/commit
tee_list.html') object_list = res.context['object_list'] self.assertEqual(map(just_id, object_list), [ self.committee_1.id, self.committee_2.id, ]) def testCommitteeMeetings(self): res = self.client.get(self.committee_1.get_absolute_url()) self.assertEqual(...
tic-ull/defensatfc-proto
tfc_webapps/packages/suds-timestamp/tests/saxenc.py
Python
agpl-3.0
1,564
0.002558
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) 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. # # This program is distributed in the hope that it will ...
e to \'play\' and sing "la,la,la";') print 'B(encoded)=\n%s' % b assert str(b) == xml print 'A(text-decoded)=\n%s' % a.getText() print 'B(text-decoded)=\n%s' % b.getText() assert a.getText() == b.getText() print 'test pruning' j = Element('A') j.set('n', 1) j.append(El
ement('B')) print j j.prune() print j
AoLab/SIMP
siml.py
Python
gpl-3.0
1,096
0
#!/usr/bin/env python3 # In The Name Of God # ======================================== # [] File Name : siml.py # # [] Creation Date : 27-04-2017 # # [] Created By : Pa
rham Alvani (parham.alvani@gmail.com) # ======================================= import click import yaml import os models = {} def load(package): for root, dirs, files in os.walk(package): for model_file in files: with open(os.path.join(root, model_file), 'r') as f: try: ...
continue click.echo('%s.%s' % (model['package'], model['name'])) models['%s.%s' % (model['package'], model['name'])] = model except Exception: pass for model_package in dirs: load(model_package) @click.command() @cli...
laroque/couchdb-python3
couchdb/view.py
Python
bsd-3-clause
7,191
0.000139
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007-2008 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Implementation of a view server for functions written in Python.""" from c...
om couchdb import json __all__ = ['main', 'run'] __docformat__ = 'restructuredtext en' log = logging.getLogger('couchdb.view') def run(input=sys.stdin, output=sys.stdout): r"""CouchDB view function handler implementation for Python. :param input: the readable file-like object to read input from :param ...
son(obj): obj = json.encode(obj) output.write(obj) output.write('\n') output.flush() def _log(message): if not isinstance(message, str): message = json.encode(message) _writejson({'log': message}) def reset(config=None): del functions[:] ...
ctogle/dilapidator
src/dilap/BROKEN/destruct.py
Python
mit
951
0.010515
import dilap.core.uinfo as di import dilap.core.sgraph as dsg import dilap.core.model as dm import dilap.io.io as dio import dilap.degenerate.overgrown as dog import pdb iotypes = dio.iotypes ############################################################################### ### simple functions which return simple dila...
################################# # dilapidors is a dict of funcs which return dilapidor objects d
ilapidors = { 'ivy':overgrown, } ###############################################################################
lamotriz/lavagem-a-seco
src/main.py
Python
gpl-2.0
8,904
0.005759
#!/usr/bin/env python # -*- coding: utf-8 -*- # # PROJETO LAVAGEM A SECO # # MAIN # # Felipe Bandeira da Silva # 26 jul 15 # import logging import tornado.escape import tornado.ioloop import tornado.web import tornado.options import tornado.websocket import tornado.httpserver import os.path from tornado.concurrent im...
ocessing.Queue() queue_joyz = multiprocessing.Queue() # anemometro queue_velocidade = multiprocessing.Queue() queue_direcao = multiprocessing.Queue() queue_distancia = multiprocessing.Queue() # usado para o controle da página pelo joystick queue_joy_botoes = multiprocessing.Queue() #class NavegadorWEB(multiprocessi
ng.Process): # def __init__(self): # multiprocessing.Process.__init__(self) # # self.navegador = subprocess.Popen(['epiphany-browser 192.168.42.1:8888'], stdout=subprocess.PIPE, \ # shell=True, preexec_fn=os.setsid) # # def run(self): # while True: # ...
tommasoberlose/p2p_gnutella
Constant.py
Python
mit
610
0.001639
PORT = "3000" LENGTH_PORT = 5 TTL = "2" LENGTH_TTL = 2 ERROR_PKT = "0000" LIST_PKT = [] LENGTH_PKTID = 16 LENGTH_FILENAME = 100 LENGTH_QUERY = 20 LENGTH_SECTION_IPV4 = 3 LENGTH_SECTION_IPV6 =
4 LENGTH_PACK = 1024 LENGTH_NCHUNK = 5
LENGTH_NCHUNKS = 6 LENGTH_HEADER = 10 CODE_QUERY = "QUER" CODE_ANSWER_QUERY = "AQUE" CODE_NEAR = "NEAR" CODE_ANSWER_NEAR = "ANEA" CODE_DOWNLOAD = "RETR" CODE_ANSWER_DOWNLOAD = "ARET" CODE_LOGO = "LOGO" FILE_COND = "FileCondivisi/" ERROR_FILE = "FILE_NOT_FOUND" NUM_NEIGHBOR = 3 START_RED = "\033[91m" END_RED = "\03...
osdlyrics/osdlyrics
python/metadata.py
Python
gpl-3.0
13,271
0.000678
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Tiger Soldier # # This file is part of OSD Lyrics. # # OSD Lyrics 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 ...
Arguments: - `title`: (string) The title of the track - `artist`: (string) The artist of the track - `album`: (string) The name of album that the track is in - `arturl`: (string) The URI of the picture of the cover of the album - `tracknum`: (int) The number of the track ...
- `length`: (int) The duration of the track in milliseconds. - `extra`: (dict) A dict that is intend to store additional properties provided by MPRIS1 or MPRIS2 DBus dicts. The MPRIS1-related values will be set in the dict returned by `to_mpris1`. The MP...
ACLARKNET/aclarknet-database
aclarknet/database/migrations/0040_auto_20170902_1841.py
Python
mit
694
0
# -*- coding: utf-8 -*- # Generated b
y Django 1.11.4 on 2017-09-02 22:41 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('database', '0039_auto_20170902_1834'), ] operations = [ migrations.RemoveField( model_name='companysettings'...
veField( model_name='service', name='company', ), migrations.RemoveField( model_name='testimonial', name='company', ), migrations.DeleteModel( name='CompanySettings', ), ]
chrisRubiano/TAP
dolar/ftp.py
Python
gpl-3.0
494
0.004049
from __future__ import print_function import os from ftplib import FTP def place_file(ftp, filename): ftp.storbinary('STOR ' + filename,open(fi
lename, 'rb')) if __name__ == '__main__': url = 'ftp.k-bits.com' ftp = FTP(url) user = 'usuario1@k-bits.com' passw = 'happy1234' ftp.login(user, passw) remoto = [] ftp.dir(remoto.append) for r in remoto: print(r) directorio_local = os.listdir(
'.') place_file(ftp, 'Banamex.csv') ftp.quit()
facebook/fbthrift
thrift/compiler/test/fixtures/basic/gen-py3lite/module/lite_metadata.py
Python
apache-2.0
13,649
0.010697
# # Autogenerated by Thrift # # DO NOT EDIT # @generated # import apache.thrift.metadata.lite_types as _fbthrift_metadata # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_MyStruct(metadata_struct: _fbthrift_...
tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_MyDataItem(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.MyDataItem" if qual
ified_name in metadata_struct.structs: return metadata_struct fields = [ ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=False, structured_annotations=[ ]) new_str...
tommyip/zulip
zerver/tests/test_mattermost_importer.py
Python
apache-2.0
22,277
0.002693
import os import ujson import filecmp import logging from typing import Dict, Any, List from zerver.lib.import_realm import ( do_import_realm, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.data_import.mattermost_user import UserHandler from zerver.data_import.mattermost import mattermo...
tion"], "A place for talking about Gryffindor common room") self.assertEqual(zerver_stream[0]["rendered_description"], "") self.assertEqual(zerver_stream[0]["realm"], 3) self.assertEqual(zerver_stream[1]["name"], "Gryffindor quidditch team") self.assertEqual(zerver_stream[1]["invite_onl...
ssertEqual(zerver_stream[1]["description"], "A place for talking about Gryffindor quidditch team") self.assertEqual(zerver_stream[1]["rendered_description"], "") self.assertEqual(zerver_stream[1]["realm"], 3) self.assertEqual(zerver_stream[2]["name"], "Dumbledores army") self.assertEqua...
dresen/praat
scripts/TextGrid.py
Python
mit
17,423
0.001148
import codecs import os import subprocess import sys from Tier import Tier from Interval import Interval from operator import itemgetter, attrgetter from numpy import array as nparray from praatNumericParser import parse as numParse from praatPitchParser import parse as pitchParse SCRIPT = '[TextGrid.py]: ' class Gri...
als) def confusionMatrixPair(self, tier1, tier2): """Computes the confusion pairs between a pair of tiers.""" assert tier1.size == tier2.size assert tier1.currentsize == tier2.currentsize confusiontbl = {} for n, i in enum
erate(tier1.intervals): key = tuple(sorted([i.text, tier2[n].text])) confusiontbl[key] = confusiontbl.get(key, 0) + 1 return confusiontbl def confusionMatrix(self, tiernames, filename): """Computes the confusion pairs between an arbitrary # of tiers.""" mat = {} ...
K-3D/k3d
tests/mesh/mesh.modifier.MorphPoints.py
Python
gpl-2.0
1,275
0.00549
#python import k3d import testing document = k3d.new_document() source1 = k3d.plugin.create("PolyCone", document) source2 = k3d.plugin.create("PolySphere", document) source3 = k3d.plugin.create("PolyCube", document) modifier =
k3d.plugin.create("MorphPoints", document) k3d.property.create(modifier,
"k3d::mesh*", "input1", "input1", "input1") k3d.property.create(modifier, "k3d::mesh*", "input2", "input2", "input2") k3d.property.create(modifier, "k3d::double_t", "amount1", "amount1", "amount1") k3d.property.create(modifier, "k3d::double_t", "amount2", "amount2", "amount2") k3d.property.connect(document, source1.ge...
pistatium/houkago_app
server_appengine/app/views/aff.py
Python
apache-2.0
1,179
0.000854
# coding: utf-8 from __future__ import absolute_import, division, print_function from django.http import HttpResponseRedirect from django.views.decorators.cache import cache_page from djan
go.core.urlresolvers import reverse from django.conf.urls import patterns fro
m app.models.app import App from app import views # -- Views -------------------------------------------- # ------------------------------------------------------ @cache_page(60 * 5) def to_home(request, app_id): app = App.getById(int(app_id)) if app: app.affiriate_point_total += 2 app.affir...
401LearningAnalytics/Project
server_side/upload.py
Python
mit
2,202
0.030427
#!/usr/bin/env python3 import sys import os import subprocess import time filename = sys.argv[1] print("extracting " + filename) p = subprocess.Popen(["unzip", filename, "-dintro"], stdout=subprocess.PIPE) p.communicate() p = subprocess.Popen(["php","-f","uploadtodb.php","intro/courses.csv","courses"],stdout=subproc...
p","intro/course_grades.csv","course_grades"],stdout=subprocess.P
IPE, universal_newlines=True) out, err = p.communicate() p = subprocess.Popen(["php","-f","uploadtodb.php","intro/course_modules.csv","course_modules"],stdout=subprocess.PIPE, universal_newlines=True) out, err = p.communicate() p = subprocess.Popen(["php","-f","uploadtodb.php","intro/course_lessons.csv","course_lesso...
hacktm15/caudexer
dexer/caudexer/migrations/0003_auto_20151107_1415.py
Python
mit
589
0
# -*- coding: utf-8 -*
- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('caudexer', '0002_auto_20151107_1409'), ] operations = [ migrations.AlterField( model_name='goodreadsdata', name='good_read...
name='google_book_id', field=models.CharField(max_length=100), ), ]
percyfal/snakemakelib
snakemakelib/exceptions.py
Python
mit
965
0
# Copyright (C) 2015 by Per Unneberg class NotInstalledError(Exception): """Error thrown if program/command/application cannot be found in path Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): sel...
tr): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code class OutputFilesException(Exception): """Error thrown if outputfiles missing or wrong number. Args: msg (st
r): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code
MPBA/pyHRV
pyphysio/tools/Tools.py
Python
gpl-3.0
51,184
0.004572
# coding=utf-8 from __future__ import division import numpy as _np from scipy.signal import welch as _welch, periodogram as _periodogram, freqz as _freqz import scipy.optimize as _opt import pycwt.wavelet as wave from scipy import linalg as _linalg import itertools as _itertools from ..BaseTool import Tool as _Tool fr...
assert refractory >= 0, "Refractory value should be non negative" _Tool.__init__(self
, delta=delta, refractory=refractory, start_max=start_max) @classmethod def algorithm(cls, signal, params): refractory = params['refractory'] if refractory == 0: # if 0 then do not skip samples refractory = 1 else: # else transform the refractory from seconds to samples ...
bardlean86/SNEK_TheReckoning
graphics.py
Python
mit
2,059
0.005342
import os import pygame as pg import glob import constants pg.display.init() video = pg.display screen = video.set_mode(constants.display_size) """ Preloads images and parameters """ images = glob.glob('*.png') image_cache = {} def get_image(path): img = image_cache.get(path) path = os.path.join('resources...
h.join('
resources', 'img', 'time_up.png')).convert()
Shopify/shopify_python_api
test/shipping_zone_test.py
Python
mit
446
0.002242
import shopify from test.test_helper import TestCase class ShippingZoneTes
t(TestCase): def test_get_shipping_zones(self): self.fake("shipping_zones", method="GET", body=self.load_fixture("shipping_zones")) shipping_zones = shopify.ShippingZone.find() self.assertEqual(1, len(shipping_zones)) self.assertEqual(shipping_zones[0].name, "Some zone") self...
untries))
rusucosmin/courses
ubb/fop/2015.Seminar.09/domain/IDObject.py
Python
mit
514
0.005837
class IDObject(): """ Base class for all objects having unique id within the application """ def __init__(self, objectId): """ Constructor method for bui
lding IDObject objectId - the unique objectId of the object in the app
lication """ self._objectId = objectId def getId(self): """ Return the object's unique id """ return self._objectId def testIDObject(): obj = IDObject(133) assert obj.getId() == 133
crakensio/django_training
lib/python2.7/site-packages/bpython/inspection.py
Python
cc0-1.0
8,924
0.000784
# Th
e MIT License # # Copyright (c) 2009-2011 the bpython authors. # # 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, m...
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 IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANT...
cryptapus/electrum-myr
gui/qt/paytoedit.py
Python
mit
9,506
0.00242
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@gitorious # # 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 witho...
iline(): e.ignore() return QPlainTextEdit.keyPressEvent(self, e) ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier) if self.c is None or (ctrlOrShift and e.text().isEmpty()): return eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\...
(e.modifiers() != Qt.NoModifier) and not ctrlOrShift; completionPrefix = self.textUnderCursor() if hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)): self.c.popup().hide() return if completionPrefix != self.c.completio...
smira/aptly
system/t06_publish/swift.py
Python
mit
7,962
0.003893
from swift_lib import SwiftTest def strip_processor(output): return "\n".join([l for l in output.split("\n") if not l.startswith(' ') and not l.startswith('Date:')]) class SwiftPublish1Test(SwiftTest): """ publish to Swift: from repo """ fixtureCmds = [ "aptly repo create -distribution=m...
wiftPublish5Test, self).check() self.check_exists('
dists/sq1') self.check_not_exists('dists/sq2') self.check_exists('pool/main/') self.check_not_exists('pool/main/p/pyspi/pyspi_0.6.1-1.3.dsc') self.check_not_exists('pool/main/p/pyspi/pyspi_0.6.1-1.3.diff.gz') self.check_not_exists('pool/main/p/pyspi/pyspi_0.6.1.orig.tar.gz') ...
popazerty/enigma2
lib/python/Plugins/Extensions/LDteam/ExtraActionBox.py
Python
gpl-2.0
1,524
0.022966
# -*- coding: utf-8 -*- from enigma import * from Screens.Screen import Screen from Components.ActionMap import ActionMap from Components.MenuList import MenuList from Components.GUIComponent import GUIComponent from Components.HTMLComponent import HTMLComponent from Tools.Directories import fileExists, SCOPE_SKIN_IMAG...
aActionBox" position="center,center" size="560,70" title=" "> <widget font="Regular;20" halign="center" name="message" position="10,10" size="538,48" valign="center" /> </screen>""" def __init__(self, session, message, title, action): Screen.__init__(self, session) self.session = session self.ctitle = title...
"] = Label(message) self["logo"] = Pixmap() self.timer = eTimer() self.timer.callback.append(self.__setTitle) self.timer.start(200, 1) def __setTitle(self): if self["logo"].instance is not None: self["logo"].instance.setPixmapFromFile(resolveFilename(SCOPE_CURRENT_SKIN, '/usr/lib/enigma2/python/Plugins...
eduNEXT/edunext-platform
lms/djangoapps/email_marketing/models.py
Python
agpl-3.0
5,191
0.002697
""" Email-marketing-related models. """ from config_models.models import ConfigurationModel from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class EmailMarketingConfiguration(ConfigurationM...
plate to use on purchasing a course seat. Deprecated " ) ) # Sailthru purchases can be tagged with interest tags to provide information about the types of courses # users are interested in. The easiest way to get the tags currently is the Sailthru content API which # looks in the content libra...
ourse discovery API) This option should normally be on, but it does add overhead to processing # purchases and enrolls. sailthru_get_tags_from_sailthru = models.BooleanField( default=True, help_text=_('Use the Sailthru content API to fetch course tags.') ) sailthru_content_cache_age = ...
CityOfNewYork/NYCOpenRecords
tests/functional/test_requests.py
Python
apache-2.0
170
0.005882
# -*- coding: utf-8
-*- """Test Request Module This module contains the tests for the OpenRecords `/request`
endpoint. """ import pytest from app.models import Requests
sean-/patroni
tests/test_patroni.py
Python
mit
7,260
0.001102
import datetime import patroni.zookeeper import psycopg2 import subprocess import sys import time import unittest import yaml from mock import Mock, patch from patroni.api import RestApiServer from patroni.dcs import Cluster, Member, Leader from patroni.etcd import Etcd from patroni.exceptions import DCSError, Postgre...
ember self.p.postgresql.data_directory_empty = true self.p.ha.dcs.initialize = true self.p.postgresql.initialize = true self.p.postgresql.start = true self.p.ha.dcs.get_cluster = get_cluster_not_initialized_without_leader self.p.initialize() self.p.ha.dcs.initial...
self.p.initialize() self.p.ha.dcs.get_cluster = get_cluster_initialized_without_leader self.assertRaises(SleepException, self.p.initialize) self.p.postgresql.data_directory_empty = false self.p.initialize() self.p.ha.dcs.get_cluster = get_cluster_not_initialized_with_l...
ContinuumIO/datashape
datashape/typesets.py
Python
bsd-2-clause
5,475
0.000731
""" Traits constituting sets of types. """ from itertools import chain from .coretypes import (Unit, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float16, float32, float64, complex64, complex128, bool_, Decimal, TimeDelta, Option) __all__ = ['TypeSet', 'm...
name='integral') floating = TypeSet(float32, float64, name='floating') comp
lexes = TypeSet(complex64, complex128, name='complexes') boolean = TypeSet(bool_, name='boolean') real = TypeSet(*integral | floating, name='real') numeric = TypeSet(*integral | floating | complexes, name='numeric') scalar = TypeSet(*boolean | numeric, name='scalar') supertype_map = { int8: signed, int16: si...
oeeagle/quantum
neutron/tests/unit/services/vpn/test_vpnaas_extension.py
Python
apache-2.0
26,021
0.000038
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
pdate an ikepolicy.""" ikepolicy_id = _uuid() update_data = {'ikepolicy': {'name': 'ikepolicy1',
'encryption_algorithm': 'aes-256'}} return_value = {'name': 'ikepolicy1', 'auth_algorithm': 'sha1', 'encryption_algorithm': 'aes-256', 'phase1_negotiation_mode': 'main', 'lifetime'...
mpercich/Calendarize
ios/dateparser/lib/python2.7/site-packages/dateparser/freshness_date_parser.py
Python
mit
3,641
0.001648
# -*- coding: utf-8 -*- from __future__ import unicode_literals import regex as re from datetime import datetime from datetime import time from dateutil.relativedelta import relativedelta from dateparser.utils import apply_timezone, localize_timezone from .parser import time_parser _UNITS = r'year|month|week|day|h...
date = self.now + td else: date = self.now - td return date, period def get_kwargs(self, date_string): m = PATTERN.
findall(date_string) if not m: return {} kwargs = {} for num, unit in m: kwargs[unit + 's'] = int(num) return kwargs def get_date_data(self, date_string, settings=None): date, period = self.parse(date_string, settings) return dict(date_obj=d...
interlegis/sapl
sapl/compilacao/models.py
Python
gpl-3.0
66,332
0.000167
from django.contrib import messages from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import F, Q from django.db.models.aggregates import Max from django.db.models.deletion import PROTECT from dj...
=True, default=None, related_name='perfil_parent_set', on_delete=PROTECT,
verbose_name=_('Perfil Herdado')) class Meta: verbose_name = _('Perfil Estrutural de Texto Articulado') verbose_name_plural = _('Perfis Estruturais de Textos Articulados') ordering = ['-padrao', 'sigla'] def __str__(self): return self.nome @property def parents(self...
SelvorWhim/competitive
Codewars/ThinkingTestingAB.py
Python
unlicense
217
0.013825
# patt
ern seems to be multiplying every pair of digits from different numbers and adding them up from itertools import product def test_it(a, b): return sum(int(d1)*int(d2) for
d1,d2 in product(str(a), str(b)))
Yelp/pyes
tests/test_percolator.py
Python
bsd-3-clause
3,235
0.006182
# -*- coding: utf-8 -*- from __future__ import absolute_import import unittest from .estestcase import ESTestCase from pyes.query import * import unittest class PercolatorTestCase(ESTestCase): def setUp(self): super(PercolatorTestCase, self).setUp() mapping = { u'parsedtext': {'boost': 1.0, ...
est_percolator(self): resu
lts = self.conn.percolate('test-index', 'test-type', PercolatorQuery({'name': 'iphone'})) self.assertTrue('test-perc1' not in results['matches']) self.assertTrue('test-perc2' in results['matches']) self.assertTrue('test-perc3' not in results['matches']) def test_or(self): results = ...
puittenbroek/slimmermeten
slimmermeten/settings/base.py
Python
bsd-3-clause
9,633
0.001661
""" This is your project's main settings file that can be committed to your repo. If you need to override a setting locally, use local.py """ import os import logging # Normally you should not import ANYTHING from Django directly # into your settings, but ImproperlyConfigured is an exception. from django.core.excepti...
USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = False # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a...
rope/Amsterdam' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) MIDDLEWARE_CLASSES = [ ...
dex4er/django-pyc
test_project/tests.py
Python
lgpl-3.0
333
0
from django.cor
e.management import call_command from django.test import TestCase class ClearCache(TestCase): @staticmethod def test_compilepyc(): call_command('compilepyc', 'django_pyc', verbosity=1, force=True) @staticmethod def test_clearpyc():
call_command('clearpyc', verbosity=1, force=True)
resamsel/dbmanagr
src/dbmanagr/driver/sqlite/driver.py
Python
gpl-3.0
1,308
0
# -*- coding: utf-8 -*- # # Copyright © 2014 René Samselnig # # This file is part of Database Navigator. # # Database Navigator is free software: you can redistribute it a
nd/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Database Navigator is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied war...
f # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Database Navigator. If not, see <http://www.gnu.org/licenses/>. # import logging from dbmanagr.logger import LogWith from...
BourbonWarfare/POTATO
tools/build.py
Python
gpl-2.0
2,898
0.006901
#!/usr/bin/env python3 import os import sys import subprocess ######## GLOBALS ######### MAINPREFIX = "z" PREFIX = "potato_" ########################## def tryHemttBuild(projectpath): hemttExe = os.path.join(projectpath, "hemtt.exe") if os.path.isfile(hemttExe): os.chdir(projectpath) ret = su...
ing obsolete file => " + file) os.remove(file) print("") for p in os.listdir(addonspath): path = os.path.join(addonspath, p) if not os.path.isdir(path): continue if p[0] == ".": continue if not check_for_changes(addonspath, p):...
try: subprocess.check_output([ "makepbo", "-NUP", "-@={}\\{}\\addons\\{}".format(MAINPREFIX,PREFIX.rstrip("_"),p), p, "{}{}.pbo".format(PREFIX,p) ], stderr=subprocess.STDOUT) except: failed += 1...
CalebM1987/pyshp
shapefile.py
Python
mit
47,927
0.005529
""" shapefile.py Provides read and write support for ESRI Shapefiles. author: jlawhead<at>geospatialpython.com date: 2015/06/22 version: 1.2.3 Compatible with Python versions 2.4-3.x version changelog: Reader.iterShapeRecords() bugfix for Python 3 """ __version__ = "1.2.3" from struct import pack, unpack,...
"""A shape object of any type.""" def __init__(self, shape=None, record=None): self.shape = shape self.record = record class ShapefileException(Exception): """An exception to handle shapefile specific problems.""" pass class Reader: """Reads the three files of a shapefile a...
t or separately. If one of the three files (.shp, .shx, .dbf) is missing no exception is thrown until you try to call a method that depends on that particular file. The .shx index file is used if available for efficiency but is not required to read the geometry from the .shp file. The "sh...
datoszs/analysis
datoszs/remote.py
Python
mit
504
0
import os import spiderpig as sp @sp.configured() def get_filename(filename, ssh_host=None, data_dir=None): if ssh_host is None: return filename else: local_copy = '{}/local_copy/{}'.format(data_dir, filename) if not os.path.exists(lo
cal_copy): dirs = os.path.dirname(local_copy) if not os.path.exists(dirs): os.makedirs(dirs) os.system("scp {}:{} {}".format(ssh_host, filename, local
_copy)) return local_copy
axelniklasson/adalyzer
backend/location_optimisation.py
Python
mit
1,650
0.033939
from sklearn import cluster import numpy as np import datetime #import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt class Location: vehicle_data = None @staticmethod def get_data(): if Location.vehicle_data is not None: return Location.vehicle_data.tolist() else: return None @sta...
e): classes_count[clusters[i], 0] = clusters[i] classes_count[clusters[i], 1] += 1 sorted = classes_count[classes_count[:,1].argsort()] cluster_locations = np.empty([count,2]) c = 0 for j in range(sorted[:,0].size-1, sorted[:,0].size - count - 1, -1): cluster_locations[c] = kmeans.cluster_centers_[so...
x') #plt.plot(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], 'bo') #plt.legend(('Data', 'Centroids'), loc='upper left') #plt.show() #plt.savefig('plt-gen-' + datetime.datetime.now().isoformat() + '.png') #plt.close(fig) Location.vehicle_data = cluster_locations
lishuwnc/DCGAN
main.py
Python
apache-2.0
10,297
0.0101
import tensorflow as tf import tensorflow.contrib.slim as slim import pprint import os from datasets import dataset_factory from dcgan import dcgan_generator, dcgan_discriminator from train import dcgan_train_step from tensorflow.python.training import optimizer from collections import OrderedDict from utils import g...
.DEFINE_integer('save_summaries_secs', 10, 'How often, in seconds, to save the summary [10]') flags.DEFINE_integer('sample_n', 16, 'How many images the network will produce in a sample process [16]') flags.DEFINE_integer('unrolled_step', 0, 'Unrolled step in surrogate loss for generator [0]') def extract_update_dict(u...
es()} for u in update_ops: var_name = u.op.inputs[0].name var = name_to_var[var_name] value = u.op.inputs[1] if u.op.type == 'Assign': update_map[var.value()] = value elif u.op.type == 'AssignAdd': update_map[var.value()] = value + var else: raise ValueError('Undefined unroll...
alirizakeles/tendenci
tendenci/apps/base/migrations/0002_auto_20150804_1545.py
Python
gpl-3.0
342
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(mig
rations.Migration): dependencies = [ ('base', '0001_initial'), ] operations = [ migrations.AlterModelOptions(
name='checklistitem', options={}, ), ]
tony/django-docutils
django_docutils/favicon/scrape.py
Python
mit
2,207
0
#!/usr/bin/env python import logging import sys from urllib.parse import urljoin import requests from lxml import html from six.moves.urllib.parse import urlparse from django_docutils.exc import BasedException logger = logging.getLogger(__name__) def _request_favicon(url): """Tries to download favicon from URL...
gies failed """.format( url=url ) ) if __name__ == '__main__': favicon = get_favicon(sys.argv[1]) file_ = open('/U
sers/me/favicon.ico', 'wb') file_.write(favicon) file_.close()
tareqalayan/pytest
_pytest/_code/source.py
Python
mit
14,033
0.000356
from __future__ import absolute_import, division, generators, print_function import ast from ast import PyCF_ONLY_AST as _AST_FLAG from bisect import bisect_right import linecache import sys import six import inspect import tokenize import py cpy_compile = compile class Source(object): """ a immutable object ho...
ect. if filename is None invent an artificial filename which displays the source/line position of the caller frame. """ if not filename or py.path.local(filename).check(file=0): if _genframe is None: _genframe = sys._ge
tframe(1) # the caller fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno base = "<%d-codegen " % self._compilecounter self.__class__._compilecounter += 1 if not filename: filename = base + '%s:%d>' % (fn, lineno) else: ...
mcallaghan/tmv
BasicBrowser/scoping/migrations/0295_doc_tslug.py
Python
gpl-3.0
369
0
# Generated by Django 2.2 on 2019-06-20 09:39 from django.db import migrations, models class Migration(
migr
ations.Migration): dependencies = [ ('scoping', '0294_titlevecmodel'), ] operations = [ migrations.AddField( model_name='doc', name='tslug', field=models.TextField(null=True), ), ]
rocky/python2-trepan
trepan/processor/cmdbreak.py
Python
gpl-3.0
5,057
0.002571
# -*- coding: utf-8 -*- # # Copyright (C) 2009, 2010, 2015, 2017-2018 Rocky Bernstein # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) ...
'if': location = '.' condition = text[text.find('if ')+3:] elif text == '': location = '.' condition = None else: try: bp_expr = build_bp_expr(text) except LocationError as e: proc.errmsg("Error in parsing breakpoint expression
at or around:") proc.errmsg(e.text) proc.errmsg(e.text_cursor) return INVALID_PARSE_BREAK except ScannerError as e: proc.errmsg("Lexical error in parsing breakpoint expression at or around:") proc.errmsg(e.text) proc.errmsg(e.text_cursor) ...
mozilla/mozilla-ignite
apps/badges/tests/view_tests.py
Python
bsd-3-clause
1,703
0
from badges.models import SubmissionBadge from badges.tests.base_tests import BadgesBaseTest from django.core.urlresolvers import reverse from timeslot.tests.fixtures import create_user, create_submission class BadgesSubmissionTest(BadgesBaseTest): def setUp(self): # Ignite fixtures are setup on the Badg...
lished) url = reverse('entry_show', kwargs={'entry_id': self.submission.id, 'phase': 'ideas'}) response = self.client.get(url) self.assertEqual(len(response.context['badge_list']), 1) def test_hidden_submission_badges(self):
"""Test the hidden badges are not shown on the Submission page""" data = { 'submission': self.submission, 'badge': self.badge_a, 'is_published': False, } SubmissionBadge.objects.create(**data) url = reverse('entry_show', kwargs={'entry_id': ...
klmitch/glance
glance/api/v2/image_tags.py
Python
apache-2.0
4,348
0
# Copyright 2012 OpenStack Foundation # 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 requ...
nguage governing
permissions and limitations # under the License. import glance_store from oslo_log import log as logging from oslo_utils import encodeutils import webob.exc from glance.api import policy from glance.api.v2 import images as v2_api from glance.common import exception from glance.common import utils from glance.commo...
stxnext/intranet-open
src/intranet3/intranet3/views/presence.py
Python
mit
3,777
0.002648
# -*- coding: utf-8 -*- import datetime from babel.core import Locale from sqlalchemy import func from pyramid.view import view_config from intranet3.utils.views import BaseView from intranet3.models import User, PresenceEntry, Late, Absence, DBSession from intranet3 import helpers
as h from intranet3.utils import excuses day_start = datetime.time(0, 0, 0) day_end = datetime.time(23, 5
9, 59) hour_9 = datetime.time(9, 0, 0) locale = Locale('en', 'US') @view_config(route_name='presence_list', permission='can_view_presence') class List(BaseView): def get(self): date = self.request.GET.get('date') if date: date = datetime.datetime.strptime(date, '%d.%m.%Y') els...
Alem/django-jfu
demo/demo/wsgi.py
Python
bsd-3-clause
1,208
0.011589
""" WSGI config for demo project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` set...
'demo.settings' SITE_ROOT = os.path.dirname(os.path.dirname( __file__ )) site.addsitedir( SITE_ROOT + '/venv/local/lib/python2.7/site-packages' ) sys.path.append( SITE_ROOT ) exc_dir = 'scripts' if os.name == 'nt' else 'bin' venv = '%s/venv/%s/activate_this.py' % (SITE_R
OOT, exc_dir ) activate_env = os.path.expanduser( venv ) execfile( activate_env, dict(__file__ = activate_env )) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
marinkaz/orange3
Orange/canvas/application/addons.py
Python
bsd-2-clause
26,262
0.00019
import sys import sysconfig import os import re import errno import shlex import shutil import subprocess import itertools import concurrent.futures from site import USER_SITE from glob import iglob from collections import namedtuple, deque from xml.sax.saxutils import escape from distutils import version import pkg_...
lable): return False elif item.installable is None: return False else: inst, dist = item try: v1 = version.StrictVersion(dist.version) v2 = version.StrictVersion(inst.version) except ValueError: pass else: return v1 ...
tyledItemDelegate): """ A QStyledItemDelegate which properly toggles Qt.ItemIsTristate check state transitions on user interaction. """ def editorEvent(self, event, model, option, index): flags = model.flags(index) if not flags & Qt.ItemIsUserCheckable or \ not option...
lilleswing/deepchem
deepchem/models/tests/test_predict.py
Python
mit
1,924
0.003119
""" Tests that deepchem models make deterministic predictions. """ __author__ = "Bharath Ramsundar" __copyright__ = "Copyright 2016, Stanford University" __license__ = "MIT" import os import tempfile import numpy as np import unittest import sklearn import shutil import tensorflow as tf import deepchem as dc from ten...
sifier from sklearn.ensemble import RandomForestRegressor class TestPredict(test_util.TensorFlowTestCase): """ Test that models make d
eterministic predictions These tests guard against failures like having dropout turned on at test time. """ def setUp(self): super(TestPredict, self).setUp() self.current_dir = os.path.dirname(os.path.abspath(__file__)) ''' def test_tf_progressive_regression_predict(self): """Test tf progres...
SneakersInc/sniffmypacketsv2
src/sniffmypacketsv2/transforms/common/packetParser.py
Python
apache-2.0
2,024
0.003953
#!/usr/bin/env python # Welcome to Gobbler, the Scapy pcap parser and dump scripts # Part of the sniffMyPackets suite http://www.sniffmypackets.net # Written by @catalyst256 / catalyst256@gmail.com import datetime from layers.http import * from layers.BadLayers import * from auxtools import error_logging import loggi...
ns import OrderedDict bind_layers(TCP, HTTP) def rename_layer(x
, n): n = n.lower().replace(' ', '_').replace('-', '_').replace('.', '_') + '_' return dict((n+k.lower(), f(v) if hasattr(v, 'keys') else v) for k, v in x.items()) def find_layers(pkts, pcap, pcap_id, streamid): packet = OrderedDict() count = 1 pcap_id = pcap_id.encode('utf-8') streamid = stre...
SpiderOak/flowbot
src/decorators.py
Python
mpl-2.0
1,211
0
from functools import wraps def mentioned(bot_command): """Only execute the decorated bot command if the bot was mentioned.""" @wraps(bot_command) def _func(bot, message, *args, **kwargs): if bot.mentioned(message): return bot_command(bot, message, *args, **kwargs) return _func d...
unc(bot, message, *args, **kwargs): if bot.from_channel_admin(message): return bot_command(bot, message, *args, **kwargs) return _func def org_admin_only(bot_command): """Only execute the decorated bot command if the user is an admin."
"" @wraps(bot_command) def _func(bot, message, *args, **kwargs): if bot.from_org_admin(message): return bot_command(bot, message, *args, **kwargs) return _func
alixedi/recline
recline.py
Python
mit
3,765
0.031076
from bottle import template, route, run, request from imp import load_source from argparse import ArgumentParser from os.path import basename, splitext from subprocess import check_output import os class ScriptRender(object): """Render a script as an HTML page.""" def __init__(self, script): self.script = scrip...
ripts.') parser.add_argument('script', type=file) if __name__ == '__main__': args = parser.parse_args() global __R__ __R__ = ScriptRender(args.script.name) r
un(host='localhost', port=8080)
adsabs/ADSDeploy
ADSDeploy/tests/test_functional/test_integration_tester.py
Python
gpl-3.0
5,702
0.000702
#!/usr/bin/env python # encoding: utf-8 """ Functional tests of the RabbitMQ Workers """ import mock import json import unittest import ADSDeploy.app as app from ADSDeploy.pipeline.workers import IntegrationTestWorker, \ DatabaseWriterWorker from ADSDeploy.webapp.views import MiniRabbit from ADSDeploy.models imp...
the database is being written to when a test passes """ # Stub data packet = { 'application': 'adsws', 'environment': 'staging',
'version': 'v1.0.0', } expected_packet = packet.copy() expected_packet['tested'] = True mocked_run_test.return_value = expected_packet # Start the IntegrationTester worker params = { 'RABBITMQ_URL': RABBITMQ_URL, 'exchange': 'test', 's...
henrygd/All-Seas-Client-Database-Application
app.py
Python
mit
5,574
0.001435
from flask import Flask, render_template, request, jsonify, \ redirect, url_for, session, send_file from functools import wraps import sqlite3 import subprocess import sql_clients # creates application object app = Flask(__name__) # encrypts sessions app.secret_key = 'long random string' # decorator redirects t...
ept: result = "error1" return jsonify(result=result) # returns full client information for specific id @app.route('/openclient') @login_required def openclient(): clientid = (request.args.get('b'),) with sqlite3.connect('clients.db') as conn: c = conn.cursor() c.execute("SELECT...
ct(id=row[0], name=row[1], birthdate=row[2], email=row[3], phone=row[4], address=row[5], citystate=row[6], notes=row[7], favoriteline=row[8], cabintype=row[9], diningtime=row[10], travelswith=row[11], trips=row[12]) for row in c.fetchall()]...
ravibhure/ansible
test/units/module_utils/basic/test_argument_spec.py
Python
gpl-3.0
18,173
0.002751
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_functio...
if 'type' in argspec['arg']: type_ = getattr(builtins, argspec['arg']['type']) else: type_ = str assert isinstance(am.params['arg'], type_) assert am.params['arg'] == expected @pytest.mark.parametrize('stdin', [{'arg':
42}], indirect=['stdin']) def test_validator_function(mocker, stdin): # Type is a callable MOCK_VALIDATOR_SUCCESS = mocker.MagicMock(return_value=27) argspec = {'arg': {'type': MOCK_VALIDATOR_SUCCESS}} am = basic.AnsibleModule(argspec) assert isinstance(am.params['arg'], int) assert am.params['...
ConPaaS-team/conpaas
conpaas-client/setup.py
Python
bsd-3-clause
705
0.005674
#!/usr/bin/env python from setuptools import setup CPSVERSION = '204' long_description = """ ConPaaS: an integrated runtime environment for elastic Cloud applications ========================================================================= """ setup(name='cpsclient', version=CPSVERSION, description='Co...
nt', author='ConPaaS team', author_email='info@conpaas.eu', url='http://www.conpaas.eu/', download_url='http://www.conpaas.eu/download/', license='BSD', packages=['cps',], scripts=['cpsclient.py'], install_requ
ires=['cpslib'], dependency_links=[ 'http://www.conpaas.eu/dl/cpslib-%s.tar.gz' % CPSVERSION, ],)
appsembler/mayan_appsembler
apps/dynamic_search/models.py
Python
gpl-3.0
2,130
0.001878
from __future__ import absolute_import import urlparse import urllib from datetime import datetime from django.db import models from django.utils.translation import ugettext as _ from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.utils.encoding import smart_unicode, ...
ment_search = SearchModel.get('documents.Document') query_dict = urlparse.parse_qs(urllib.unquote_plus(smart_str(self.query))) if self.is_advanced(): # Advanced search advanced_string = [] for key, value in query_dic
t.items(): search_field = document_search.get_search_field(key) advanced_string.append(u'%s: %s' % (search_field.label, smart_unicode(' '.join(value)))) display_string = u', '.join(advanced_string) else: # Is a simple search display_string = s...
mhbu50/erpnext
erpnext/hr/report/employee_birthday/employee_birthday.py
Python
gpl-3.0
1,261
0.025377
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def get_columns(...
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(filters["month"]) + 1 con
ditions += " and month(date_of_birth) = '%s'" % month if filters.get("company"): conditions += " and company = '%s'" % \ filters["company"].replace("'", "\\'") return conditions
drogenlied/qudi
qtwidgets/plotwidget_modified.py
Python
gpl-3.0
3,362
0.001785
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This file contains the modified PlotWidget for Qudi. Qudi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) an...
the received event ev with all the properties of a Qt mouse # press event. QtWidgets.QGraphicsView.mousePressEvent(self, ev) # this signal will be catched by othe
r methods if the mouse was clicked # inside the PlotWidget. self.sigMouseClick.emit(ev) if not self.mouseEnabled: return self.mousePressPos = ev.pos() self.clickAccepted = ev.isAccepted() if not self.clickAccepted: self.scene().clearSelection() ...
autostack/pytest-ansible
pytest_ansible/node.py
Python
mit
1,681
0
#!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from pytest_ansible.utils import memoize import threading import os class Facts(dict): PREF = 'ansible_' def __getattr__(self, attr): try: ...
y def name(self): return self._name @property def inventory(self): return self._inventory @memoize def get_node(name, inventory): ''' Generating Node object base on given ansible host instance :param name: host name :param inventory: inventory manager instance :return:...
return Node(name, inventory)
171121130/SWI
venv/Lib/site-packages/openpyxl/cell/__init__.py
Python
mit
149
0
from __future__ import absolute_import #
Copyright (c) 2010-2017 openpyxl from .cell import Cell, WriteOnlyCell from .read_only import ReadOnlyCell
Penaz91/Glitch_Heaven
Game/libs/lasergen.py
Python
mit
1,000
0.002
# Laser Generator Library # Part of the Glitch_Heaven Project # Copyright 2015-2016 Penaz <penazarea@altervista.org> import pygame from os.path import join as pjoin def generate(size, vertical=False, image=None): if image is Non
e: graphics = pygame.image.load(pjoin("resources", "sprites", "laser.png")).convert_alpha() else: graphics = image if vertical: plat = pygame.surface.Surface((32, size), pygame.SRCALPHA, 32) graphics = pygame.transform.rotate(graphics, 90) for i in
range(0, size, 32): plat.blit(graphics, (0, i)) else: plat = pygame.surface.Surface((size, 32), pygame.SRCALPHA, 32) for i in range(0, size, 32): plat.blit(graphics, (i, 0)) return plat.convert_alpha() if __name__ == "__main__": pygame.init() screen = pygame.disp...