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
xaroth8088/sprite-magic
models/sprite_sheet.py
Python
gpl-3.0
1,116
0.019713
""" A SpriteSheet is the overall collection of individual frames (which may be spread across files) that define one layer of the final sprite. """ from models.sprite_action import SpriteAction class SpriteSheet(): def __init__( self, data, group_name ): if "file_path" not in data: raise "file_...
sheet you mean" self.file_path = data.get( "file_path" ) self.group_name = group_name self.name = data.get( "name", "Unnamed Layer" ) self.layer = data.get( "layer", "Unspecified Layer"
) self.credit_name = data.get( "credit_name", "Unknown Artist" ) self.credit_url = data.get( "credit_url", "" ) self.license = data.get( "license", "Not specified (do not use this artwork without explicit written permission from the artist!)" ) self.actions = {} avail_actions = ...
DirectXMan12/nova-hacking
nova/openstack/common/rpc/proxy.py
Python
apache-2.0
9,391
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012-2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2....
rn {'method': method, 'namespace': namespace, 'args': kwargs} def make_msg(self, method, **kwargs): return self.make_namespaced_msg(meth
od, self.RPC_API_NAMESPACE, **kwargs) def _serialize_msg_args(self, context, kwargs): """Helper method called to serialize message arguments. This calls our serializer on each argument, returning a new set of args that have been serialized. ...
mintuhouse/shotfactory
build/scripts-2.6/browsershot.py
Python
gpl-3.0
2,045
0.000489
#!/usr/bin/python # browsershots.org - Test your web design in different browsers # Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org> # # Browsershots 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 Foundatio...
:0)") parser.add_option("-w", dest="wait", action="store", type="int",
metavar="<seconds>", default=5, help="wait before taking screenshots (default 5)") (options, args) = parser.parse_args() config = {'width': 1024, 'bpp': 32} system = platform.system() if system == 'Linux': from shotfactory04.gui import linux gui = linux....
darksteelcode/authorship
mainNeuralClassifier.py
Python
gpl-3.0
1,669
0.00719
import numpy as np import calcFeatures import calcAuthor import AUTHORS from classifiers import neural debug = True authors = ["Jane Austen", "Walter Scott", "Arthur Conan Doyle", "Charles Dickens", "Mark Twain", "Louisa Alcott"] #Index coresponds to authors array textDirs = ["texts/Jane_Austen", "texts/Walter_Scott", ...
uresCalculated = [] #Features Authors featuresAuthors = [] authorNum = 0 for directory in textDirs: c = calcAuthor.CalcAuthorBatch(directory, True, sampleLength, False) featuresCalculated.append(c.calcFeatures()) featuresAuthors.append(np.zeros(c.getNumSamples(), dtype=np.int)) featuresAuthors[len(featu...
= np.concatenate(featuresAuthors) classifier = neural.NeuralNetworkClassifier(sum(calcAuthor.LENGTHS), len(textDirs)) classifier.train(samples, sampleAuthors) trainingAccuracy = classifier.testAccuracy(samples, sampleAuthors) testSamples, testSamplesAuthors = AUTHORS.getSamplesAndAuthors("texts/Unknown", authors, deb...
alphagov/notifications-admin
tests/app/main/views/uploads/test_upload_hub.py
Python
mit
10,939
0.000457
import re import pytest from flask import url_for from freezegun import freeze_time from app.formatters import normalize_spaces from tests.conftest import ( SERVICE_ONE_ID, create_active_caseworking_user, create_active_user_with_permissions, create_platform_admin_user, ) @pytest.mark.parametrize('ex...
p.job_api_client.get_jobs', return_value={'data': []}) service_one['permissions'] += ['letter', 'upload_letters'] page = client_request.get('main.uploads', service_id=SERVICE_ONE_ID) assert page.find('h1').text == 'Uploads' assert page.find('a', text=re.compile('Upload a letter')).attrs['href'] == url_f...
ain.upload_letter', service_id=SERVICE_ONE_ID ) uploads = page.select('tbody tr') assert len(uploads) == 3 assert normalize_spaces(uploads[0].text.strip()) == ( 'Uploaded letters ' 'Printing today at 5:30pm ' '33 letters' ) assert uploads[0].select_one('a.file-list-fil...
nuigroup/pymt-widgets
tests/test_textinput.py
Python
lgpl-3.0
345
0.011594
''' test usage of MTTextInput widget ''' from init import test, import_pymt_window def instance(): import_pymt_window() from pymt import MTTextInput from pymt import css_add_sheet, css_reload try: t = MTText
Input() return
True except: return False def unittest_mttextinput(): test(instance())
EmanueleCannizzaro/scons
test/Execute.py
Python
mit
4,013
0.002492
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
"h.in\n") test.write('i.in', "i.in\n") test.write('j.in', "j.in\n") test.write('k.in', "k.in\n") test.write('l.in', "l.in\n") test
.write('m.in', "m.in\n") import sys if sys.platform == 'win32': expect = r"""scons: \*\*\* Error 1 scons: \*\*\* Error 2 scons: \*\*\* nonexistent.in/\*\.\*: (The system cannot find the path specified|Das System kann den angegebenen Pfad nicht finden)""" else: expect = r"""scons: \*\*\* Error 1 scons: \*\*\* E...
GNOME/libical-glib
tests/value.py
Python
lgpl-2.1
3,063
0.019589
#!/usr/bin/env python3 #GI_TYPELIB_PATH=$PREFIX/lib/girepository-1.0/ ./value.py ############################################################################### # # Copyright (C) 2015 William Yu <williamyu@gnome.org> # # This library is free software: you can redistribute it and/or modify it # under the terms of versi...
nd); assert (kind_string == "ATTACH"); converted_kind = ICalGLib.Value.string_to_kind (kind_string); assert (converted_kind == kind); szText = "This is a text\nand this is a new line"; after_encoded_szText = "This is a text\\nand this is a new line"; before_decoded_szText = "This is a text\\\nand this is a new line"; ...
after_encoded_szText); result = ICalGLib.Value.decode_ical_string (before_decoded_szText); assert (result == szText);
lukas/ml-class
examples/keras-audio/audio_utilities.py
Python
gpl-2.0
13,234
0.002342
import scipy.io.wavfile from os.path import expanduser import os import array from pylab import * import scipy.signal import scipy import wave import numpy as np import time import sys import math import matplotlib import subprocess # Author: Brian K. Vogel # brian.vogel@gmail.com fft_size = 2048 iterations = 300 hop...
ormalize. max_sample = np.max(abs(x_reconstruct)) if max_sample > 1.0: x_reconstruct = x_reconstruct / max_sample return x_reconstruct def hz_to_mel(f_hz): """Convert Hz to mel scale. This uses the formula from O'Shaugnessy's book. Args: f_hz (float): The value in Hz. Ret...
hz(m_mel): """Convert mel scale to Hz. This uses the formula from O'Shaugnessy's book. Args: m_mel (float): The value in mels Returns: The value in Hz """ return 700*(10**(m_mel/2595) - 1.0) def fft_bin_to_hz(n_bin, sample_rate_hz, fft_size): """Convert FFT bin index to f...
csparpa/check
fluentcheck/tests/tests_check/test_file_formats.py
Python
mit
2,101
0
import unittest from fluentcheck.classes import Check from fluentcheck.exceptions import CheckError class TestFileFormatAssertions(unittest.TestCase): # noinspection PyUnresolvedReferences def test_is_yaml(self): res = Check("hello").is_yaml() self.assertIsInstance(res, Check) try: ...
es, Check) try: Check("v
alid_yaml").is_not_yaml() self.fail() except CheckError: pass # noinspection PyUnresolvedReferences def test_is_xml(self): obj = """<Agenda> <type>gardening</type> <Activity> <type>cooking</type> </Activity> </Agenda>""" res = Check(obj)...
finger563/editor
src/view_attributes.py
Python
mit
3,890
0.000257
''' These classes specify the attributes that a view object can have when editing views ''' __author__ = 'William Emfi
nger' __copyright__ = 'Copyright 2016, ROSMOD' __credits__ =
['William Emfinger', 'Pranav Srinivas Kumar'] __license__ = 'GPL' __version__ = '0.4' __maintainer__ = 'William Emfinger' __email__ = 'emfinger@isis.vanderbilt.edu' __status__ = 'Production' from meta import Attribute objects = ['Container', 'Association'] # model related class Object(Attribute): tooltip = 'Wha...
DamienIrving/ocean-analysis
data_processing/mom_to_cmip.py
Python
mit
5,922
0.003715
""" Filename: mom_to_cmip.py Author: Damien Irving, irving.damien@gmail.com Description: convert MOM data files to be like ACCESS-CM2 CMIP6 files """ # Import general Python modules import sys, os, pdb import argparse import numpy as np import xarray as xr import iris import cf_units import cmdline_proven...
nargs.ref_var) if inargs.single: cube_list = iris.cube.CubeList([]) for mom_file in inargs.mom_files: print(mom_file) dset = xr.open_dataset(mom_file, decode_times=False) cube = xr_to_cube(dset, re
f_cube, inargs) cube_list.append(cube) outcube = gio.combine_cubes(cube_list) else: dset = xr.open_mfdataset(inargs.mom_files, decode_times=False, combine='by_coords') outcube = xr_to_cube(dset, ref_cube, inargs) outcube.attributes['history'] = cmdprov.new_log(git_repo=...
mbohlool/client-python
kubernetes/test/test_v1_list_meta.py
Python
apache-2.0
913
0.003286
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://g
ithub.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_list_meta import V1ListMeta class TestV1ListMeta(unittest.TestCase): """ V1ListMet...
ME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1_list_meta.V1ListMeta() pass if __name__ == '__main__': unittest.main()
sparkslabs/kamaelia_
Sketches/MPS/Random/MSChooser.py
Python
apache-2.0
3,281
0.019506
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
if self.loop: self.index = 0 else: self.index = len(self.items)-1 elif msg == "PREV": self.index = self.index - 1 if self.index < 0: if self.loop: self.index ...
self.index = 0 elif msg == "FIRST": self.index = 0 elif msg == "LAST": self.index = 1 try: self.send( self.items[self.index], "outbox") except IndexError: pass done = self.shutdown() __kamaelia...
JoeOsborn/hyped
player/__init__.py
Python
mit
69
0
_
_al
l__ = ["engine", "graphics", "input", "data", "rrt", "profiler"]
shft117/SteckerApp
erpnext/stock/doctype/delivery_note/test_delivery_note.py
Python
agpl-3.0
15,964
0.024618
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe import json import frappe.defaults from frappe.utils import cint, nowdate, nowtime, cstr, add_days, flt from erpnext.stoc...
_hand_account = frappe.db.get_value("Account", {"warehouse": "_T
est Warehouse - _TC"}) prev_bal = get_balance_on(stock_in_hand_account) dn = create_delivery_note() gl_entries = get_gl_entries("Delivery Note", dn.name) self.assertTrue(gl_entries) stock_value_difference = abs(frappe.db.get_value("Stock Ledger Entry", {"voucher_type": "Delivery Note", "voucher_no": dn....
inirudebwoy/AutobahnPython
autobahn/twisted/websocket.py
Python
mit
23,106
0.002337
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 with...
og.debug("Connection to/from {peer} was aborted locally",
peer=self.peer) elif isinstance(reason.value, ConnectionLost): # The following is ridiculous, but the treatment of reason.value.args # across py2/3 and tx and over various corner cases is deeply fucked up. if hasattr(reason.value, 'message'):...
nasirali1/CerebralCortex
cerebralcortex/data_processor/signalprocessing/ecg.py
Python
bsd-2-clause
16,830
0.003446
# Copyright (c) 2017, MD2K Center of Excellence # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
ata)): if item.start_time.timestamp() <= ecg_raw_timestamp_array[i] <
= item.end_time.timestamp(): ecg_filtered_array.append(ecg.data[i]) final_index = i initial_index = final_index ecg_filtered.data = ecg_filtered_array return ecg_filtered def compute_rr_intervals(ecg: DataStream, ecg_quality: DataS...
ziv17/SRT-tools
srtFix/src/srtFix/processFile.py
Python
mit
3,797
0.022913
''' Created on Mar 28, 2016 @author: Ziv ''' class MyClass(object): ''' classdocs ''' def __init__(self, params): ''' Constructor ''' import sys import os from getArgs import getParams from parse import parse __all__ = [] __version__ = 0.1 __date__ = '2015-05-24' __...
d a separating line - an empty line" for line in f: if line == '\n': break else: print('empty line not found') #get the next
sub (num, time, text) = getNextSub(f) #get the last sub (a, b, c) = getNextSub(f) while a is not None: (num, time, text) = (a, b, c) (a, b, c) = getNextSub(f) #now we have the last sub return convertSubTimetoSec(time[0:12]) def calculateOffset(params): "Set fixed fi...
sgallagher/anaconda
pyanaconda/modules/storage/partitioning/specification.py
Python
gpl-2.0
6,228
0.000803
# # Copyright (C) 2009 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
t of the disk. This is mainly used to make sure /boot ends up in front, and any special (PReP, appleboot, etc.) partitions end up in front of /boot. This value means nothing unless lv and btr are both False. required_space -- This value is o...
e containing VG must be for this PartSpec to even get used. The VG's size is calculated before any other LVs are created inside it. If not enough space exists, this PartSpec will never get turned ...
sonntagsgesicht/regtest
.aux/venv/lib/python3.9/site-packages/sphinx/builders/latex/nodes.py
Python
apache-2.0
1,051
0
"""
sphinx.builders.latex.nodes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Additional nodes for LaTeX writer. :copyright: Copyrig
ht 2007-2021 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from docutils import nodes class captioned_literal_block(nodes.container): """A node for a container of literal_block having a caption.""" pass class footnotemark(nodes.Inline, nodes.Referential, nodes.TextElement...
nickhand/nbodykit
benchmarks/conftest.py
Python
gpl-3.0
3,880
0.006443
import pytest import numpy from nbodykit.lab import UniformCatalog, LogNormalCatalog from nbodykit.cosmology import LinearPower from nbodykit.transform import CartesianToSky class BenchmarkingSample(object): """ An object to generate catalog source objects for benchmarking for various sample configuration....
roperty
def N(self): return getattr(self, '_N', getattr(self, self.name)['N']) @N.setter def N(self, val): self._N = val @property def cosmo(self): from nbodykit.cosmology import Planck15 return Planck15 @property def redshift(self): return 0. def data(se...
magul/pywikibot-core
pywikibot/families/vikidia_family.py
Python
mit
639
0
# -*- coding: ut
f-8 -*- """Family module for Vikidia.""" # # (C) Pywikibot team, 2010-2016 # # Distributed under the terms of the MIT licen
se. # from __future__ import absolute_import, unicode_literals from pywikibot import family class Family(family.SubdomainFamily): """Family class for Vikidia.""" name = 'vikidia' domain = 'vikidia.org' codes = ['ca', 'de', 'en', 'es', 'eu', 'fr', 'it', 'ru', 'scn'] # Sites we want to edit but...
josephturnerjr/boatshoes
runtests.py
Python
isc
376
0.00266
import unittest import tests.test_daemon_context import tests.test_single_instance test_modules = [ tests.test_single_instance, tests.test_daemon_context, ] suite = unittest.TestSuite() for module in test_modules: suite.addTest(unittest.defaultTestLoader.loadTestsFro...
ite)
nishad89/newfies-dialer
newfies/dialer_audio/urls.py
Python
mpl-2.0
681
0.002937
# # Newfies-Dialer License # http://www.newfies-dialer.org # # This Source Code Form is subject to t
he terms of the Mozilla Public # License,
v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid <info@star2billing.com> # from django.conf.urls import patterns urlpatterns = patterns(...
gatoravi/python_chennai_jul2016
code/parsing_logs_arun.py
Python
cc0-1.0
991
0.007064
import re def check_patterns(): patterns_list = [] #Read patterns file with open("patterns.txt") as patterns1: for line in patterns1: line = line.rstrip("\n") patterns_list.append(line) print(patterns_list) #Read log file with open("Sample Logs.txt") as log...
line) if match != None:
log_line.lstrip(" ") count = int(match.group(1)) host = match.group(2) if count > 100: print(host, " Has count > 100") print(log_line) def rstrip_example(): s1 = "hello" s1 = s...
ella/mypage
mypage/widgets/management/commands/__init__.py
Python
bsd-3-clause
1,936
0.001033
from django.core.management.base import NoArgsCommand from mypage.widgets.conf import settings class LockedCommand(NoArgsCommand): help = 'helper command that locks iteslf and kills predecessors' cachelock = settings.MYPAGE_COMMAND_CACHELOCK cachelock_timeout = settings.MYPAGE_COMMAND_CACHELOCK_TIMEOUT ...
mple cache lock mechanism
""" from os import getpid, kill, path, remove import time from mypage.widgets.storage import storage if self.cachelock is not None: # cache lock - to ensure this command is run only once at a time l = storage.get(self.cachelock) if l is not None...
acutesoftware/lifepim
setup.py
Python
gpl-3.0
1,101
0.011807
from setuptools import setup
setup( name='lifepim', version='0.0.3', author='Duncan Murray', author_email='djmurray@acutesoftware.com.au', packages=['lifepim', 'lifepim.web_app'], url='https://github.com/acutesoftware/lifepim', license='GNU General Public License v3 (GPLv3)', description='Personal Information Mana...
maurozucchelli/dipy
dipy/info.py
Python
bsd-3-clause
3,570
0.007283
""" This file contains defines parameters for dipy that we use to fill settings in setup.py, the dipy top-level docstring, and for building the docs. In setup.py in particular, we exec this file, so it cannot import dipy """ # dipy version information. An empty _version_extra corresponds to a # full release. '.dev'...
_version_micro, _version_extra) CLASSIFIERS = ["Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent"...
"Topic :: Scientific/Engineering"] description = 'Diffusion MRI utilities in python' # Note: this long_description is actually a copy/paste from the top-level # README.txt, so that it shows up nicely on PyPI. So please remember to edit # it only in one place and sync it correctly. long_description = """ ====== DiP...
shrinidhi666/rbhus
tests/sockTest.py
Python
gpl-3.0
472
0.036017
#!/usr/bin/python import socket import sys print "pass1" clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "pass2" try: print "pass3" clientSocket.settimeout(4) prin
t "pass4" clientSocket.connect(("192.168.1.7",6660)) print "pass5" print("Connected to client") sockstatus = 1 except: print("Screwed pingClientProcess sock connect : client : "+ str(
sys.exc_info())) sockstatus = 0 try: clientSocket.close() except: pass
endreman0/Excalibot
excalibot/cogs/optins.py
Python
gpl-3.0
6,536
0.029376
import discord from discord.ext.commands import guild_only from .. import db from ..core import command, format class Optins(metaclass=command.Cog): @guild_only() @command.group(name='optin', aliases=['giveme']) async def base_command(self, ctx, *roles: discord.Role): """Opt into the given roles. Multiple roles c...
eturn await ctx.send('BAKA! That role is already an
optin!') settings.optin_roles.append(OptinRole(id=role.id)) await ctx.send('Opt-in added! Use `{}optin "{}"` to get it!', ctx.prefix, role.name) add.example_usage = """ `{prefix}optin add "foo bar"` - allow opting into the "foo bar" role """ @base_command.command() async def create(self, ctx, *, nam...
joehewitt/devon
devon/makers/mac/diskImage.py
Python
bsd-3-clause
3,981
0.006782
import devon.maker from devon.tags import * import datetime, os.path, shutil # ************************************************************************************************** class DiskImage(devon.maker.MakerManyToOne): path = "hdiutil" def getTarget(self, project): return "%s.dmg" % project....
os.makedirs(dirName) def __createFiles(self, project, target): pkginfoPath = os.path.join(target, "Contents", "Pkginfo") if not os.path.exists(pkginfoPath) or self.__newerThanProject(pkginfoPath, project): f = file(pkginfoPath, "w") f.write(project.signature) ...
projectPath = os.path.join(devon.projectsFileName, project.path) projectTime = datetime.datetime.fromtimestamp(os.stat(projectPath).st_mtime) sourceTime = datetime.datetime.fromtimestamp(os.stat(sourcePath).st_mtime) return sourceTime > projectTime def getDirectorySize(path): size = 0 f...
nwjs/chromium.src
tools/grit/grit/tool/postprocess_unittest.py
Python
bsd-3-clause
1,889
0.007941
#!/usr/bin/env python3 # 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 test that checks postprocessing of files. Tests postprocessing by having the postprocessor modify the grd data tree,...
def Process(self, rctext, rcpath, grdnode): smarter = re.compile(r'(DUMMY)(.*)') messages = grdnode.children[2].children[2] for node in messages.children:
name_attr = node.attrs['name'] m = smarter.search(name_attr) if m: node.attrs['name'] = 'SMART' + m.group(2) return grdnode if __name__ == '__main__': unittest.main()
floydwch/kaggle-cli
kaggle_cli/common.py
Python
mit
1,733
0.001731
import sys import os import pickle import re import getpass from mechanicalsoup import Browser from .config import CONFIG_DIR_NAME def login(username=None, password=None): if username is None: username = input('Please provide username: ') if password is None: password = getpass.getpass('Plea...
str(login_page.soup) ).group(1) login_result_page = browser.post( login_url, data={ 'username': username, 'password': password, '__RequestVerificationToken': token } ) error_match = re.search( '"errors":\["(?P<error>.+)"\]', ...
(1)) return if not os.path.isdir(config_dir_path): os.mkdir(config_dir_path, 0o700) with open(pickle_path, 'wb') as f: pickle.dump(dict( username=username, password=password, browser=browser ), f) return browser
itbabu/django-oscar
src/oscar/apps/basket/migrations/0002_auto_20140827_1705.py
Python
bsd-3-clause
1,749
0.002859
# -*- coding: utf-8 -*- from __future__ import unicode_literals fro
m django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('partner', '0001_initial'), ('catalogue', '0001_initial'), ('basket', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ...
='lineattribute', name='option', field=models.ForeignKey(verbose_name='Option', to='catalogue.Option'), preserve_default=True, ), migrations.AddField( model_name='line', name='basket', field=models.ForeignKey(verbose_name='Basket', ...
Sticklyman1936/workload-automation
wlauto/workloads/anomaly2/__init__.py
Python
apache-2.0
2,354
0.001699
# Copyright 2014-2015 ARM Limited # # 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 w...
king each one. Scores
reported are intended to represent overall perceived quality of the game, based not only on raw FPS but also factors like smoothness. """ package = 'com.elevenbitstudios.anomaly2Benchmark' activity = 'com.android.Game11Bits.MainActivity' loading_time = 30 asset_file = 'obb:com.elevenbitstu...
ankitmathur3193/song-cli
song/commands/MusicWebsiteParser/MusicWebsiteParser.py
Python
mit
346
0.031792
class MusicWebsiteParser: ''' Base class for music website parsers Every parser needs to implement it ''' def
Parse(self,url): '''It will parse the html page specified by url and return the resource url from where the music file needs to be downloaded ''' raise NotImplementedError('Y
ou must implement the Parse() method yourself!')
precice/aste
src/partition_mesh.py
Python
gpl-3.0
17,758
0.001746
#!/usr/bin/env python3 import argparse import logging import math import os from typing import List import numpy as np import shutil from ctypes import * import json import platform def main(): args = parse_args() logging.basicConfig(level=getattr(logging, args.logging)) mesh_name = args.in_meshname a...
bmetispath = os.path.join(binpath, "libmetisAPI"+ext) elif os.path.isfile(os.path.join(libpath, "libmetisAPI"+ext)): libmetispath = os.path.join(libpath, "libmetisAPI"+ext) else: raise Exception("libmetisAPI"+ext+" cannot fo
und!") libmetis = cdll.LoadLibrary(libmetispath) idx_t = c_int if libmetis.typewidth() == 32 else c_longlong cell_count = idx_t(len(mesh.cells)) point_count = idx_t(len(mesh.points)) num_parts = idx_t(numparts) partition = (idx_t * len(mesh.points))() cell_ptr = (idx_t * len(cellPtr))(*cellP...
Spiderlover/Toontown
toontown/launcher/ToontownLauncher.py
Python
mit
8,767
0.00365
import os import sys import time import types ltime = 1 and time.localtime() logSuffix = '%02d%02d%02d_%02d%02d%02d' % (ltime[0] - 2000, ltime[1], ltime[2], ltime[3], ltime[4], ltime[5]) logfile = 'toontownD-' + logSuffix + '.log' class LogAndOutput: def __init__(self,...
y) self.chatEligibleKey = 0 if 'chatEligible' in dict: self.chatEligibleKey = dict['chatEligible'] else: self.notify.warning('no chatEligible token in webAcctParams') self.notify.info('chatEligibleKey = %d' % s
elf.chatEligibleKey) def getBlue(self): blue = self.getValue(self.toontownBlueKey) self.setValue(self.toontownBlueKey, '') if blue == 'NO BLUE': blue = None return blue def getPlayToken(self): playToken = self.getValue(self.toontownPlayTokenKey) self...
ActiveState/code
recipes/Python/231516_Using/recipe-231516.py
Python
mit
802
0.009975
# start --- config.ini --- # --*-- python --*-- enemy = "Dr. No" salary = 100 def tax(salary): return salary * 0.2 bond = employee(id = "007", salary=salary * 2, tax=tax(salary * 2)) # end --- config.ini --- # start --- readconf.py ---
class employee: def __init__(self, id, salary, tax): self.id = id self.salary = salary self.tax = tax #FIXME: No error checking is done (to simplify code) def read_conf(filename, optnames): '''Read config
uration file return elements hash''' # Load file & eval h = {} execfile(filename, globals(), h) # Get only what we want options = {} for item in h: if isinstance(h[item], employee) or (item in optnames): options[item] = h[item] return options # end --- readconf.py ---
un33k/django-toolware
toolware/__init__.py
Python
mit
127
0
__author__ = 'Val Neekman [
neekware.com]' __description
__ = 'This application handles all common tasks.' __version__ = '1.0.6'
ATIX-AG/ansible
lib/ansible/modules/network/f5/bigip_profile_dns.py
Python
gpl-3.0
20,772
0.001541
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # 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', ...
ired: no use_local_bind: no enable_dns_firewall: yes password: secret server: lb.mydomain.com state: present user: admin delegate_to: localhost ''' RETURN = r''' enable_dns_express: description: Whether DNS Express is enabled on the resource or not. returned: changed type: bool sample...
True enable_zone_transfer: description: Whether zone transfer are enabled on the resource or not. returned: changed type: bool sample: False enable_dnssec: description: Whether DNSSEC is enabled on the resource or not. returned: changed type: bool sample: False enable_gtm: description: Whether GTM is ...
mozilla/mrburns
smithers/smithers/data_types.py
Python
mpl-2.0
340
0
DOWNLOAD = '0' PRIVACY = '1' OPPORTUNITY = '2' ACCESSIBILITY = '3' FREEDOM = '4' EDUCATION = '5' C
ONTROL = '6' types_map = { PRIVACY: 'privacy', OPPORTUNITY: 'opportunity', ACCESSIBILITY: 'access', FREEDOM: 'freedom', EDUCATION: 'learning', CONTROL: 'control', } name_to_id = {v: k
for k, v in types_map.items()}
ResearchSoftwareInstitute/MyHPOM
hs_access_control/tests/test_provenance_function.py
Python
bsd-3-clause
58,013
0.000172
from django.test import TestCase from django.contrib.auth.models import Group from hs_access_control.models import UserResourceProvenance, UserResourcePrivilege, \ GroupResourceProvenance, GroupResourcePrivilege, \ UserGroupProvenance, UserGroupPrivilege, \ PrivilegeCodes from hs_core import hydroshare fr...
resource=bikes, user=john), PrivilegeCodes.CHANGE) self.assertTrue( is_equal_to_as_set( UserResourcePrivilege.get_undo_users( resource=bikes, grantor=george), [alva])) self.assertTrue(
is_equal_to_as_set( UserResourcePrivilege.get_undo_users( resource=bikes, grantor=alva), [john])) record = UserResourceProvenance.get_current_record( resource=bikes, user=john) self.assertEqual(record.resource, bik...
fireball-dft/fireball-fireball
tests/06.methane/energies_components.py
Python
gpl-3.0
1,017
0.019666
pathebs= 'ebs.txt' docuebs= open(pathebs, 'w') pathke= 'ke.txt' docuke= open(pathk
e, 'w') pathvna= 'vna.txt' docuvna= open(pathvna, 'w') pathvxc= 'vxc.txt' docuvxc= open(pathvxc, 'w') pathvnl= 'vnl.txt' docuvnl= open(pathvnl, 'w') for n in range(1, 200): if n <
10: pathSour1= '00%d.ENERGIES' % n if n >= 10 and n < 100: pathSour1= '0%d.ENERGIES' % n if n >= 100: pathSour1= '%d.ENERGIES' % n docuSour1 = open(pathSour1) l =0 for line in docuSour1: l = l+1 m =0 docuSour1 = ope...
Acehaidrey/incubator-airflow
tests/providers/microsoft/azure/hooks/test_azure_cosmos.py
Python
apache-2.0
10,134
0.003552
# # 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...
oint, {'masterKey': self.test_master_key}) mock_cosmos.assert_has_calls(expected_calls) @mock.patch('airflow.providers.microsoft.azure.hooks.cosmos.CosmosClient') def test_cre
ate_container_default(self, mock_cosmos): hook = AzureCosmosDBHook(azure_cosmos_conn_id='azure_cosmos_test_key_id') hook.create_collection(self.test_collection_name) expected_calls = [ mock.call().CreateContainer('dbs/test_database_default', {'id': self.test_collection_name}) ...
cadencewatches/frappe
frappe/core/doctype/workflow/workflow.py
Python
mit
1,714
0.026838
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document class Workflow(Document): def validate(self): self.set_act
ive() self.create_custom_field_for_workflow_state() self.update_default_workflow_status() def on_update(self): frappe.clear_cache(doctype=self.document_type) def create_custom_field_for_workflow_state(self): frappe.clear_cache(doctype=self.document_type) meta = frappe.get_meta(self.document_type) if not...
_type, "__islocal": 1, "fieldname": self.workflow_state_field, "label": self.workflow_state_field.replace("_", " ").title(), "hidden": 1, "fieldtype": "Link", "options": "Workflow State", }).save() frappe.msgprint(_("Created Custom Field {0} in {1}").format(self.workflow_state_field, ...
bountyful/bountyfulcoins
bountyfulcoins/context_processors/__init__.py
Python
mit
29
0.034483
fro
m settings import setti
ngs
SasView/sasview
src/sas/qtgui/Plotting/Plottables.py
Python
bsd-3-clause
39,256
0.000484
""" Prototype plottable object support. The main point of this prototype is to provide a clean separation between the style (plotter details: color, grids, widgets, etc.) and substance (application details: which information to plot). Programmers should not be dictating line colours and plotting symbols. Unlike the ...
"""Add a new plottable to the graph""" # record the colour associated with the plottable if not plottable in self.plottables: if color is not None: self.plottables[plottable] = color else: self.color += plottable.colors() se...
"""Detect if any graphed plottables have changed""" return any([p.changed() for p in self.plottables]) def get_range(self): """ Return the range of all displayed plottables """ min_value = None max_value = None
ytlai4851/Uva
Python/Q424.py
Python
gpl-2.0
392
0.091837
a=['999','1'] max_l
ength=len(max(a,key=len)) tem=0 carry=0 for i in xrange(len(a)): while len(a[i])<max_length: a[i]='0'+a[i] for x in xrange(len(a)): a[x]=a[x][::-1] out='' for x in xrange(max_length): for i in a: tem+=int(i[x]) print(i[x],carry) tem+=carry carry=0 print(tem) if tem>9: carry=tem/10 out=str(tem%10)+out...
(out)
seomoz/simhash-db-py
test/test_riak.py
Python
mit
377
0
#! /usr/bin/env python '''Make sure the Riak client is sane''' import unittest from test import BaseTest from simhash_db import Client class RiakTest(BaseTest, unittest.TestCa
se): '''Te
st the Riak client''' def make_client(self, name, num_blocks, num_bits): return Client('riak', name, num_blocks, num_bits) if __name__ == '__main__': unittest.main()
downpoured/labs_coordinate_music
labs_coordinate_music/recurring_coordinate.py
Python
gpl-3.0
22,111
0.006784
# labs_coordinate_music # Ben Fisher, 2016 # Released under the GNU General Public License version 3 import re import copy import codecs import time from labs_coordinate_music.coordmusicutil import * from labs_coordinate_music.recurring_music_to_url import SaveDiskSpaceMusicToUrl from labs_coordinate_music.recurring_l...
eturn True except ValueError: pass elif field == 'title': a = stripMarkersFromFilename(a)
b = b.rstrip('!') return doStringsMatchForField(a, b, None) return False def checkDeleteUrlsInTheWayOfM4as(fullpathdir, shorts): changedAtLeastOne = False for short in shorts: if short.endswith('.url'): filem4a = fullpathdir + '/' + files.splitext(short)[0] + '.m4a' ...
MengGuo/mix_initiative
utilities/map/vis_sim.py
Python
gpl-2.0
12,697
0.011735
from math import exp import matplotlib import matplotlib.pyplot as plt from PIL import Image import pickle matplotlib.rcParams['ps.useafm'] = True matplotlib.rcParams['pdf.use14corefonts'] = True matplotlib.rcParams['text.usetex'] = True def draw_map(img_dir): im = Image.open(img_dir) pix = im.load() ...
ax2.plot(robot_x[k4[0]:k4[1]], robot_y[k4[0]:k4[1]], color='r', linestyle='-',linewidth=2, marker='o', mfc='grey', fillstyle='full', markersize=2.3, zorder=6, label=r'HIL') ax2.plot(robot_x[k5[0]:k5[1]], robot_y[k5[0]:k5[1]], color
='g', linestyle='-',linewidth=2, marker='o', mfc='grey', fillstyle='full', markersize=2.3, zorder=5, label=r'$\tau_r^t$') ax2.plot(robot_x[k6[0]:k6[1]], robot_y[k6[0]:k6[1]], color='m', linestyle='-',linewidth=2, marker='o', mfc='grey', fillstyle='full', markersize=2...
arlyon/codestreak
migrations/0002_auto_20170226_1202.py
Python
mit
476
0.002101
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-26 11:02 from __future__ import unicode_lit
erals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('codestreak', '0001_initial'), ] operations = [ migrations.AlterField( model_name='streak', name='uuid', field=models.CharField(max_length=36, prim...
]
lliss/model-my-watershed
src/mmw/apps/modeling/migrations/0004_auto_20150529_1700.py
Python
apache-2.0
388
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration
): dependencies = [ ('modeling', '0003_auto_20150526_1700') ] operations = [ migrations.RenameField( model_name='district', old_name='polygon', new_name='geom',
), ]
yhlam/cobble
src/reader/models.py
Python
mit
2,241
0
from django.conf import settings from django.db import models import jsonfield class Feed(models.M
odel): name = models.CharField(max_length=1024) url = models.URLField() homepage = models.URLField() etag = models.CharField(max_length=1024, blank=True) last_modified = models.DateTimeField(blank=True, null=True) subscribers = models.ManyToManyField( settings.AUTH_USER_MODEL, re...
'feeds', related_query_name='feed', ) def __str__(self): return '{} ({})'.format(self.name, self.url) class Entry(models.Model): feed = models.ForeignKey(Feed) entry_id = models.CharField(max_length=1024) title = models.CharField(max_length=1024) content = models.TextField() ...
elwlwlwk/GeneSeq2Taxonomy
train.py
Python
mit
3,062
0.035924
import os import json import tensorflow as tf import numpy as np def load_data(taxonomy): data_list= list(filter(lambda x:x[-3:]=='npy', os.listdir(taxonomy))) result=[] for data_file in data_list: result.append(np.load('%s/%s' %(taxonomy, data_file))) if len(result)%1000== 0: print("%s: %d/%d" %(taxonomy, l...
data
)-val_len):] fungi_val= fungi_data[int(len(fungi_data)-val_len):] x_train= np.concatenate((archaea_train, bacteria_train, protozoa_train, fungi_train), axis=0) y_train= [] x_val= np.concatenate((archaea_val, bacteria_val, protozoa_val, fungi_val), axis=0) y_val= [] for i in range(len(archaea_train)): y_train.a...
fulfilio/trytond-stock-production-location
__init__.py
Python
bsd-3-clause
210
0
# -*-
coding: utf-8 -*- from trytond.pool import Pool from production import Production def register(): Pool.register( Production, module='stock_production_location', type_='model'
)
versae/DH2304
data/arts2.py
Python
mit
1,974
0.004053
import numpy as np import pandas as pd arts = pd.DataFrame() # 1. Clean the dates so you only see numbers by using string manipulations arts["execution_date"] = arts["execution_date"].str.findall(r"([0-9]+)").str[0] arts["execution_date"] = arts["execution_date"].astype(float) arts.head() # 1. If a year is lower th...
scending=False).head() # 6. Get the average length of
artworks titles per category and artist. arts['title_length'] = arts['title'].str.len() length_by_category = arts.groupby("category")[["title_length"]].aggregate(np.mean) length_by_category.sort("title_length", ascending=False).head() # 6. Get the year with the highest production. artworks_by_year = arts.groupby("exec...
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Tools/unicode/makeunicodedata.py
Python
gpl-2.0
48,917
0.002514
# # (re)generate unicode property and type databases # # This script converts Unicode database files to Modules/unicodedata_db.h, # Modules/unicodename_db.h, and Objects/unicodetype_db.h # # history: # 2000-09-24 fl created (based on bits and pieces from unidb) # 2000-09-25 fl merged tim's splitbin fixes, separate ...
a(unicode, trace) makeunicodetype(unicode, trace) # --------------------------------------------------------------
------ # unicode character properties def makeunicodedata(unicode, trace): dummy = (0, 0, 0, 0, 0, 0) table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) FILE = "Modules/unicodedata_db.h" print("--- Preparing", FILE, "...") # 1) database properties for char in unico...
hehongliang/tensorflow
tensorflow/python/kernel_tests/scatter_nd_ops_test.py
Python
apache-2.0
28,025
0.007529
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
r, indices, updates).eval() # Compare self.assertAllClose(new, self.evaluate(ref_var)) def _VariableRankTests(self, np_scatter, tf_scatter): for vtype in (np.int32, np.float16, np.float32, np.float64, np.complex64, np.complex128): for itype in (np.int32, np.int64): ...
._VariableRankTest(np_scatter, tf_scatter, vtype, itype) def testSimple(self): indices = constant_op.constant([[4], [3], [1], [7]], dtype=dtypes.int32) updates = constant_op.constant([9, 10, 11, 12], dtype=dtypes.float32) ref = variables.Variable([0, 0, 0, 0, 0, 0, 0, 0], dtype=dtypes.float32) expect...
destijl/grr
grr/lib/checks/hints_test.py
Python
apache-2.0
4,932
0.001825
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for checks.""" from grr.lib import flags from grr.lib import test_lib from grr.lib.checks import hints from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import config_file as rdf_config_file from grr.lib.rdfvalues import protodict as rdf_pro...
Value("skynet") value = rdf_protodict.DataBlob().SetValue([1997]) rdf = rdf_protodict.KeyValue(k=key
, v=value) template = "{k}: {v}" hinter = hints.Hinter(template=template) expected = "skynet: 1997" result = hinter.Render(rdf) self.assertEqual(expected, result) def testRdfFormatterAttributedDict(self): sshd = rdf_config_file.SshdConfig() sshd.config = rdf_protodict.AttributedDict(skyne...
google/appengine_xblock_runtime
appengine_xblock_runtime/store.py
Python
apache-2.0
4,101
0
# Copyright 2013 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 ...
ching key in the store. """ kv_entity = ndb.Key(KeyValueEntity, key_string(key)).get() if kv_entity is None: raise KeyError() return kv_entity.value def set(self, key, value): """Sets the given value in the store. Overwrite any previous value.""" key = nd...
key_string(key)) kv_entity = KeyValueEntity(key=key) kv_entity.value = value kv_entity.put() def set_many(self, update_dict): entities = [] for key, value in update_dict.iteritems(): ndb_key = ndb.Key(KeyValueEntity, key_string(key)) kv_entity = KeyV...
demisto/content
Packs/ZeroTrustAnalyticsPlatform/Scripts/ZTAPExtractFields/ZTAPExtractFields.py
Python
mit
1,265
0
from CommonServerPython import * from typing import Dict, Any, List import traceback """ STANDALONE FUNCTION """ def extract_fields(value) -> List: """ Extracts ordered ZTAP fields for use in analytics """ out
put = [] for event in value: fields = {} for field in event["fields"]: key = field["key"]
value = field["value"] fields[key] = value output.append(fields) return output """ COMMAND FUNCTION """ def extract_fields_command(args: Dict[str, Any]) -> CommandResults: value = args.get("value", []) if not value: raise ValueError("value not specified") # Call the ...
barbosa/clorox
clorox/reporter.py
Python
mit
551
0
# !/usr/bin/python # -*- coding: utf-8 -*- class Reporter: @classmethod def from_identifier(cls, identifier): clazz = TYPES.get(identifier, None) return clazz() if clazz else None def report(self, all_fi
les, modified_files): pass class JSONReporter(Reporter): def report(self, all_files, modified_files): import json print(json.dumps({ 'status': 'clean' if len(modified_files) == 0 else 'di
rty', 'files': modified_files })) TYPES = {'json': JSONReporter}
PiStuffing/Quadcopter
Quadcopter.py
Python
gpl-2.0
267,801
0.009223
#!/usr/bin/env python #################################################################################################### #################################################################################################### ## ...
m ## ## this should retain this copyright comment. ## ## ## ## Copyright 201
2 - 2018 Andy Baker (Hove) - andy@pistuffing.co.uk ## ## ## #################################################################################################### #################################...
dettoman/website-4mb
camera_pi.py
Python
gpl-3.0
1,703
0.000587
import time import io import threading import picamera class Camera(object): thread = None # background thread that reads frames from camera frame = None # current frame is stored here by background thread last_access = 0 # time of last client access to the camera def initialize(self): if ...
rame thread Camera.thread = threading.Thread(target=self._thread) Camera.thread.start() # wait until frames start to be available while self.frame is None: time.sleep(0) def get_frame(self): Camera.last_access = time.time() self.initi...
_thread(cls): with picamera.PiCamera() as camera: # camera setup camera.resolution = (640, 400) camera.hflip = True camera.vflip = True # let camera warm up #camera.start_preview(fullscreen=False, window=(100,20,640,480)) time...
jmluy/xpython
exercises/practice/space-age/.meta/example.py
Python
mit
566
0
def period_converter(period): def inner(self): return round(self.seconds / period, 2) return inner class SpaceAge: on_mercu
ry =
period_converter(7600530.24) on_venus = period_converter(19413907.2) on_earth = period_converter(31558149.76) on_mars = period_converter(59354294.4) on_jupiter = period_converter(374335776.0) on_saturn = period_converter(929596608.0) on_uranus = period_converter(2651370019.3) on_neptune = pe...
doganmeh/django-datatable-view
datatableview/tests/test_datatables.py
Python
apache-2.0
29,048
0.002892
# -*- encoding: utf-8 -*- from inspect import isgenerator from .testcase import DatatableViewTestCase from .test_app import models from ..exceptions import ColumnError from ..datatables import Datatable, ValuesDatatable from ..views import DatatableJSONResponseMixin, DatatableView from .. import columns class Datatab...
eModel columns = ['name', 'fake'] # Verify a fake field name ends up separated from the db-backed field dt = DT([], '/', query_config={'order[0][column]': '0', 'order[0][dir]': 'asc'}) # iSortingCols': '1', dt.configure() self.assertEqual(dt.get_ordering_splits(), (['nam...
: '0', 'order[0][dir]': 'asc', 'order[1][column]': '1', 'order[1][dir]': 'asc'}) # 'iSortingCols': '2', dt.configure() self.assertEqual(dt.get_ordering_splits(), (['name'], ['fake'])) # Verify a fake field name as the sort column correctly finds no db sort fields dt = DT([], '/', query_...
mattgrogan/ledmatrix
ledmatrix/pattern/fire.py
Python
mit
3,096
0.00646
# Source:https://github.com/FastLED/FastLED/blob/master/examples/Fire2012WithPalette/Fire2012WithPalette.ino from __future__ import division import math import random from colour import Color #import randomcolor from PIL import Image, ImageChops, ImageDraw, ImageFont from components import App def hex...
little for y in range(self.height): cooling_factor = random.randint( 0, int(((self.cooling * 10) / self.height) + 2)) self.heat[x][y] = max(self.heat[x][y] - cooling_factor, 0) # Step 2: Heat from each cell drifts up and diffuses a little for y in range(self.height...
] + self.heat[x] [y2] + self.heat[x][y2]) / 3 # Step 3: Randomly ignite sparks of heat if random.randrange(0, 255) < self.sparking: y0 = self.height - 1 self.heat[x][y0] = min( (self.heat[x][y0] + random.randrange(160, 255)), 255) # Ste...
kelvict/Online-GoBang-Center
Server/TestClient.py
Python
mit
875
0.006857
#-*- encoding:UTF-8 -*- __author__ = 'gzs2478' from netstream import * import json import time if __name__ == '__main__': try: client = netstream(8) client.connect('127.0.0.1',12345) if client.state != NET_STATE_ESTABLISHED: print "connect failed!" print "First Statu...
recv() print "Get:",data except BaseException, e:
print e client.close()
milletluo/awesome-python3-webapp
www/config_override.py
Python
gpl-3.0
134
0
#!
/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'milletluo' configs = { 'db': { 'host': '127.0.0.1' } }
SimoneLucia/EmbASP-Python
specializations/dlv/desktop/dlv_desktop_service.py
Python
mit
529
0.007561
from platforms.desktop.desktop_service import DesktopService from specializations.dlv.dlv_answer_sets import DLVAnswerSets class DLVDesk
topService(DesktopService): """Is an extention of DesktopService for DLV's solver""" def __init__
(self, exe_path): super(DLVDesktopService, self).__init__(exe_path) self._load_from_stdin_option = "--" def _get_output(self, output, error): """Return a new DLVAnwerSets from output and error given""" return DLVAnswerSets(output, error)
nextgis-extra/tests
lib_gdal/ogr/ogr_wasp.py
Python
gpl-2.0
17,685
0.024597
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id: ogr_shape.py 26794 2014-01-08 16:02:22Z rouault $ # # Project: GDAL/OGR Test Suite # Purpose: WAsP driver testing. # Author: Vincent Mora <vincent dot mora at oslandia dot com> # ####...
tring ) if layer == None: gdaltest.post_r
eason( 'unable to create layer') return 'fail' layer.CreateField( ogr.FieldDefn( 'elevation', ogr.OFTReal ) ) for i in range(10): feat = ogr.Feature( layer.GetLayerDefn() ) feat.SetField(0, float(i) ) line = ogr.Geometry( type = ogr.wkbLineString ) line.AddPoint( i, 0 )...
atengler/kqueen-ui
kqueen_ui/blueprints/registration/views.py
Python
mit
4,267
0.002812
from datetime import datetime from flask import Blueprint, current_app as app, flash, redirect, render_template, url_for from flask_mail import Mail, Message from kqueen_ui.auth import confirm_token, generate_confirmation_token from kqueen_ui.exceptions import KQueenAPIException from kqueen_ui.generic_views import KQue...
user['active'] = True self.kqueen_request('user', 'update', fnargs=(user['id'], user), service=True) flash('You have confirmed your account. Thanks!', 'success') else: flash('No user found based on given e-mail.', 'danger') return redirect(url_for('ui...
_view('register')) registration.add_url_rule('/verify/<token>', view_func=VerifyEmail.as_view('verify_email'))
leductan-nguyen/RaionPi
src/octoprint/plugins/softwareupdate/exceptions.py
Python
agpl-3.0
823
0.028015
# coding=utf-8 from __future__ import absolute_import __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The RaionPi Project - Released under terms of the AGPLv3 License" class NoUpdateAvailable(Excep...
ata class ScriptError(Exception): def __init__(self, returncode, stdout, stderr): self.returncode = returncode
self.stdout = stdout self.stderr = stderr class RestartFailed(Exception): pass class ConfigurationInvalid(Exception): pass
mezz64/home-assistant
homeassistant/components/forecast_solar/sensor.py
Python
apache-2.0
2,649
0.000755
"""Support for the Forecast.Solar sensor service.""" from __future__ import annotations from datetime import datetime from homeassistant.components.sensor import DOMAIN as
SENSOR_DOMAIN, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType fro
m homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import DOMAIN, SENSORS from .m...
scdoshi/django-bits
bits/templatetags/custom_utils.py
Python
bsd-2-clause
1,358
0.001473
############################################################################### ## Imports ############################################################################### # Django from django import template from django.forms.forms import BoundField ####################################################################...
field): self.__dict__ = field.__dict__ def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be use...
"" if not widget: widget = self.field.widget attrs = attrs or {} auto_id = self.auto_id if auto_id and 'id' not in attrs and 'id' not in widget.attrs: if not only_initial: attrs['id'] = auto_id else: attrs['id'] = self....
edx/course-discovery
course_discovery/apps/course_metadata/migrations/0072_courseentitlement_partner.py
Python
agpl-3.0
548
0.001825
# Generated by Django 1.11.3 on 2017-12-07 19:07 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('core', '0007_auto_20171004_1133'), ('course_metadata', '0071_auto_20171128_1945'), ] operations = [ migrations.AddField( model_name='courseentitlement', name='partner', field=models.ForeignKey(null=True, on_delete=django.
db.models.deletion.DO_NOTHING, to='core.Partner'), ), ]
derek-miller/flask-template
tests/test_api.py
Python
bsd-3-clause
156
0
# -*- coding: utf-8 -*- import pytest @pytest.mark.inte
gration def test_fake_int(api_app): assert True def test_fa
ke_unit(api_app): assert True
Vauxoo/server-tools
attachment_synchronize/models/storage_backend.py
Python
agpl-3.0
2,354
0.002549
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StorageBackend(models.Model): _inherit = "storage.backend" synchronize_task_ids = fields.One2many( "attachment.synchronize.task", "backend_id", string="Tasks" ) import_task_count = fiel...
da t: t.method_type == "import") ) def _comput
e_export_task_count(self): for rec in self: rec.export_task_count = len( rec.synchronize_task_ids.filtered(lambda t: t.method_type == "export") ) def action_related_import_task(self): self.ensure_one() act_window_xml_id = "attachment_synchronize.acti...
prasannav7/ggrc-core
src/ggrc_workflows/converters/handlers.py
Python
apache-2.0
14,283
0.007701
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: miha@reciprocitylabs.com # Maintained By: miha@reciprocitylabs.com """ Module for all special column handlers for workflow objects """ import dat...
== "annually": if None in [day, month]: return "" return "{}/{}".format(month, day) else: return "" class TaskStartColumnHandler(TaskDateColumnHandler): """ handler for start column in task group tasks """ def set_obj_attr(self): """ se
t all possible start date attributes """ # disable false parentheses warning for 'not (a < b < c)' # pylint: disable=C0325 freq = self.row_converter.obj.task_group.workflow.frequency if freq == "one_time": if len(self.value) != 3: self.add_error(errors.WRONG_VALUE_ERROR, ...
aptana/Pydev
tests/org.python.pydev.refactoring.tests/src/python/rewriter/testRaise.py
Python
epl-1.0
769
0.020806
class fooexception(Exception): def __init__(self, msg): Exception.__init__(self) print msg def __init__(self):
Exception.__init__(self) print "i am a fooexception" data = 2 raise "foo" raise "foo", data # before raise fooexception # on-line # after # before raise fooexception, "bla" # on-line # after raise fooexception, [1, 2, 3] raise fooexception, range(3) raise fooexception, (1, 2, 3) raise fooexception, (1,...
aise fooexception, (1, 2, 3), "foo" # on-line # after raise fooexception, (1, 2, 3), (1, 2, 3) raise fooexception, (1, 2, 3), [1, 2, 3] # after raise fooexception, (1, 2, 3), range(1) # on-line # after raise fooexception, (1, 2, 3), (1 + 1) raise raise fooexception, (1, 2, 3), 1 + 1 raise
roverdotcom/django-celery-transactions
tests/test/tests.py
Python
bsd-2-clause
2,324
0.003873
import django, os from djcelery_transactions import task from django.test import TransactionTestCase if django.VERSION < (1,7): from django.core.cache import cache else: from django.core.cache import caches cache = caches['default'] if django.VERSION >= (1,6): from django.db.transaction import atomic e...
except SpecificException: self.assertIsNone(cache.get('my_g
lobal')) else: self.fail('Exception not raised') def test_via_api(self): r = self.client.get('/test_api/') self.assertEqual(r.status_code, 200) self.assertEqual(cache.get('my_global'), 42) def test_django_db_transaction_managed(self): """ Check tha...
xyuanmu/XX-Net
code/default/launcher/download_modules.py
Python
bsd-2-clause
4,591
0.001307
import os import threading import time import zipfile import shutil from update_from_github import request, xlog, hash_file_sum current_path = os.path.dirname(os.path.abspath(__file__)) root_path = os.path.abspath(os.path.join(current_path, os.pardir)) top_path = os.path.abspath(os.path.join(root_path, os.pardir, os....
ot os.path.isdir(download_path): os.mkdir(download_path) fn = url.split(
"/")[-1] dfn = os.path.join(download_path, fn) if not download_file(url, dfn): xlog.warn("download file %s fail.", url) return try: os.mkdir(extract_path) with zipfile.ZipFile(dfn, "r") as dz: dz.extractall(extract_path) dz.close() xlog.info(...
d120/pyophase
dashboard/views.py
Python
agpl-3.0
3,245
0.002466
from django.urls import reverse_lazy from django.utils import timezone from django.utils.translation import gettext as _ from django.views.generic import TemplateView from .components import DashboardBaseMixin, DashboardAppMixin from .dashboard_widgets import DashboardWidgets from .shortcuts import check_permissions ...
ardWidgets.active_widgets: #...only add widgets with matching permissions if check_permissions(user, widget.permissions): active_widgets_for_current_user.append(widget) context['widgets'] = active_widgets_for_current_user return context class PersonalDashboardM...
links = [ (_('Start'), reverse_lazy("dashboard:personal_overview")) ] from clothing.models import Settings clothing_settings = Settings.instance() if clothing_settings is not None and clothing_settings.clothing_ordering_enabled: links.append((_('Kleidungsbes...
IgorDubois/ComplementAlgoS4
couverture_arbre/main.py
Python
gpl-3.0
458
0.00655
import networkx as nx import random import unittest import kruskal ''' for i in range(1,500,1): for j in range(i+1,500,1): G.add_edge(int(i),int(j),weight=random.randint(1,20)) nx.write_weighted_edgelist(G, "k500.
adjlist") ''' G = nx.read_weighted_edgelist("k500.adjlist" , nodetype=in
t) print kruskal.kruskal(G) print ('coucou') T = nx.minimum_spanning_tree(G) print(sorted(T.edges(data=True))) #print nx.all_pairs_dijkstra_path_length(G)[1]
CartesianCo/argentum-control
src/controllers.py
Python
gpl-3.0
3,990
0.003008
#!/usr/bin/python # -*- coding: utf-8 -*- """ Argentum Control GUI Copyright (C) 2013 Isabella Stevens Copyright (C) 2014 Michael Shiel Copyright (C) 2015 Trent Waddington This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License...
imitive2 = self.decodePrimitiveBitmask(primitive2) self.firingCommand(primitive1, address1, primitive2, address2) class TestParsingController(ParsingControllerBase): positions = {'X': 0, 'Y': 0}
maximums = {'X': 0, 'Y': 0} def incrementalMovementCommand(self, axis, steps): #print('incrementalMovementCommand on {} axis for {} steps.'.format(axis, steps)) increment = abs(steps) if increment > 0: self.positions[axis] += increment elif increment == 0: ...
cherusk/ansible
lib/ansible/modules/cloud/ovirt/ovirt_clusters.py
Python
gpl-3.0
25,773
0.002638
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (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 #...
_as_cores: description: - "If I(True) the exposed host threads would be treated as cores which can be utilized by virtual machin
es." ksm: description: - "I I(True) MoM enables to run Kernel Same-page Merging I(KSM) when necessary and when it can yield a memory saving benefit that outweighs its CPU cost." ksm_numa: description: - "If I(True) enables KSM C(ksm) for best...
jbpease/shear
adapt.py
Python
gpl-3.0
13,208
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This progam (as part of SHEAR) searches adapter sequences and generates an adapter file for use with SHEAR/Scythe. """ import sys import os import argparse import re import gzip _LICENSE = """ SHEAR: Simple Handler for Error and Adapter Removal James B. Pease http://...
ch.group(0)] = self.found.get( match.group(0), 0) + 1 if len(match.groups()) > 0: if match.groups()[0] is not None: if len(match.groups()[0]) > 0: self.barcodes.update([match.groups()[0]]) r
eturn '' class Adaptamers(object): def __init__(self): self.endmers = {} def add_read_end(self, read, k=16): endmer = read[len(read) - k:] if "N" in endmer: return '' self.endmers[endmer] = self.endmers.get(endmer, 0) + 1 return '' def generate_argparser...
gsnedders/w3ctestlib-git
Sources.py
Python
bsd-3-clause
57,592
0.01245
#!/usr/bin/python # CSS Test Source Manipulation Library # Initial code by fantasai, joint copyright 2010 W3C and Microsoft # Licensed under BSD 3-Clause: <http://www.w3.org/Consortium/Legal/2008/03-bsd-license> from os.path import basename, exists, join import os import filecmp import shutil import re import codecs i...
ool(pathLi
st, fileName)): return intern('tool') return intern('support') class SourceCache: """Cache for FileSource objects. Supports one FileSource object per sourcepath. """ def __init__(self, sourceTree): self.__cache = {} self.sourceTree = sourceTree def generateSource(self, sourcepath, re...
baocongchen/M101P-MONGODB-FOR-PYTHON-DEVELOPERS
week2/Homework2.1.py
Python
mit
1,208
0.021595
# -*- coding: utf-8 -*- #HOMEWORK: HOMEWORK 2.1 #In this problem, you will be using a collection of student scores that is similar to what we used in the lessons. Please download grades.json from the Download Handout link and import it into your local mongo database as follows: #mongoimport -d students -c grades < gra...
the highest average score: #> db.grades.aggregate({'$group':{'_id':'$student_id', 'average':{$avg:'$score'}}}, {'$sort':{'average':-1}}, {'$limit':1}) #Note: Aggregation requ
ires mongodb 2.2 or above. #The answer, deep in the resulting document, should be student_id 164 with an average of approximately 89.3. #Now it’s your turn to analyze the data set. Find all exam scores greater than or equal to 65, and sort those scores from lowest to highest. #What is the student_id of the lowest exam...
pizzapanther/Neutron-IDE
neutron/ide/grep.py
Python
bsd-3-clause
1,106
0.028029
import re import ide.utils class Grep (object): def __init__ (self, filepath, needle): self.filepath = filepath self.needle = needle def replace (self, rstr, rlines): fh = open(self.filepath, 'r') newlines = '' linenum = 0 while 1: line = fh.readline() if line: ...
lose() def results (self): ret = [] fh = open(self.filepath, 'r') if ide.utils.istext(fh.read(512)): fh.seek(0) linenum = 0 while 1: line = fh.readline() if line: for match in self.needle.finditer(line): ret.append((linenum, match.start(), match...
eturn ret
githubutilities/LeetCode
Python/queue-reconstruction-by-height.py
Python
mit
1,549
0.002582
# Time: O(n * sqrt(n)) # Space: O(n) # Suppose you have a random list of people standing in a queue. # Each person is described by a pair of integers (h, k), # where h is the height of the person and k is the number of people # in front of this person who have a height greater than or equal to h. # Write an algorit...
block.insert(index, p) if len(block) * len(block) > len(people): blocks.insert(i+1, block[len(block)/2:]) del block[len(block)/2:] return [p for block in blocks for p in block] # Time: O(n^2) # Space: O(n) class Solution2(object): def reconstructQueue(s...
result = [] for p in people: result.insert(p[1], p) return result
RyanWolfe/cloud-custodian
c7n/ufuncs/logsub.py
Python
apache-2.0
3,740
0
# Copyright 2016 Capital One Services, LLC # # 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...
vt['timestamp']/1000.0) return "%s: %s" % ( dt.ctime(), "\n".join(textwrap.wrap(evt['message'], 80))) def process_log_event(event, context): """Format log events and relay via sns/email""" init() serialized = event['awslogs'].pop('data') data = json.loads(zlib.decompress( base64.b6...
ndow) timestamps = [e['timestamp'] for e in data['logEvents']] start = min(timestamps) - 1000 * 15 end = max(timestamps) + 1000 * 5 events = logs.get_log_events( logGroupName=data['logGroup'], logStreamName=data['logStream'], startTime=start, endTime=end, startFr...
chenyoufu/writeups
jarvisoj/pwn_level2.py
Python
gpl-3.0
247
0.004049
from pwn import * p = remote("pwn2.
jarvisoj.com", 9878) elf = ELF('./level2') bin_sh_addr = 0x804a024 sys_plt = elf.plt['system'] print hex(sys_plt) payload = 'A'* 140 + p32(sys_plt) + 'JUNK' + p32(bin_sh_addr) p.send(pay
load) p.interactive()
JackDanger/sentry
tests/sentry/runner/commands/test_cleanup.py
Python
bsd-3-clause
1,102
0
# -*- coding: utf-8 -*- from __future__ import absolute_import from sentry.models import Event, Group, GroupTagValue, TagValue, TagKey from sentry.runner.commands.cleanup import cleanup from sentry.testutils import CliTestCase ALL_MODELS = (Event, Group, GroupTagValue, TagValue, TagKey) class SentryCleanupTest(Cli...
unt() rv = self.invoke('--days=1', '--project=2') assert rv.exit_code == 0, rv.output for model in ALL_MODELS: assert model.objects.count() == orig_counts[model]
rv = self.invoke('--days=1', '--project=1') assert rv.exit_code == 0, rv.output for model in ALL_MODELS: assert model.objects.count() == 0
matthewbhall/pack-generator
Scripts/card-scraper.py
Python
mit
3,428
0.009918
#!/usr/bin/python import sys import getopt import urllib2 import json from bs4 import BeautifulSoup import re import json colors = {'W': 'White', 'U': 'Blue', 'B': 'Black', 'R': 'Red', 'G': 'Green'} colorless = "Colorless" multicolored = "Multicolored" def extract_cmc_and_color(cost): pieces = re.findall(r'[\dWU...
outfile = open('%s.txt' % set, 'w') json.dump(data, outfile) print 'card data written to
%s.txt' % set if __name__ == "__main__": main(sys.argv[1:])
luisibanez/SahanaEden
models/mpr.py
Python
mit
5,652
0.015039
# -*- coding: utf-8 -*- """ MPR Missing Persons Registry @author: nursix @see: U{http://eden.sahanafoundation.org/wiki/BluePrintVITA} """ module = "mpr" if deployment_settings.has_module(module): # # Settings -------------------------------------------------------------------- # resource =...
esent)), represent = lambda id: \ (id and [shn_pr_person_represent(id)] or ["None"])[0], comment = shn_mpr_re
porter_comment, ondelete = "RESTRICT")) # ------------------------------------------------------------------------- resource = 'missing_report' tablename = "%s_%s" % (module, resource) table = db.define_table(tablename, timestamp, uuidstamp, a...
jsheedy/neopixel-framebuffer
fx/midi_note.py
Python
mit
2,048
0.004395
import numpy as np from point import Point from .fx import Fx from .midi_event import MidiEvent def make_key(note, channel): return "{}-{}".format(note, channel) colors = [ (.8, .2, .1), (.3, .8, .3), (.7, .2, .8), (.1, .2, .3), (.9, .2, .4), (.8, .6, .1), (.9, .2, .1), (.5, .0,...
n*self.length point = self.points[event.channel] point.pos = relative_position intensity = event.velocity / 128 r,g,b = colors[event.channel] points = point.get_points()
self.x[:,0] += r * intensity * points self.x[:,1] += g * intensity * points self.x[:,2] += b * intensity * points return self.x