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
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_PolyTrend/cycle_7/ar_/test_artificial_1024_RelativeDifference_PolyTrend_7__20.py
Python
bsd-3-clause
274
0.083942
i
mport pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order
= 0);
AlexandreProenca/django-url-filter
tests/filtersets/test_base.py
Python
mit
7,675
0.000782
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import pytest from django import forms from django.http import QueryDict from test_project.one_to_one.models import Restaurant, Waiter from url_filter.backends.django import DjangoFilterBackend from url_filter.filters import Filter from u...
def test_default_filter_no_default(self): class TestFilterSet(FilterSet):
foo = Filter(form_field=forms.CharField()) assert TestFilterSet().default_filter is None def test_default_filter(self): class TestFilterSet(FilterSet): foo = Filter(form_field=forms.CharField(), is_default=True) bar = Filter(form_field=forms.CharField()) ...
klahnakoski/esReplicate
pyLibrary/queries/namespace/typed.py
Python
mpl-2.0
4,356
0.002525
# encoding: utf-8 # # # This Source Code Form is subject to the 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/. # # Author: Kyle Lahnakoski ([email protected]) # from __future__ import absolute_import from __f...
def _convert_having(self, having): raise NotImplementedError() def _convert_window(self, window): raise NotImplementedError() def _convert_many(self, k, v): return {k: map(self.convert, v)} def _convert_
bop(self, op, term): if isinstance(term, list): return {op: map(self.convert, term)} return {op: {var: val for var, val in term.items()}}
mdejongh/ModelComparison
lib/ModelComparison/ModelComparisonClient.py
Python
mit
7,099
0.001127
############################################################ # # Autogenerated by the KBase
type compiler - # any changes made here will be overwritten # ############################################################ try: import json as _json except Import
Error: import sys sys.path.append('simplejson-2.3.3') import simplejson as _json import requests as _requests import urlparse as _urlparse import random as _random import base64 as _base64 from ConfigParser import ConfigParser as _ConfigParser import os as _os _CT = 'content-type' _AJ = 'application/json'...
beav/pulp
server/test/unit/test_migration_0005.py
Python
gpl-2.0
2,511
0.001195
# -*- coding: utf-8 -*- # # Copyright © 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or impli...
dule module.migrate() # validation for collection in [connection.get_collection(n) for n in TEST_COLLECTIONS]: for unit in collection.find({}): self.assertTrue(LAST_UPDATED in unit) unit_id = unit[ID] last_updated = unit[LAST_UPDATED] ...
else: self.assertTrue(isinstance(last_updated, float))
google-research/google-research
multiple_user_representations/models/parametric_attention_test.py
Python
apache-2.0
1,915
0.001567
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
ITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for parametric_attention.""" import numpy as np import tensorflow as tf from multi
ple_user_representations.models import parametric_attention class ParametricAttentionTest(tf.test.TestCase): def test_parametric_attention_model_with_single_representation(self): model = parametric_attention.SimpleParametricAttention( output_dimension=2, input_embedding_dimension=2, vo...
kcsaff/maze-builder
maze_builder/lost_text/negative_status.py
Python
mit
5,360
0
from maze_builder.sewe
r import MadLibs, Choice from maze_builder.lost_text.text_decorations import fix_sentence negative_status_sentence = MadLibs({ '{NEGATIVE_STATUS INTENSIFIED SENTENCE FIXED}': 1, '{NEGATIVE_STATUS SENTENCE FIXED}': 1, }, FIXED=fix_sentence, SENTENCE={
'{}.': 30, '{}!': 10, '{} again?': 10, '{} now.': 2, '{} here.': 5, '{} here!': 2, '{}. Now I know what that means.': 1, '{}: and not for the first time.': 1, '{} -- and not for the first time.': 1, '{}? Yes, always.': 1, 'I feel {}...
thinkopensolutions/tkobr-addons
tko_partner_multiple_phones/__manifest__.py
Python
agpl-3.0
2,154
0.000464
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # ThinkOpen Solutions Brasil # Copyright (C) Thinkopen Solutions <http://www.tkobr.com>. # # Th
is program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the F
ree Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Aff...
qtproject/pyside-pyside
tests/QtGui/qcolor_test.py
Python
lgpl-2.1
3,949
0.006584
############################################################################# ## ## Copyright (C) 2016 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of the test suite of PySide2. ## ## $QT_BEGIN_LICENSE:GPL-EXCEPT$ ## Commercial License Usage ## Licensees holding valid commercial ...
getHsv(), hsva) def testGetCmyk(self): # not supported by colorsys self.assertEqual(self.color.getCmyk(), (170, 85
, 0, 195, 80)) def testGetCmykF(self): # not supported by colorsys for x, y in zip(self.color.getCmykF(), (170/255.0, 85/255.0, 0, 195/255.0, 80/255.0)): self.assertTrue(x - y < 1/10000.0) class QColorQRgbConstructor(unittest.TestCase): '''QColor(QRgb) constructor''' # Affected by bug...
ferram4/ProcEngines
GameData/ProcEngines/PropellantMixtures/config_parser.py
Python
mit
928
0.003233
from os import walk files = [] for (dirpath, dirnames, filenames) in walk('./data/'): files.extend(filenames) break data = [] OFratio = None for file in files: t = [] with open('./data/' + file) as f: for i, line in enumerate(f): if i in [15, 24, 25, 29, 31, 34, 39]: ...
.append([Pc, Tc, Te, Pe, MW, gamma, Mach, Cpc, Cpe]) if len(data) < 15: print('[WRN] Less than 15 keys!') block = ''.join(['MixtureRatioData\n{\n OFratio =', OFratio, '\n PressureData\n {\n', ''.join([' key = {}, {}, {}, {}, {}, {}, {}, {}, {}\n'.format(*line) for line in
data]), ' }\n}']) with open('./data/results.txt', 'a') as f: f.write(block)
Gurgel100/gcc
gcc/ada/doc/share/conf.py
Python
gpl-2.0
3,966
0.000756
# -*- coding: utf-8 -*- # Style_Check:Python_Fragment (meaning no pyflakes check) # # GNAT build configuration file import sys import os import time import re sys.path.append('.') import ada_pygments import latex_elements # Some configuration values for the various documentation handled by # this conf.py DOCS = { ...
dacore_transparent.png' if os.path.isfile('favicon.ico'): html_favicon = 'favicon.ico' html_static_path = ['_static'] latex_additional_files = ['gnat.sty'] copyright_macros = { 'date': time.strftime("%b %d, %Y"), 'edition': 'GNAT %s Edition' % 'Pro' if get_gnat_build_type() == 'PRO'
else 'GPL', 'name': u'GNU Ada', 'tool': u'GNAT', 'version': version} latex_elements = { 'preamble': '\\usepackage{gnat}\n' + latex_elements.TOC_DEPTH + latex_elements.PAGE_BLANK + latex_elements.TOC_CMD + latex_elements.LATEX_HYPHEN + latex_elements.doc_settings(DOCS[doc_nam...
kalhartt/django-fluxbb
fluxbb/models/search_word.py
Python
gpl-2.0
481
0
from django.db import models from fluxbb import FLUXBB_PREFIX class SearchWord(model
s.Model): """ FluxBB Search Word Fields on this model match exactly with those defined by fluxbb, see the [fluxbb dbstructure](http://fluxbb.org/docs/v1.5/dbstructure#users). """ id = models.AutoField(primary_key=True) word = models.CharField(max_length=2
0, default="") class Meta: app_label = 'fluxbb' db_table = FLUXBB_PREFIX + 'search_words'
roving99/robot_pi
0mq/wii_ir_test.py
Python
gpl-2.0
966
0.030021
#!/usr/bin/python import smbus import time ''' retrieve data from wii ir camera. x = 0-1023 y = 0-720 size = 1-15? top right of scene = [0,0] ''' def getBlob(n,list): # return x,y,size for blob n (0-3) from list if len(list)<13: return [] x = list[1+(n*3)] y = list[2+(n*3)] s = list[3+(n*3)...
ep(0.05) i2c.write_byte_data(wiiAddr, 0x33,0x33) time.sleep(0.05) while 1: data = i2c.read_i2c_block_data(wiiAddr, 0x36, 16)
print len(data), "\t", getBlob(0,data), "\t", getBlob(1,data), "\t", getBlob(2,data), "\t", getBlob(3,data) time.sleep(0.5)
Distrotech/bzr
bzrlib/smart/message.py
Python
gpl-2.0
13,276
0
# Copyright (C) 2008 Canonical Ltd # # 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 ...
Possible states:
* args: expecting args * body: expecting body (terminated by receiving a post-body status) * error: expecting post-body error * end: expecting end of message * nothing: finished """ def __init__(self, request_handler, responder): MessageHandler.__init__(self) self.request...
Azure/azure-sdk-for-python
sdk/timeseriesinsights/azure-mgmt-timeseriesinsights/azure/mgmt/timeseriesinsights/aio/operations/_reference_data_sets_operations.py
Python
mit
19,516
0.00497
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
der_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters
['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ReferenceDataSetCreateOrUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_p...
dsoprea/LicensePrepend
setup.py
Python
gpl-2.0
692
0.001445
from setuptools import setup, find_packages import os description = "Make sure all source files have your standard licensing stub "\ "at the top." long_description = "" setup(name='plicense', version='0.2.1', description=descri
ption, long_description=long_description, classifiers=[], keywords='license', author='Dustin Oprea', author_email='[email protected]', url='https://github.com/dsoprea/LicensePrepend', license='GPL 2', packages=find_packages(exclude=[]),
include_package_data=True, zip_safe=True, install_requires=[ 'nose' ], scripts=['scripts/plicense'], )
cbecker/LightGBM
python-package/lightgbm/basic.py
Python
mit
66,093
0.001407
# coding: utf-8 # pylint: disable = invalid-name, C0111, C0301 # pylint: disable = R0912, R0913, R0914, W0105, W0201, W0212 """Wrapper c_api of LightGBM""" from __future__ import absolute_import import ctypes import os from tempfile import NamedTemporaryFile import numpy as np import scipy.sparse from .compat import...
.format(data.dtype)) else: raise TypeError("Unknown type({})".format(type(data).__name__)) return (ptr_data, type_data) def c_int_
array(data): """get pointer of int numpy array / list""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): if data.dtype == np.int32: ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)) type_data = C_API_DTYPE_INT32 ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.2/Lib/toaiff.py
Python
mit
2,989
0.004015
"""Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format). Input may be compressed. Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others. An exception is raised if the file is not of a recognized type. Returned filename is either the input filename or a temporary filename; in the la...
('sox -t voc - -t aiff -r 11025 -', '--') table['voc'] = t t = pipes.Template() t.append('sox -t wav - -t aiff -', '--') table['wav'] = t t = pipes.Template() t.append('sox -t 8svx
- -t aiff -r 16000 -', '--') table['8svx'] = t t = pipes.Template() t.append('sox -t sndt - -t aiff -r 16000 -', '--') table['sndt'] = t t = pipes.Template() t.append('sox -t sndr - -t aiff -r 16000 -', '--') table['sndr'] = t uncompress = pipes.Template() uncompress.append('uncompress', '--') class error(Excepti...
ScottBuchanan/eden
modules/s3/s3query.py
Python
mit
82,174
0.001217
# -*- coding: utf-8 -*- """ S3 Query Construction @copyright: 2009-2015 (c) Sahana Software Foundation @license: MIT 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 ...
else: value = ogetattr(row, fname) except: try: value = row[colname] except (KeyError, AttributeError):
raise error(colname) elif fname in row: value = row[fname] elif colname in row: value = row[colname] elif tname is not None and \ tname in row and fname in row[tname]: value = row[tname][fname] else: raise error(coln...
danwent/Perspectives-Server
util/__init__.py
Python
gpl-3.0
156
0.00641
""" A c
ollection of utility and helper modules. These differ from notary_utils in that they do
not depend on or need to connect to the notary database. """
deevarvar/myLab
book/tlpi_zhiye/utlib/ut_util.py
Python
mit
335
0.01194
__author__ = 'deevarvar' import string import random import o
s #generate a random string def string_generator(size=6, chars=string.ascii_letters+string.digits): return ''.join(random.choice(chars) for _ in range(size)) #emulate touch cmd def touchFile(fname, time=None): with open(fname, 'a'): os.utime(fname
,time)
GiancarloF/raspymc_server
core/conf_manager.py
Python
gpl-3.0
4,528
0.023852
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- """ Raspymc is a multimedia centre exposed via a http server built with bottlepy Copyright (C) 2013
Giancarlo Fringuello 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied wa...
usc-isi-i2/WEDC
spark_dependencies/python_lib/digSparkUtil/fileUtil.py
Python
apache-2.0
11,462
0.005496
#!/usr/bin/env python from __future__ import print_function import sys import json import csv import StringIO import io from dictUtil import as_dict, merge_dicts import urllib # import jq from itertools import izip from logUtil import logging # for manifest introspection only import inspect from pyspark import SparkC...
rmat, data_type)] handler = getattr(self, handlerName) rdd = handler(rdd, filename, **kwargs) # TBD: return (rdd, manifestEntry) # entry = self.makeEntry(output_filename=filename, # output_file_format=file_format, # ...
raise NotImplementedError("File_Format={}, data_type={}".format(file_format, data_type)) save_dispatch_table = {("sequence", "json"): "_save_sequence_json_file", ("sequence", "csv"): "_save_sequence_csv_file", ("text", "json"): "_save_text_json_file",...
indie1982/osmc-fixes
package/mediacenter-addon-osmc/src/script.module.osmcsetting.updates/resources/lib/apt_cache_action.py
Python
gpl-2.0
11,354
0.035406
''' This script is run as root by the osmc update module. ''' import apt import socket import sys from datetime import datetime import json import os import time import subprocess import traceback from CompLogger import comprehensive_logger as clog t = datetime class Logger(object): def __init__(self, filename="Def...
) def fetch(self): self.cache.upgrade(True) print '%s %s fetching all packages' % (t.now(), 'apt_cache_action.py') dprg = Download_Progress() self.cache.fetch_archives(progress=dprg) # call the p
arent and kill the pDialog call_parent('progress_bar', {'kill': True}) return '%s %s all packages fetched' % (t.now(), 'apt_cache_action.py') class Operation_Progress(apt.progress.base.OpProgress): def __init__(self): super(Operation_Progress, self).__init__() def update(self): call_parent('progress_ba...
tjgillies/distributed-draw
entangled/kademlia/constants.py
Python
lgpl-3.0
1,820
0.006593
#!/usr/bin/env python # # This library is free software, distributed under the terms of # the GNU Lesser General Public License Version 3, or any later version. # See the COPYING file included in this archive # # The docstrings in this module contain epytext markup; API documentation # may be created by processing this...
lpha = 3 #: Maxim
um number of contacts stored in a bucket; this should be an even number k = 8 #: Timeout for network operations (in seconds) rpcTimeout = 5 # Delay between iterations of iterative node lookups (for loose parallelism) (in seconds) iterativeLookupDelay = rpcTimeout / 2 #: If a k-bucket has not been used for this amou...
itJunky/web-tasker.py
db_repository/versions/028_migration.py
Python
gpl-2.0
1,041
0.000961
from sqlalchemy import * from migrate im
port * from migrate.changeset import schema pre_meta = MetaData() post_meta = MetaData() task = Table('task', post_meta, Column('id', Integer, primary_key=True, nullable=False), Column('parent_id', Integer, default=ColumnDefault(0)), Column('body', String), Column('taskname',
String(length=140)), Column('timestamp', DateTime), Column('user_id', Integer), Column('project_id', Integer), Column('status', String(length=10)), Column('depth', Integer, default=ColumnDefault(0)), ) def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; bi...
zappyk-github/zappyk-python
src/src_zappyk/developing/test-gui-Gtk.py
Python
gpl-2.0
4,640
0.009483
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'zappyk' import sys, subprocess from gi.repository import Gtk, Gio from gi.repository import GLib ############################################################################### class MyWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__...
True # FUNDAMENTAL, OTHERWISE THE CALLBACK ISN'T RECALLED else: ret
urn False # RAISED AN ERROR: EXIT AND I DON'T WANT TO SEE YOU ANYMORE #______________________________________________________________________________ # def test_2(): cmd = CommandTextView("find") win = Gtk.Window() win.connect("delete-event", lambda wid, event: Gtk.main_quit()) # DEFINING CALLBACKS WITH LA...
ulikoehler/ODBPy
ODBPy/SurfaceParser.py
Python
apache-2.0
1,978
0.004044
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ODB++ surface parser components """ import re from collections import namedtuple from .Decoder import DecoderOption from .Treeifier import TreeifierRule from .PolygonParser import Polygon from .Structures import Polarity, polarity_map from .Attributes import parse_attr...
code, attributes = match.groups()
# Parse attribute string attributes = parse_attributes(attributes[1:]) \ if attributes is not None else {} return SurfaceBeginTag(polarity_map[polarity], int(dcode), attributes) def _parse_surface_end(match): "Parse a surface end tag regex match" return Surf...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/security/cmd/hide/type_Result.py
Python
unlicense
1,899
0.002633
# uncompyle6 version 2.9.10 # Python bytecode 2
.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: type_Result.py from types import * RESULT_TYPE_PROCESS_HIDE = 0 RESULT_TYPE_PROCESS_UNHIDE = 1 class Result: def __init__(self): self.__dict__['type'] = 0 self.__dict__['item...
def __getattr__(self, name): if name == 'type': return self.__dict__['type'] if name == 'item': return self.__dict__['item'] if name == 'metaData': return self.__dict__['metaData'] raise AttributeError("Attribute '%s' not found" % name) def __seta...
mazulo/taskbuster-boilerplate
docs/conf.py
Python
mit
8,303
0.006263
# -*- coding: utf-8 -*- # # TaskBuster documentation build configuration file, created by # sphinx-quickstart on Tue Jun 16 10:01:14 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
he given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes
and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index i...
ostree/plaso
plaso/formatters/plist.py
Python
apache-2.0
497
0.012072
# -*- coding: utf-8 -*- """The plist event formatter.""" from plaso.formatters
import inte
rface from plaso.formatters import manager class PlistFormatter(interface.ConditionalEventFormatter): """Formatter for a plist key event.""" DATA_TYPE = u'plist:key' FORMAT_STRING_SEPARATOR = u'' FORMAT_STRING_PIECES = [ u'{root}/', u'{key}', u' {desc}'] SOURCE_LONG = u'Plist Entry' ...
xjsender/haoide
salesforce/lib/diff.py
Python
mit
2,098
0.005243
import sublime, sublime_plugin import difflib import time import datetime import codecs import os def diff_changes(file_name, result): try: if "Body" in result: server = result["Body"].splitlines() elif "Markup" in result: server = result["Markup"].splitline
s() local = codecs.open(file_name, "r", "utf-8").read().splitlines() except UnicodeDecodeError: show_diff_panel("Diff only works with UTF-8 files") return time.strfti
me("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) bdate_literal = result["LastModifiedDate"].split(".")[0] server_date = datetime.datetime.strptime(bdate_literal, "%Y-%m-%dT%H:%M:%S") local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) diff = difflib.unified_diff(server, loc...
dubwub/F2016-UPE-AI
sample_AIs/darwinbot2.py
Python
mit
1,018
0.016699
# posting to: http://localhost:3000/api/articles/update/:articleid with title, content # changes title, content # # id1: (darwinbot1 P@ssw0rd!! 57d748bc67d0eaf026dff431) <-- this will change with differing mongo instances import time # for testing, this is not good import requests # if not installed already, run python...
) print(json) gameID = json['gameID'] playerID = json['playerID'] print(gameID) print(
playerID) input = ' ' while input != '': input = raw_input('input move: ') r = requests.post('http://localhost:80/api/games/submit/' + gameID, data={'playerID': playerID, 'move': input, 'devkey': "581ced5d7563227053011823"}); # submit sample move json = r.json() print(json)
pythonvietnam/nms
apps/alarm/apps.py
Python
mit
85
0
fro
m django.a
pps import AppConfig class AlarmConfig(AppConfig): name = 'alarm'
codenote/chromium-test
tools/telemetry/telemetry/core/chrome/inspector_backend.py
Python
bsd-3-clause
9,767
0.009727
# 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. import json import logging import socket import sys from telemetry.core import util from telemetry.core import exceptions from telemetry.core.chrome impo...
._runtime.Evaluate( 'window.chrome.gpuBenchmarking === undefined'): return Fa
lse if self._runtime.Evaluate( 'window.chrome.gpuBenchmarking.beginWindowSnapshotPNG === undefined'): return False # TODO(dtu): Also check for Chrome branch number, because of a bug in # beginWindowSnapshotPNG in older versions. crbug.com/171592 return True def Screenshot(self, timeo...
danieldUKIM/controllers_dockers
rem_console/REM_console.py
Python
apache-2.0
2,275
0.037528
#!/usr/bin/python3 import rem_backend.query_data as qd import rem_backend.propagation_model_estimation as pm import threading import _thread __author__ = "Daniel Denkovski", "Valentin Rakovic" __copyright__ = "Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia"...
"3. Path loss model estimation") print("0. Quit") choice = input(" >>  ") if (choice == '0'): run = 0 elif (choice == '1'): print("Loc:Enter the channel of interest") chann = input(" >>  ") dev_list = qd.get_all_active_devices_on_channel(chann,1) try: print("Select the index of the device o...
ind += 1 devind = input(" >>  ") print(dev_list[int(devind)-1][0]) try: location = qd.estimate_tx_location(str(dev_list[int(devind)-1][0]),10) print("The location of devices {} is:".format(str(dev_list[int(devind)-1][0]))) print("x:{} y:{} z:{} Pt:{} dBm".format(location[0],location[1],locat...
PetePriority/home-assistant
homeassistant/components/lutron/light.py
Python
apache-2.0
2,793
0
""" Support for Lutron lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.lutron/ """ import logging from homeassistant.components.light import ( ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light) from homeassistant.components.lutron import ( ...
(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS @property def brightness(self): """Return the brightness of the light.""" new_brightness = to_hass_level(self._lutron_device.last_level()) if new_brightness != 0: self._prev_brightness = new_bri...
new_brightness def turn_on(self, **kwargs): """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs and self._lutron_device.is_dimmable: brightness = kwargs[ATTR_BRIGHTNESS] elif self._prev_brightness == 0: brightness = 255 / 2 else: brightness = s...
TacticAlpha/basic-lan-webserver
server/status.py
Python
agpl-3.0
938
0
import json as json_ # Template for code 200 requests so data can easily be added def ok(d=None, *, json=True): code = {'code': 200, 'status': 'OK', 'data': d
} if json: code = json_.dumps(code) return code # The 400 codes shoul
dn't require any special aruments. def invalid_request(*, json=True): code = {'code': 400, 'status': 'MALFORMED_REQUEST'} if json: code = json_.dumps(code) return code def unknown_request(*, json=True): code = {'code': 400, 'status': 'UNKNOWN_REQUEST'} if json: code = json_.dumps(c...
pepincho/Python101-and-Algo1-Courses
Programming-101-v3/week9/1-Money-In-The-Bank/start.py
Python
mit
465
0.002151
from bank_CI import BankCI from bank_controller
import BankController from settings import DB_NAME, CREATE_TABLES, DROP_DATABASE from sql_manager import BankDatabaseManager def main(): manager = BankDatabaseManager.create_from_db_and_sql(DB_NAME, CREATE_TABLES, DROP_DATABASE, create_if_exists=False) controller = BankController(manager) command_interfac...
== '__main__': main()
duointeractive/python-bluefin
bluefin/__init__.py
Python
bsd-3-clause
31
0.032258
#
Major, Minor VERSION = (1, 4)
internap/netman
netman/core/objects/backward_compatible_switch_operations.py
Python
apache-2.0
3,375
0.003556
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
ce_state(interface_id, state) instead", DeprecationWarning) return self.set_interface_state(inte
rface_id, OFF) def openup_interface(self, interface_id): warnings.warn("Deprecated, use set_interface_state(interface_id, state) instead", DeprecationWarning) return self.set_interface_state(interface_id, ON)
gguillen/galeranotify
galeranotify.py
Python
gpl-2.0
5,427
0.00387
#!/usr/bin/python # # Script to send email notifications when a change in Galera cluster membership # occurs. # # Complies with http://www.codership.com/wiki/doku.php?id=notification_command # # Author: Gabe Guillen <[email protected]> # Version: 1.5 # Release: 3/5/2015 # Use at your own risk. No warranties expr...
message += "-- " message += self._members[i] + "\n" else: message += "\
n".join((" " + str(x)) for x in self._members) message += "\n" if(self._index): message += "Index of this node in the member list: " + self._index + "\n" return message if __name__ == "__main__": main(sys.argv[1:])
mr-uuid/snippets
python/classes/init_vs_call.py
Python
mit
530
0.001887
# making a class callable: class a(object): def __init__(self, a): print "__init__" self.a = a def __call__(self, *args): print "__call__" self.a = args[0] # Based on this code, when we call a, the __init__ function gets called. My guess # is that we dont have
an instance initiallzed, then when we have an instance, # we can call it # Initallizing an obj apple = a("Hello")
# Calling an obj apple("Hi") # What will this do? : # @a # def fuu(*args): # print args # fuu("hi")
peterhinch/micropython-tft-gui
tft/driver/tft.py
Python
mit
32,591
0.010034
# # The MIT License (MIT) # # Copyright (c) 2016 Robert Hammelrath # # 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, cop...
d_data(0xe2, bytearray(b'\x1d\x02\x54'), 3) # PLL multiplier, set PLL clock to 100M # N=0x2D for 6.5MHz, 0x1D for 10MHz crystal # PLLClock = Crystal * (Mult + 1) / (Div + 1) # The intermediate value Crystal * (Mult + 1) must be
between 250MHz and 750 MHz TFT_io.tft_cmd_data(0xe0, bytearray(b'\x01'), 1) # PLL Enable pyb.delay(10) TFT_io.tft_cmd_data(0xe0, bytearray(b'\x03'), 1) pyb.delay(10) TFT_io.tft_cmd(0x01) # software reset pyb.delay(10) # # Settin...
scrapycloud/scrapy-cluster
crawler/crawler/spiders/baidu.py
Python
mit
979
0.002043
# -*- coding: utf-8 -*- from scrapy.spiders import Rule from scrapy.linkextractors import LinkE
xtractor from scrapy_redis.spiders import RedisCrawlSpider class BaiduSpider(RedisCrawlSpider): """Spider that reads urls from redis queue (myspider:start_urls).""" name = 'baidu' redis_key = 'crawler:start_keyword' """Spider that reads urls from redis queue when idle.""" rules = ( Rule(L...
lly define the allowed domains list. domain = kwargs.pop('domain', '') self.allowed_domains = filter(None, domain.split(',')) super(BaiduSpider, self).__init__(*args, **kwargs) def parse_page(self, response): data = { 'name': response.css('title::text').extract_first(), ...
torypages/luigi
luigi/lock.py
Python
apache-2.0
3,102
0.001289
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
onality
when launching things from the command line. Uses a pidfile. This prevents multiple identical workflows to be launched simultaneously. """ from __future__ import print_function import hashlib import os from luigi import six def getpcmd(pid): """ Returns command of process. :param pid: """ cmd ...
j-martin/raspberry-gpio-zmq
raspzmq/alerts.py
Python
mit
3,371
0.00089
#!/usr/bin/env python """alerts.py Classes for sendings alerts """ __author__ = "Jean-Martin Archer" __copyright__ = "Copyright 2013, MIT License." import smtplib from twilio.rest import TwilioRestClient from vendors.pushbullet.pushbullet import PushBullet import configuration class Alerts(object): """<ac:im...
self.receivers = self.config['email_receivers'] self.server = self.config['server'] def send_notification(self,
message): email_body = """From: Alert <%s> To: Alert <%s> Subject: %s This is a test e-mail message. """ % (self.sender, self.receivers, message) try: smtpObj = smtplib.SMTP(self.server) smtpObj.sendmail(self.sender, self.receivers, email_body)...
kslundberg/pants
src/python/pants/backend/codegen/tasks/protobuf_gen.py
Python
apache-2.0
13,284
0.008883
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import itertools imp...
ports jars. jars_address = Address(os.path.relpath(self.codegen_work
dir(target), get_buildroot()), target.id + '-rjars') jars_target = self.context.add_new_target(jars_address, JarLibrary, jars=target.imported_jars, ...
ntt-sic/nova
nova/virt/configdrive.py
Python
apache-2.0
6,518
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Michael Still and Canonical 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:...
raise exception.ConfigDriveMountFailed(operation='mount', error=err) mounted = True # NOTE(mikal): I can't just use
shutils.copytree here, because the # destination directory already exists. This is annoying. for ent in os.listdir(self.tempdir): shutil.copytree(os.path.join(self.tempdir, ent), os.path.join(mountdir, ent)) finally: if mounte...
rjschwei/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/conn_string_info.py
Python
mit
1,434
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
------------------------------------------------------------- from msrest.serialization import Model class ConnStrin
gInfo(Model): """Database connection string information. :param name: Name of connection string. :type name: str :param connection_string: Connection string value. :type connection_string: str :param type: Type of database. Possible values include: 'MySql', 'SQLServer', 'SQLAzure', 'Custom...
aerler/HGS-Tools
Python/geospatial/xarray_tools.py
Python
gpl-3.0
40,502
0.015234
''' Created on Feb. 23, 2019 Utility functions to extract data from xarray Dataset or DataArray classes. @author: Andre R. Erler, GPL v3 ''' from warnings import warn from datetime import datetime import os import numpy as np import xarray as xr import netCDF4 as nc from dask.diagnostics import ProgressBar # intern...
xlon = None if ylat_dim in xvar.coords: ylat = xvar.coords[ylat_dim] if lvars else ylat_dim else: ylat = None elif isinstance(xvar,nc.Variable) and lraise: raise TypeError("Cannot infer coordinates from netCDF4 Variable - only Dataset!") elif isinstance(xvar,nc.Dataset): ...
riables: ylat = xvar.variables[ylat_dim] if lvars else ylat_dim else: ylat = None # optionally raise error if no coordinates are found, otherwise just return None if lraise and (xlon is None or ylat is None): raise ValueError("No valid pair of geographic coodinates found:\n...
chrismattmann/drat
distribution/src/main/resources/bin/list-ghe-repos.py
Python
apache-2.0
1,171
0
#!/usr/bin/env python3.7 # 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 "Li...
le 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. import github3 import sys githubent = github3.enterprise_login( username=sys.argv[1], password=sys.argv[2], url=sys.argv[3]) for d in ["2014", "2015", "2016", "2017", "2018", "2019"]: date...
bartTC/django-markup
django_markup/filter/markdown_filter.py
Python
bsd-3-clause
1,360
0
from django_markup.filter import MarkupFilter class MarkdownMarkupFilter(MarkupFilter): """ Applies Markdown conversion to a string, and returns the HTML. """ title = 'Markdown' kwargs = {'safe_mode': True} def render(self, text, **kwargs): if kwargs: self.kwargs.updat
e(kwargs) from markdown import markdown text = markdown(text, **self.kwa
rgs) # Markdowns safe_mode is deprecated. We replace it with Bleach # to keep it backwards compatible. # https://python-markdown.github.io/change_log/release-2.6/#safe_mode-deprecated if self.kwargs.get('safe_mode') is True: from bleach import clean # fmt: off ...
JoseBlanca/franklin
franklin/backbone/mapping.py
Python
agpl-3.0
16,787
0.005957
''' This module is part of ngs_backbone. This module provide mapping related analyses Created on 15/03/2010 @author: peio ''' # Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of franklin. # franklin is free software: you can redistribute it and/or modify # it under the...
s_path.last_version, reference_fpath) def _get_basename(fpath): 'It returns the base name without path and extension' return os.path.splitext(os.path.basename(fpath))[0] class MappingAnaly
zer(Analyzer): 'It performs the mapping of the sequences to the reference' def run(self): '''It runs the analysis.''' self._log({'analysis_started':True}) project_settings = self._project_settings settings = project_settings['Mappers'] tmp_dir = project_settings['General...
mrexmelle/liblinesdk-py
setup.py
Python
mit
1,211
0.000826
import os from setuptools import setup from setuptools import find_packages with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='li...
'Pr
ogramming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
nuclear-wizard/moose
python/MooseDocs/extensions/floats.py
Python
lgpl-2.1
8,900
0.004494
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/
COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import uuid import collections import moosetree import MooseDocs from ..common import exceptions from ..base import components, MarkdownReader, LatexRenderer, Extension from ..tree import tokens, html,...
eturn FloatExtension(**kwargs) Float = tokens.newToken('Float', img=False, bottom=False, command='figure') FloatCaption = tokens.newToken('FloatCaption', key='', prefix='', number='?') ModalLink = tokens.newToken('ModalLink', bookmark=True, bottom=False, close=True) ModalLinkTitle = tokens.newToken('ModalLinkTitle') M...
openstack/congress
congress/db/db_ds_table_data.py
Python
apache-2.0
3,233
0
# Copyright (c) 2016 VMware, Inc. All right
s reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complian
ce with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, ei...
eddie-dunn/swytcher
swytcher/swytcher.py
Python
mit
3,436
0
"""Automatic keyboard layout switcher""" import functools import logging import subprocess from typing import Iterable from typing import Set import xkbgroup import swytcher.settings as settings import swytcher.xwindow as xwindow from swytcher.util import suppress_err log = logging.getLogger(__name__) # pylint: dis...
e[str], substrings: Iterable[str]) -> Set[str]: """Returns True if any of the strings in the two filters `strings` and `substrings` occur in `name_list`.""" matched = (set(strings) & set(name_list) or _match_substrings(name_list, substrings or {})) if matched: log.debu...
None: # pragma: no cover """Event handler when active window is changed""" # NOTE: These extracted variables should be removed later primary_filter = layouts[0]['strings'] primary_substrings = layouts[0]['substrings'] primary = layouts[0]['name'] secondary_filter = layouts[1]['strings'] se...
d0ugal/readthedocs.org
readthedocs/projects/migrations/0028_add_version_default_privacy.py
Python
mit
9,508
0.007678
# -*- 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 'Project.version_privacy_level' db.add_column('projects_project', 'version_privacy_level', ...
{'max_length': '255', 'blank': 'True'}), 'documentation_type': ('django.db.models.fields.CharField', [], {'default': "'sphinx'", 'max_length': '20'}), 'featured': ('django.db.models.fields.BooleanField', [], {'def
ault': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'pa...
berquist/PyQuante
PyQuante/OEP.py
Python
bsd-3-clause
25,427
0.019664
"Yang/Wu's OEP implementation, in PyQuante." from math import sqrt import settings from PyQuante.NumWrap import zeros,matrixmultiply,transpose,dot,identity,\ array,solve from PyQuante.Ints import getbasis, getints, getJ,get2JmK,getK from PyQuante.LA2 import geigh,mkdens,trace2,simx from PyQuante.hartree_fock impo...
kwargs): self.iter = 0 self.etemp = kwargs.get("etemp",settings.DFTElectronTemperature) logging.debug("iter Energy <b|b>") logging.debug("---- ------ -----")
self.b = fminBFGS(self.get_energy,self.b,self.get_gradient,logger=logging) return def get_energy(self,b): self.iter += 1 self.Hoep = get_Hoep(b,self.H0,self.Gij) self.orbe,self.orbs = geigh(self.Hoep,self.S) if self.etemp: self.D,self.entropy = mkdens_fe...
missionpinball/mpf-monitor
mpfmonitor/core/devices.py
Python
mit
13,716
0.000948
import logging import time import os # will change these to specific imports once code is more final from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5 import uic BRUSH_WHITE = QBrush(QColor(255, 255, 255), Qt.SolidPattern) BRUSH_GREEN = QBrush(QColor(0, 255, 0), Qt.SolidPat...
value > 255: self.log.warning("Got value %s for brightness which outside the expected range", value) value = 0 value = int(pow(value, gamma) * a) if value > 255: value = 255 corrected.append(value) return corrected def _c...
ype == 'light': color = self.data()['color'] if color == [0, 0, 0]: # shortcut for black return BRUSH_BLACK color = self._calculate_color_gamma_correction(color) elif self._type == 'switch': state = self.data()['state'] ...
gabrik/ingunict-bot
ingbot.py
Python
apache-2.0
9,550
0.030389
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ING UNI CT Telegram Bot from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import logging from utils import utility from unidecode import unidecode import json #need load configuration from file ROOMS_FILE='utils/rooms.json' COURSES_FILE='utils...
lassrooms if insegnamento_name.upper() in insegnamento['Nome'].upper()] if len(search_result)>0: bot.sendMessage(update.message.chat_id, text='Sono stati trovati %d insegnamenti con la tua ricerca' % len(search_result)) descr="" for m in search_result: doc=''.join([docente+'\n' for docente in m['Doc...
: %s\nCorso di Laurea: %s\n" % (m['Nome'], m['Semestre'], m['Corso di Laurea']) descr+= "Anno: %s\nDocenti: %s\nSSD: %s\n" % (m['Anno'], doc, m['SSD']) descr+= "CFU: %s\n\n" % (m['CFU']) bot.sendMessage(update.message.chat_id, text=descr) else: bot.sendMessage(update.message.chat_id, text='Insegnam...
mhallin/knitty-gritty
setup.py
Python
bsd-3-clause
918
0
from setuptools import setup, find_packages with open('README.rst') as f: description = f.read() setup( name='knitty-gritty', ver
sion='0.0.2', description='A tool for managing knitting machine patterns', long_description=description, url='https://github.com/mhallin/knitty-gritty', author='Magnus Hallin', author_email='[email protected]', license='BSD', packages=find_packages(), install_requires=[ 'clic...
.4,<2.5', 'Pillow>=2.5,<2.6', 'pyserial>=2.7,<2.8', ], extras_require={ 'dev': [ 'flake8>=2.2,<2.3', 'mccabe>=0.2,<0.3', 'pep8>=1.5,<1.6', 'pip-tools>=0.3,<0.4', 'pyflakes>=0.8.1,<0.9', 'wheel>=0.24,<0.25', ...
pombredanne/stockpile
stockpile/__about__.py
Python
bsd-2-clause
539
0
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals __all__ = [ "__title__", "__summary__", "__u
ri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "stock
pile" __summary__ = "Generic file storage abstraction" __uri__ = "https://github.com/dstufft/stockpile/" __version__ = "0.1" __author__ = "Donald Stufft" __email__ = "[email protected]" __license__ = "Simplified BSD" __copyright__ = "Copyright 2012 Donald Stufft"
zstackio/zstack-woodpecker
integrationtest/vm/ha/test_one_node_shutdown_with_scheduler.py
Python
apache-2.0
2,920
0.004452
''' Integration Test for scheduler reboot VM in HA mode. @author: Quarkonics ''' import zstackwoodpecker.test_
util as test_util impo
rt zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header import zstackwoodpecker.operations.vm_operations as vm_ops import zstackwoodpecker.operati...
dendyyangky/sgeede_b2b
sgeede_internal_transfer/stock_internal_transfer.py
Python
unlicense
4,237
0.029974
from datetime import date, datetime from dateutil import relativedelta import json import time from openerp.osv import fields, osv from openerp.tools import float_compare from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT from openerp import SUPER...
ehouse_id' : fields.many2one('stock.warehouse', 'Source Warehouse', track_visibility='onchange'), 'dest_warehouse_id' : fields.many2one('stock.warehouse', 'Destination Warehouse', track_visibility='onchange'), 'state' : fields.selection([('c
ancel', 'Cancel'), ('draft', 'Draft'), ('send', 'Send'), ('done', 'Done')], 'Status', track_visibility='onchange'), 'line_ids' : fields.one2many('stock.internal.transfer.line', 'transfer_id', 'Stock Internal Transfer Line'), 'picking_ids' : fields.one2many('stock.picking', 'transfer_id', 'Picking'), 'backorder_id...
earwig/earwigbot
earwigbot/tasks/__init__.py
Python
mit
5,993
0.000167
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2015 Ben Kurtovic <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated
documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following ...
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT ...
arju88nair/projectCulminate
venv/lib/python3.5/site-packages/pylint/test/regrtest_data/beyond_top/__init__.py
Python
apache-2.0
108
0.009259
from ... import Something from .
import data try: from ... import Lala except I
mportError: pass
dbbhattacharya/kitsune
vendor/packages/pylint/test/input/func_interfaces.py
Python
bsd-3-clause
1,802
0.010544
# pylint:disable-msg=R0201 """docstring""" __revision__ = '' class Interface: """base class for interfaces""" class IMachin(Interface): """docstring""" def truc(self): """docstring""" def troc(self, argument): """docstring""" class Correct1: """docstring""" __implemen...
_ = IMachin def __init__(self): pass def truc(self): """docstring""" pass def troc(self, argument): """docstring""" pass class Correct2: """docstring""" __implements__ = (IMachin,) def __init__(self): pass def truc(self): ...
IMachin, def __init__(self): pass def troc(self, argument): """docstring""" print argument def other(self): """docstring""" class BadArgument: """docstring""" __implements__ = (IMachin,) def __init__(self): pass def truc(self): "...
Petrole/MaturePyRobots
WebPyRobot/backend/migrations/0009_userprofile_level.py
Python
gpl-3.0
460
0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-15 14:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0008_auto_20171115_1443'), ] operations = [ migrations.AddField( model_name...
field=models.PositiveIntegerField(default=1), ), ]
vtemian/university_projects
practic_stage/hmw7/main.py
Python
apache-2.0
125
0
from office import Office from bank i
mport Bank bank = Bank("Open Bank") office = Office("Timisoara", ban
k) office.open()
justinnoah/autobot
autobot/common.py
Python
apache-2.0
1,761
0.001136
# # common.py # # Copyright (C) 2009 Justin Noah <[email protected]> # # Basic plugin template created by: # Copyright (C)
2008 Martijn Voncken <[email protected]> # Copyright (C) 2007-2009 Andrew Resch <[email protected]> # Copyright (C) 2009 Damien Churchill <[email protected]> # # Deluge is free software. # # You may redistribute it and/or modify it under the terms of the # GNU General Public License, as published by the Free Softwa...
at it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with deluge. If not, write to: # The Free...
BrainIntensive/OnlineBrainIntensive
resources/nipype/nipype/examples/dmri_preprocessing.py
Python
mit
5,464
0.000549
# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ =================== dMRI: Preprocessing =================== Introduction ============ This script, dmri_preprocessing.py, demonstrates how to prepare dMRI data for tractography and co...
_id')]), (datasource, prep, [('dwi', 'inputnode.in_file'), ('dwi_rev', 'inputnode.alt_file'), ('bvals', 'inputnode.in_bval'), ('bvecs', 'inputnode.in_bvec')]), (prep, bias, [('outputnode.out_file', 'inputnode.in_file'), ('...
executable """ if __name__ == '__main__': wf.run() wf.write_graph()
wakiyamap/electrum-mona
electrum_mona/gui/qt/update_checker.py
Python
mit
6,116
0.00327
# Copyright (C) 2019 The Electrum developers # Distr
ibuted under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php import asyncio import base64 from distutils.version import LooseVersion from PyQt5.QtCore import Qt, QThread, pyqtSignal from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QLabel, QProgress...
rum_mona import constants from electrum_mona import ecc from electrum_mona.i18n import _ from electrum_mona.util import make_aiohttp_session from electrum_mona.logging import Logger from electrum_mona.network import Network class UpdateCheck(QDialog, Logger): url = "https://electrum-mona.org/version" download...
turbokongen/home-assistant
homeassistant/components/withings/common.py
Python
apache-2.0
34,960
0.00083
"""Common code for Withings.""" import asyncio from dataclasses import dataclass import datetime from datetime import timedelta from enum import Enum, IntEnum import logging import re from typing import Any, Callable, Dict, List, Optional, Tuple, Union from aiohttp.web import Response import requests from withings_api...
", SENSOR_DOMAIN, True, UpdateType.POLL, ), WithingsAttribute( Measurement.SKIN_TEMP_C,
MeasureType.SKIN_TEMPERATURE, "Skin Temperature", const.UOM_TEMP_C, "mdi:thermometer", SENSOR_DOMAIN, True, UpdateType.POLL, ), WithingsAttribute( Measurement.FAT_RATIO_PCT, MeasureType.FAT_RATIO, "Fat Ratio", PERCENTAGE, ...
wright-group/PyCMDS
pycmds/project/file_dialog_handler.py
Python
mit
4,481
0.000893
""" QFileDialog objects can only be run in the main thread. """ ### imports ################################################################### import os import time from PySide2 import QtCore from PySide2 import QtWidgets from pycmds.project import project_globals as g from pycmds.project import classes as pc ...
if QtCore.QThread.currentThread() == g.main_thread.read(): file_dialog.getExistingDirectory(inputs) else: q.push("getExistingDirectory", inputs) while busy.read(): time.sleep(0.1) return directory_filepath.read() def open_dialog(caption, directory, options): inputs = [c...
ame(inputs) else: q.push("getOpenFileName", inputs) while busy.read(): time.sleep(0.1) return open_filepath.read() def save_dialog(caption, directory, savefilter, selectedfilter, options): inputs = [caption, directory, savefilter, selectedfilter, options] if QtCore.QThread....
knnniggett/weewx
bin/weewx/drivers/ws23xx.py
Python
gpl-3.0
77,294
0.004463
#!usr/bin/env python # # Copyright 2013 Matthew Wall # See the file LICENSE.txt for your full rights. # # Thanks to Kenneth Lavrsen for the Open2300 implementation: # http://www.lavrsen.dk/foswiki/bin/view/Open2300/WebHome # description of the station communication interface: # http://www.lavrsen.dk/foswiki/bin/vie...
llowing: addr smpl description 0x527 0 Wind overflow flag: 0 = normal 0x528 0 Wind minimum code: 0=min, 1=--.-, 2=OFL 0x529 0 Windspeed: binary nibble 0 [m/s * 10] 0x52A 0 Windspeed
: binary nibble 1 [m/s * 10] 0x52B 0 Windspeed: binary nibble 2 [m/s * 10] 0x52C 8 Wind Direction = nibble * 22.5 degrees 0x52D 8 Wind Direction 1 measurement ago 0x52E 9 Wind Direction 2 measurement ago 0x52F 8 Wind Direction 3 measurement ago 0x530 7 Wind Direction 4 measurement ago 0x531 7 Wind ...
abarisain/mopidy
mopidy/utils/path.py
Python
apache-2.0
5,006
0.0002
from __future__ import unicode_literals import logging import os import string import urllib import urlparse import glib logger = logging.getLogger(__name__) XDG_DIRS = { 'XDG_CACHE_DIR': glib.get_user_cache_dir(), 'XDG_CONFIG_DIR': glib.get_user_config_dir(), 'XDG_DATA_DIR': glib.get_user_data_dir(),...
s inplace dirnames.remove(dirname) for filename in filenames: if filename.startswith(b'.'): # Skip hidden files continue yield os.path.relpath(os.path.join(dirpath, filename), path) def check_file_path_is_inside_base_dir(file_path, base...
h a path separator' % file_path) # Expand symlinks real_base_path = os.path.realpath(base_path) real_file_path = os.path.realpath(file_path) # Use dir of file for prefix comparision, so we don't accept # /tmp/foo.m3u as being inside /tmp/foo, simply because they have a # common prefix, /tmp/fo...
ImpregnableProgrammer/Advent-of-Code
2019/Day_06.py
Python
gpl-3.0
1,071
0.006536
def First_Part(orbits): Orbits = dict() checksum = 0 for orbit in orbits: od, og = orbit.split(')') Orbits[og] = od for og in Orbits.keys(): while 1: try: og = Orbits[og] checksum += 1 except KeyError: break...
'\n')[:-1] print(First_Part(Orbits)) print(Second_
Part(Orbits))
naoyeye/geeksoho
application.py
Python
mit
1,969
0.019457
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: J.Y Han # start # spawn-fcgi -d /users/hanjiyun/project/geeksoho -f /users/hanjiyun/project/geeksoho/application.py -a 127.0.0.1 -p 9001 #stop # kill `pgrep -f "/users/hanjiyun/project/geeksoho/application.py"` import os import web import rediswebpy from web....
der.jobs(jobsList=jobsList) def POST(self): data = web.input(title='', link='', company='', company_weibo='', company_website='', city='', salary='', intro='') CreatNewJob(data) raise web.seeother('/') class test: """test""" def GET(self): # return pjax('test.html') ...
'jobs', title = data.title, link = data.link, company = data.company, company_weibo = data.company_weibo, company_website = data.company_website, city = data.city, salary = data.salary, intro = data.intro) def GetJobs(): return db.select('jobs', li...
jbms/ofxclient
ofxclient/config.py
Python
mit
9,882
0.000506
from __future__ import with_statement from ofxclient.account import Account from configparser import ConfigParser import os import os.path try: import keyring KEYRING_AVAILABLE = True except: KEYRING_AVAILABLE = False try: DEFAULT_CONFIG = os.path.expanduser(os.path.join('~', 'ofxclient.ini')) except:...
v)) return items def secure_items(self, section): """Like items() but only return secure items. :param section: section id :type section: string """
return [x for x in self.items(section) if self.is_secure_option(section, x[0])] def set(self, section, option, value): """Set an option value. Knows how to set options properly marked as secure.""" if self.is_secure_option(section, option): self.s...
sharadagarwal/autorest
AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/paging_tests.py
Python
mit
6,270
0.003191
# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""),...
D *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # # --...
halcy/MastodonToTwitter
mtt/__init__.py
Python
mit
1,421
0
import os from threading import RLock from path import Path import mtt.config as base_config # noqa __all__ = ['config', 'lock'] class ConfigAccessor: def __init__(self, configuration_items): self.config = configuration_items def update(self, other): self.config.update(other.config if 'co...
and not isinstance(value, module_type) and not isinstance(value, class_type)} return ConfigAccessor(variables) config = get_variables_in_module('base_config') try:
import mtt.user_config as user_config # noqa config.update(get_variables_in_module('user_config')) except ImportError: pass lock = RLock()
steveniemitz/scales
test/integration/thrift/test_mux.py
Python
mit
224
0.017857
import unittest fro
m integration.thrift.test_thrift import ThriftTestCase from scales.thriftmux import ThriftMux class ThriftMuxTestCase(ThriftTestCase): BUILDER = ThriftMux if __name__ == '__main__': unittest.
main()
kgao/MediaDrop
mediacore/lib/auth/group_based_policy.py
Python
gpl-3.0
52
0
from mediadrop.lib.auth.group_based_
policy import *
coala/coala-bears
tests/python/requirements/PySafetyBearWithoutMockTest.py
Python
agpl-3.0
5,749
0
import os from queue import Queue from bears.python.requirements.PySafetyBear import PySafetyBear from coalib.settings.Section import Section from coalib.settings.Setting import Setting from coalib.testing.LocalBearTestHelper import LocalBearTestHelper from coalib.results.Result import Result from coalib.results.RESUL...
mpleteM
e to execute arbitrary code.')], filename=get_testfile_path(file_name)) def test_without_cve_vulnerability(self): file_name = 'requirement.txt' file_contents = load_testfile(file_name) file_contents = [file_contents[1]] self.check_results( self.uut, ...
TailorDev/pauling
api/models.py
Python
mit
2,935
0.001704
import datetime import uuid from flask import current_app as app from flask import url_for from database import db from sqlalchemy import Column, DateTime, String, Text from sqlalchemy.dialects.postgresql import UUID class Poster(db.Model): __tablename__ = 'posters' id = Column(UUID(as_uuid=True), primary_...
de_svg_url(self, absolute=False): return url_for('get_qrcode_svg', id=self.id, _external=absolute) def qrcode_png_url(self, absolute=False): return url_for('get_qrcode_png', id=self.id, _external=absolute) def is_image(self): return self.download_url.endswith('.png') or self.download_u...
oudinary): return self.download_url return '{}/image/fetch/{}'.format(cloudinary, self.download_url) def thumbnail_url(self): cloudinary = app.config['CLOUDINARY_BASE_URL'] transformations = 'c_thumb,w_370,h_200,f_png' if self.download_url.startswith(cloudinary): ...
dyomas/pyhrol
examples/example_0050.py
Python
bsd-3-clause
1,983
0.00706
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2013, 2014, Pyhrol, [email protected] # GEO: N55.703431,E37.623324 .. N48.742359,E44.536997 # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistri...
ILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WA
Y # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # import example_0050 try: example_0050.function_with_keywords() except TypeError as ex: print '***', ex try: example_0050.function_with_keywords(arg1 = 1) except TypeError as ex: print '***', ex example_0050.functio...
Dennisparchkov/rumal
interface/management/commands/fdaemon.py
Python
gpl-2.0
10,312
0.001649
#!/usr/bin/env python # # fdaemon.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; w...
rt loads,dumps import json from bson import json_util from interface.producer import Producer import pika STATUS_NEW = 0 # identifies local status of task STATUS_PROCESSING = 1 STATUS_FAILED = 2 STATUS_COMPLETED = 3 STATUS_TIMEOUT = 4 NEW_SCAN_TASK = 1 # identifies data being sent to back end SEND_ANY = 'Any' ANY...
y_queue' PRIVATE_QUEUE = 'private_queue' RPC_PORT = 5672 config = ConfigParser.ConfigParser() config.read(os.path.join(settings.BASE_DIR, "conf", "backend.conf")) BACKEND_HOST = config.get('backend', 'host', 'localhost') # mongodb connection settings client = pymongo.MongoClient() db = client.thug dbfs = client.thugf...
hacklab-fi/hhlevents
hhlevents/apps/hhlregistrations/migrations/0005_auto_20150412_1806.py
Python
bsd-3-clause
592
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db impor
t models, migrations class Migration(migrations.Migration): dependencies = [ ('hhlregistrations', '0004_auto_
20150411_1935'), ] operations = [ migrations.AddField( model_name='event', name='payment_due', field=models.DateTimeField(null=True, blank=True), ), migrations.AddField( model_name='event', name='require_registration', ...
wozz/electrum-myr
lib/transaction.py
Python
gpl-3.0
30,650
0.006754
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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...
i = i + 1 self.lookup = lookup self.reverseLookup = reverseLookup def __getattr__(self, attr): if not self.lookup.has_key(attr): raise AttributeError return self.lookup[attr] def whatis(self, value): return self.reverseLookup[value] # This function ...
bytes.encode('hex_codec') # This function comes from bitcointools, bct-LICENSE.txt. def short_hex(bytes): t = bytes.encode('hex_codec') if len(t) < 11: return t return t[0:4]+"..."+t[-4:] def parse_redeemScript(bytes): dec = [ x for x in script_GetOp(bytes.decode('hex')) ] # 2 of 2 ...
Bleno/sisgestor-django
docente/apps.py
Python
mit
89
0
from djang
o.apps import AppConfig class DocenteConfig(AppConfig): nam
e = 'docente'
woddx/privacyidea
tests/base.py
Python
agpl-3.0
4,803
0.000625
import unittest import json from privacyidea.app import create_app from privacyidea.models import db from privacyidea.lib.resolver import (save_resolver) from privacyidea.lib.realm import (set_realm) from privacyidea.lib.user import User from privacyidea.lib.auth import create_db_admin from privacyidea.api.lib.postpoli...
self.assertTrue(user_str == "<root.resolver1@realm1>", user_str) self.assertFalse(user.is_empty()) self.assertTrue(User().is_empty()) user_repr = "%r" % user expected = "User(login='root', realm='realm1', resolver='resolver1')" self.assertTrue(user_repr == expected, user_repr...
dresolver", "fileName": PWFILE}) self.assertTrue(rid > 0, rid) (added, failed) = set_realm(self.realm2, [self.resolvername1]) self.assertTrue(len(failed) == 0) self.assertTrue(len(added) == 1) user = User(login="r...
geojames/Dart_EnvGIS
Week6-2_Matplotlib_Adv.py
Python
mit
3,114
0.008992
#------------------------------------------------------------------------------ __author__ = 'James T. Dietrich' __contact__ = '[email protected]' __copyright__ = '(c) James Dietrich 2016' __license__ = 'MIT' __date__ = 'Wed Nov 16 11:33:39 2016' __version__ = '1.0' __status__ = "initial release" __url__ =...
h.edu Copyright: (c) James Dietrich 2016 """ #-
----------------------------------------------------------------------------- import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # MESHGRID # # Meshgrid is a command/function that allows you to easily build X and Y # grids from 1-D arrays/vectors which can be used to evalua...
yugangw-msft/azure-cli
src/azure-cli/azure/cli/command_modules/vm/disk_encryption.py
Python
mit
27,499
0.004291
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
force=False): from msrestazure.tools import parse_resource_id from knack.util import CLIError # pylint: disable=no-member
compute_client = _compute_client_factory(cmd.cli_ctx) vm = compute_client.virtual_machines.get(resource_group_name, vm_name) is_linux = _is_linux_os(vm) backup_encryption_settings = vm.storage_profile.os_disk.encryption_settings vm_encrypted = backup_encryption_settings.enabled if backup_encryption_se...
anzenehansen/wedding-photos
plugins/bases/handlers.py
Python
mpl-2.0
4,489
0.008911
import tornado.web import traceback from plugins.bases.plugin import PluginBase import os import sys import gdata import gdata.youtube import gdata.youtube.service class HandlersBase(tornado.web.RequestHandler, PluginBase): # Every handler must have a web path, override this in this fashion WEB_PATH = r"/" ...
Feed(uri=self.yt_plist_uri) # Get total number of videos in playlist def yt_playlist_count(self): plist = self.yt_playlist() entry = [] for e in plist.entry: entry.append(e) return len(entry) # Wrapper to get upload token for Y...
uest def yt_uploadtoken(self, mg): video_entry = gdata.youtube.YouTubeVideoEntry(media=mg) response = self.yt_service.GetFormUploadToken(video_entry) return (response[0], response[1]) # This defines various aspects of the video def yt_mediagroup(self, title, desc): ...
PEDSnet/pedsnetcdms
pedsnetcdms/pedsnetcdm/alembic/versions/cfbd6d35cab_initial.py
Python
bsd-2-clause
30,989
0.012101
"""Initial Revision ID: cfbd6d35cab Revises: Create Date: 2015-03-04 04:13:56.547992 """ # revision identifiers, used by Alembic. revision = 'cfbd6d35cab' down_revision = None branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by A...
id'), 'organization', ['organization_id'], unique=False, postgresql_ops={}) op.create_index(op.f('ix_organization_organization_source_value_place_of_service_source_value'), 'organization', ['organization_source_value', 'place_of_service_source_value'], unique=False, postgresql_ops={u'place_of_service_source_value':...
e': u'varchar_pattern_ops'}) op.create_table('care_site', sa.Column('place_of_service_source_value', sa.String(length=100), nullable=True), sa.Column('place_of_service_concept_id', sa.Integer(), nullable=True), sa.Column('care_site_source_value', sa.String(length=100), nullable=False), sa.Column('or...
Azure/azure-sdk-for-python
sdk/identity/azure-identity/tests/test_msal_client.py
Python
mit
1,769
0.001131
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from azure.core.exceptions import ServiceRequestError from azure.identity._internal.msal_client import MsalClient import pytest from helpers import mock, mock_response...
ror, match=message): client.get("https://localhost") assert transport.send.call_count > 1 def test_get_error_response(): first_result = {"error": "first"} first_response = mock_response(401, json_payload=first_result) second_result = {"error": "second"} second_response = mock_respon
se(401, json_payload=second_result) transport = validating_transport( requests=[Request(url="https://localhost")] * 2, responses=[first_response, second_response] ) client = MsalClient(transport=transport) for result in (first_result, second_result): assert not client.get_error_respons...
TheGentlemanOctopus/thegentlemanoctopus
octopus_code/core/octopus/patterns/spiralOutFast.py
Python
gpl-3.0
1,846
0.008667
from pattern import Pattern import copy import numpy as np import random import collections #from scipy.signal import convolve2d import time from collections import deque class SpiralOutFast(Pattern): def __init__(self): self.register_param("r_leak", 0, 3, 1.2) self.register_param("g_leak", 0, 3, ...
elf.r[0] del self.g[0] del self.b[0] domain_r = np.linspace(current_time, current_time - self.r_leak, len(self.pixels)) domain_g = np.linspace(current_time, current_time - self.g_leak, len(self.pixels)) domain_b = np.linspace(current_time, current_time - self.b_leak, ...
g = np.interp(domain_g, self.t, self.g) b = np.interp(domain_b, self.t, self.b) for i in range(len(self.pixels)): self.pixels[i].color = (r[i], g[i], b[i])
octogene/hadaly
hadaly/painter.py
Python
gpl-3.0
3,680
0.00163
# -*- coding: utf-8 -*- import math from kivy.uix.widget import Widget from kivy.graphics import Color, Line from kivy.vector import Vector from kivy.properties import StringProperty, DictProperty, BooleanProperty, BoundedNumericProperty, ListProperty class Painter(Widget): tools = DictProperty({'arrow': {'color...
Color(*self.color, mode='rgba') touch.ud['line'] = Line(points=(touch.x, touch.y), width=self.thickness, cap='round', joint='miter') if self.current_tool == 'arrow': touch.ud['arrowhead'] = Line(width=self.thickness, cap='square', joint='miter') ...
False return super(Painter, self).on_touch_down(touch) def on_touch_move(self, touch): if not self.locked and self.collide_point(*touch.pos): try: if self.current_tool == 'freeline': touch.ud['line'].points += [touch.x, touch.y] else...