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 |
|---|---|---|---|---|---|---|---|---|
lebauce/artub | winshell.py | Python | gpl-2.0 | 12,268 | 0.024617 | """winshell - convenience functions to access Windows shell functionality
Certain aspects of the Windows user interface are grouped by
Microsoft as Shell functions. These include the Desktop, shortcut
icons, special folders (such as My Documents) and a few other things.
These are mostly available via the shell modu... | Initial release by Tim Golden
"""
__VERSION__ = "0.2"
import os, sys
from win32com import storagecon
from win32comext.shell import shell, shellcon
import win32api
import pythoncom
class x_winshell (Exception):
pass
#
# Although this can be done in one call, Win9x didn't
# support it, so I added this worka... | Location (0, folder_id))
def desktop (common=0):
"What folder is equivalent to the current desktop?"
return get_path ((shellcon.CSIDL_DESKTOP, shellcon.CSIDL_COMMON_DESKTOPDIRECTORY)[common])
def common_desktop ():
#
# Only here because already used in code
#
return desktop (common=1)
def application_data (com... |
OmkarPathak/Python-Programs | CompetitiveProgramming/HackerEarth/Algorithms/Searching/P06_RankIt.py | Python | gpl-3.0 | 1,665 | 0.010334 | # You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to
# answer some queries based on the elements of this array. Each query will consist of a single integer x. You ne | ed to
# print the rank based position of this element in this array considering that the array is 1 indexed. The rank
# based position o | f an element in an array is its position in the array when the array has been sorted in ascending order.
#
# Note: It is guaranteed that all the elements in this array are unique and for each x belonging to a query, value ′x′
# shall exist in the array
#
# Input Format
#
# The first line consists of a single integer N ... |
bencebeky/etudes | fibonacci.py | Python | gpl-3.0 | 3,792 | 0.027426 | #!/usr/bin/env python
# Calculate the 1000th element of the Fibonacci series. Fast.
# (Another popular tech interview question.)
import numpy;
# Definition of Fibonacci numbers:
# F(1) = 1
# F(2) = 1
# For n = 3, 4, 5, ...: F(n) = F(n-2) + F(n-1).
# Method one: recursion.
# Very inefficient: F(n) is called once, it ... | cirecursion = lambda n: 1 if n <=2 else fibonaccirecursion(n-2) + fibonaccirecursion(n-1);
# Method two: dual recursion. Returns the list [F(n-1),F(n)].
# Calling it with n triggers one call for each of 2, 3, ..., n-1: that is only O(n) calls | .
def fibonaccidualrecursion(n):
if n >= 3:
a, b = fibonaccidualrecursion(n-1);
# F(n-2) = a, F(n-1) = b, F(n) = a+b.
return b, a+b;
elif n == 2:
return 1, 1;
elif n == 1:
# F(0) = 0.
return 0, 1;
else:
raise NotImplementedError;
# Method three: loop. Nothing fancy.
# Should be much... |
pistacchio/django-extrasettings | extrasettings/apps.py | Python | mit | 1,917 | 0.006781 | import os
import re
import json
import extrasettings
from django.conf import settings
from django.apps import AppConfig
from django.db.utils import OperationalError
from extrasettings.models import Extrasetting
class ExtrasettingsConfig(AppConfig):
name = 'extrasettings'
verbose_name = "Djang... | S_DIR, setting_name + '.json')
try:
schema = json.load(open(filename))
except ValueError:
raise Exception('django-extrasettings: %s.json is not a valid JSON file' % setting_name)
settings_obj, created = Extrasetting.objects.update... | dumps(schema)
})
setattr(extrasettings, setting_name, json.loads(settings_obj.settings))
except OperationalError:
pass
except Exception as ex:
raise ex
|
maxkferg/smart-city-model | birdseye.py | Python | gpl-3.0 | 1,354 | 0.007386 | import cv2
import random
from moviepy.editor import VideoFileClip
#from modules.ssd.main import ImageNetwork
"""
def pipeline_yolo(img):
img_undist, img_lane_augmented, lane_info = lane_process(img)
output = vehicle_detection_yolo(img, img_lane_augmented, lane_info)
return output
def process_image(img):
... | VideoFileClip("examples/project_video.mp4").subclip(30,32)
clip = clip1.fl_image(pipeline_yolo)
clip.write_videofile(video_output, audio=False)
"""
def save_image(image):
"""Save an image to the test directory"""
image = image[:,:,::-1]
frame = random.randint(0,100)
filenam | e = 'test/frames/frame-{0}.png'.format(frame)
cv2.imwrite(filename,image)
return image
def process_video(video_input, video_output):
"""Process a video using the SSD network"""
#with ImageNetwork() as ssd:
clip = VideoFileClip(video_input).subclip(26,31)
#clip = clip.fl_image(ssd.ssd_process_f... |
AstroMatt/esa-time-perception | backend/api_v3/admin.py | Python | mit | 3,822 | 0.002616 | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from import_export.admin import ImportExportModelAdmin
from backend.api_v3.models import Result
class TempoListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar ju... | return queryset.filter(tempo_all__gt=125, tempo_all__lte=200)
if self.value() == 'normal':
return queryset.filter(tempo_all__gte=75, tempo_all__lte=125)
i | f self.value() == 'slow':
return queryset.filter(tempo_all__gte=25, tempo_all__lt=75)
if self.value() == 'too-few':
return queryset.filter(tempo_all__lt=25)
class ValidateAction:
def make_invalid(modeladmin, request, queryset):
queryset.update(status=Result.STATUS_INVALID)... |
secgroup/ctforge | ctforge/utils.py | Python | agpl-3.0 | 4,456 | 0.017729 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# CTForge: Forge your own CTF.
# Copyright (C) 2016-2019 Marco Squarcina
# Copyright (C) 2016-2019 Mauro Tempesta
# Copyright (C) 2016-2019 Lorenzo Veronese
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero ... | = config.get('website', 'log_file', fallback=None),
SECRET_KEY = config.get('website', 'secret_key', fallback='ChengeMeWithRandomStuffASAP'),
BOT_LOG_FILE = config.get('flagbot', 'log_file', fallback=None),
BOT_SCRIPT_PATH = config.get('flagbot', 'bot_script_path', fallback='~/.ctfor... | sys.stderr.write('Malformed configuration file, aborting: {}\n'.format(e))
sys.exit(1)
# expand home
for k in ['LOG_FILE', 'BOT_LOG_FILE', 'BOT_SCRIPT_PATH']:
if conf[k] is not None:
conf[k] = os.path.expanduser(conf[k])
return conf
def flash_errors(form):
"""Handle fo... |
blueyed/coveragepy | coverage/config.py | Python | apache-2.0 | 17,744 | 0.00062 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Config file for coverage.py"""
import collections
import os
import re
from coverage import env
from coverage.backward import configparser, iitems, string_class... |
# The default partial branch regexes, to be modified by the user.
DEFAULT_PARTIAL = [
r'#\s*(pra | gma|PRAGMA)[:\s]?\s*(no|NO)\s*(branch|BRANCH)',
]
# The default partial branch regexes, based on Python semantics.
# These are any Python branching constructs that can't actually execute all
# their branches.
DEFAULT_PARTIAL_ALWAYS = [
'while (True|1|False|0):',
'if (True|1|False|0):',
]
class CoverageConfig... |
miguelinux/vbox | src/VBox/ValidationKit/testmanager/core/webservergluebase.py | Python | gpl-2.0 | 20,134 | 0.014701 | # -*- coding: utf-8 -*-
# $Id: webservergluebase.py $
"""
Test Manager Core - Web Server Abstraction Base Class.
"""
__copyright__ = \
"""
Copyright (C) 2012-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you... | raise WebServerGlueException('Redirection code %d is not supported' % (iCode,));
| self.setHeaderField('Location', sLocation);
self.setHeaderField('Status', '302 Found');
return True;
def _writeWorker(self, sChunkOfHtml):
"""
Worker function which child classes can override.
"""
self.oOutputText.write(sChunkOfHtml);
return True;
d... |
sbfnk/epiwork-website | apps/journal/cms_app.py | Python | agpl-3.0 | 259 | 0.011583 | from cms.app_base import | CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class JournalApphook(CMSApp):
name = _("Journal")
| urls = ["apps.journal.urls"]
apphook_pool.register(JournalApphook)
|
bird-house/threddsclient | tests/test_birdhouse_sample.py | Python | apache-2.0 | 2,985 | 0 | import pytest
from threddsclient import read_xml
def test_birdhouse_root():
xml = """
<catalog xmlns="http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0" xmlns:xlink="http://www.w3.org/1999/xlink" name="THREDDS Server Default Catalog" version="1.0.1"> # noqa
<service name="all" serviceType... | xlink:title="hummingbird" ID="testDatasetScan/hummingbird" name="" />
<catalogRef xlink:href="flyingpigeon/catalog.xml" xlink:title="flyingpigeon" ID="testDatasetScan/flyingpigeon" name="" />
<catalogRef xlink:href="emu/catalog.xm | l" xlink:title="emu" ID="testDatasetScan/emu" name="" />
</dataset>
</catalog>
"""
cat = read_xml(xml, 'http://example.test/catalog.xml')
assert cat.name == "Test all files in a directory"
assert len(cat.datasets) == 1
assert len(cat.references) == 0
assert len(cat.flat_datasets()) == ... |
marekhakala/temperaturehub | Thermometer_DUMMY_server/classes/file_loader.py | Python | apache-2.0 | 957 | 0 | #!/usr/bin/env python3
#
# (C) Copyright 2015 by Marek Hakala <hakala.marek@gmail.com>
# Licensed un | der the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is dist... | under the License.
#
class FileLoader(object):
def __init__(self, filename):
self.filename = filename
def loadFile(self):
self.file = open(self.filename, mode='rb')
self.fileContent = self.file.read()
def closeFile(self):
self.file.close()
def getContent(self):
... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/hplip/ui4/pluginlicensedialog_base.py | Python | gpl-3.0 | 5,171 | 0.003868 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui4/pluginlicensedialog_base.ui'
#
# Created: Mon May 4 14:30:35 2009
# by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setup... | .addWidget(self.page)
self.gridlayout.addWidget(self.StackedWidget, 0, | 0, 1, 5)
self.line_2 = QtGui.QFrame(Dialog)
self.line_2.setFrameShape(QtGui.QFrame.HLine)
self.line_2.setFrameShadow(QtGui.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.gridlayout.addWidget(self.line_2, 1, 0, 1, 5)
spacerItem = QtGui.QSpacerItem(161, 20, QtGui.Q... |
dreamhost/ceilometer | ceilometer/openstack/common/rpc/impl_fake.py | Python | apache-2.0 | 5,641 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
#
# 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/LICEN... | .openstack.common.rpc import common as rpc_common
CONSUMERS = {}
cla | ss RpcContext(rpc_common.CommonRpcContext):
def __init__(self, **kwargs):
super(RpcContext, self).__init__(**kwargs)
self._response = []
self._done = False
def deepcopy(self):
values = self.to_dict()
new_inst = self.__class__(**values)
new_inst._response = self._... |
grevutiu-gabriel/sympy | sympy/printing/tests/test_str.py | Python | bsd-3-clause | 22,751 | 0.003209 | from __future__ import division
from sympy import (Abs, Catalan, cos, Derivative, E, EulerGamma, exp,
factorial, factorial2, Function, GoldenRatio, I, Integer, Integral,
Interval, Lambda, Limit, Matrix, nan, O, oo, pi, Rational, Float, Rel,
S, sin, SparseMatrix, sqrt, summation, Sum, Symbol, symbols, Wild,... | *y) == "-x*y**2 + x"
assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)"
def test_Catalan():
assert str(Catalan) == "Catalan"
def test_ComplexInfinity():
assert str(zoo) == "zoo"
def test_Derivative():
assert str(D... | )) == "Derivative(x**2/y, x, y)"
def test_dict():
assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}"
assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}")
assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}"
def test_Dict():
assert str(Dict({1: 1 + x})) == sstr({1: 1 +... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/django/core/management/templates.py | Python | mit | 14,053 | 0.000356 | import cgi
import errno
import io
import mimetypes
import os
import posixpath
import re
import shutil
import stat
import sys
import tempfile
from os import path
import django
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.core.management.utils import hand... | g: utf-8 -*-\n'
'from __future__ import unicode_literals\n\n',
}), autoescape=False)
# Setup a stub settings environment for template rendering
if not settings.configured:
settings.configure()
django.setup()
tem... | te(options['template'],
base_subdir)
prefix_length = len(template_dir) + 1
for root, dirs, files in os.walk(template_dir):
path_rest = root[prefix_length:]
relative_dir = path_rest.replace(base_name, name)
if relative_dir:... |
Abhin33t/ann_minor | Neural_Network_Eval1.py | Python | gpl-2.0 | 2,898 | 0.003796 | __author__ = 'Abhineet Saxena'
"""
Neural Net Classification and Evaluation Trial
"""
# The imports:
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
# from pybrain.structure.modules import SoftmaxLayer
from pybrain.structure import FeedForwardNetwork
from pybra... | port random as rnd
def roundOff(xvar): |
"""
Returns the rounded value to signify the meaning of the output of the Neural Network.
:param xvar:
:return:
"""
if xvar <= 0.5:
return 0
else:
return 1
# # Here we instantiate a Feed-Forward Network.
# annet = FeedForwardNetwork()
#
# # Creation of the input layer: Here ... |
geopython/QGIS | python/plugins/processing/algs/saga/SagaAlgorithmProvider.py | Python | gpl-2.0 | 6,154 | 0.001625 | # -*- coding: utf-8 -*-
"""
****************************************************** | *********************
SagaAlgorithmProvider.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* ... | erms 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. *
* *
**********************************... |
XLSForm/pyxform | tests/test_file.py | Python | bsd-2-clause | 622 | 0 | # -*- coding: utf-8 -*-
"""
Test file question type.
"""
from tests.pyxform_test_case import PyxformTestCase
class FileWidgetTest(PyxformTestCase):
"""
Test file widget class.
"""
def test_file_type(self):
"""
Test file question type.
"""
self.assertPyxformXform(
... | ,
md="""
| survey | | | | |
| | type | name | label |
| | file | file | Attach a file |
""",
xml__contains=['<upload mediatype="application/*"'],
)
|
mpatacchiola/naogui | zpgc_2016c/include/pynaoqi-python2.7-2.1.3.3-linux64/allog.py | Python | mit | 2,493 | 0.020858 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import ... | uteError( | "You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if metho... |
fiete201/qutebrowser | qutebrowser/config/configcache.py | Python | gpl-3.0 | 1,820 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2018-2021 Jay Kamat <jaygkamat@gmail.com>
#
# This file is part of qutebrowser.
#
# qutebrowser 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, e... | ld have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""Implementation of a basic config cache."""
from typing import Any, Dict
from qutebrowser.config import config
class ConfigCache:
"""A 'high-performance' cache for the config sy... | to the config system very frequently, DO
NOT modify the value returned, DO NOT require per-url settings, and do not
require partially 'expanded' config paths.
If any of these requirements are broken, you will get incorrect or slow
behavior.
"""
def __init__(self) -> None:
self._cache:... |
Smelly-London/datavisualisation | python_utils/sqlite_utilities.py | Python | apache-2.0 | 2,385 | 0.010901 | #!/usr/bin/env python3
# This script connects to and performs queries on an SQLite database using Python.
# Jen Thomas, Oct 2016.
#########################################################
import sqlite3
import shutil
def connect_to_sqlite_db(sqlite_file):
""" Connect to an SQLite database. Return a connection... | mn_names):
"""Perform an SQL command to get data from an SQL database. Return data in a list of dictionaries with column headers as keys and their associated values."""
print(sql)
sql = sql.replace('{column_names}', ",".join(column_names))
cur.execute(sql)
all_rows = cur.fetchall()
data = []
... | r column_name in column_names:
d[column_name] = row[i]
i=i+1
data.append(d)
return data
def get_data(conn, cur, sql):
'''Get data from a database using the connection and cursor and defined sql.Output the data in a python list.'''
cur.execute(sql)
all_rows = cur.f... |
execunix/vinos | xsrc/external/mit/MesaLib/dist/src/gallium/docs/source/exts/formatting.py | Python | apache-2.0 | 1,120 | 0.004464 | # formatting.py
# Sphinx extension providing formatting for Gallium-specific data
# (c) Corbin Simpson 2010
# Public domain to the extent permitted; contact author for special licensing
import docutils.nodes
import sphinx.addnodes
def parse_envvar(env, sig, signode):
envvar, t, default = sig.split(" ", 2)
env... | e.strip().upper()
desc = " (%s)" % desc.strip()
signode += sphinx.addnodes.desc_name(opcode, opcode)
signode += sphinx.ad | dnodes.desc_annotation(desc, desc)
return opcode
def setup(app):
app.add_description_unit("envvar", "envvar", "%s (environment variable)",
parse_envvar)
app.add_description_unit("opcode", "opcode", "%s (TGSI opcode)",
parse_opcode)
|
luboslenco/cyclesgame | blender/arm/props.py | Python | lgpl-3.0 | 27,293 | 0.006961 | import bpy
from bpy.props import *
import os
import shutil
import arm.props_ui as props_ui
import arm.assets as assets
import arm.log as log
import arm.utils
import arm.make
import arm.props_renderpath as props_renderpath
import arm.proxy
import arm.nodes_logic
# Armory version
arm_version = '2019.6'
arm_commit = '$Id... | ", update=assets.invalidate_compiler_cache)
bpy.types.World.arm_project_version = StringProperty(name="Version", description="Exported project version", default="1.0", update=assets.invalidate_compiler_cache)
bpy.types.World.arm_project_bundle = StringProperty(name="Bundle", description="Exported project bundle... | t icon, must be a PNG image", default="", subtype="FILE_PATH", update=assets.invalidate_compiler_cache)
bpy.types.World.arm_project_root = StringProperty(name="Root", description="Set root folder for linked assets", default="", subtype="DIR_PATH", update=assets.invalidate_compiler_cache)
bpy.types.World.arm_phy... |
msmbuilder/msmbuilder | msmbuilder/tests/test_ghmm.py | Python | lgpl-2.1 | 6,280 | 0 | from __future__ import print_function, division
import warnings
from itertools import permutations
import hmmlearn.hmm
import numpy as np
import pickle
import tempfile
from sklearn.pipeline import Pipeline
from msmbuilder.example_datasets import AlanineDipeptide
from msmbuilder.featurizer import SuperposeFeaturizer... | True
for i in range(numStates):
if abs(means[i] - model.means_[order[i]]) > valuetol:
match = False
break
if abs(vars[i] - model.vars_[order[i]]) > valuetol:
match = False
break
for j in range(numStates):
... | r[j]]
if abs(diff) > transmattol:
match = False
break
if match:
# It matches.
return
# No permutation matched.
assert False
def test_2_state():
transmat = np.array([[0.7, 0.3], [0.4, 0.6]])
means = np.array([[0.0]... |
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Plugins/Extensions/MediaPortal/additions/porn/wicked.py | Python | gpl-2.0 | 10,807 | 0.027672 | # -*- coding: utf-8 -*-
###############################################################################################
#
# MediaPortal for Dreambox OS
#
# Coded by MediaPortal Team (c) 2013-2017
#
# This plugin is open source but it is NOT free software.
#
# This plugin may only be distributed to and executed... | enes
self.filmliste.append((decodeHtml(Title), Url, Image))
if len(self.filmliste) == 0:
self.filmliste.append((_('No pornstars found!'), None, None))
self.ml.setList(map(self._defaultlistleft, self.filmliste))
self.ml.moveToIndex(0)
self.keyLocked = False
self.th_ThumbsQuery(self.filmliste, 0, 1, 2, N... | s()
def showInfos(self):
title = self['liste'].getCurrent()[0][0]
pic = self['liste'].getCurrent()[0][2]
self['name'].setText(title)
CoverHelper(self['coverArt']).getCover(pic)
def keyOK(self):
if self.keyLocked:
return
Link = self['liste'].getCurrent()[0][1]
if Link:
rangelist = [['Scenes', 'vi... |
TheTimmy/spack | var/spack/repos/builtin/packages/transset/package.py | Python | lgpl-2.1 | 1,723 | 0.00058 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be ... | terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
########################... |
iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert_gui/models/connectors/init/init_history_length.py | Python | gpl-3.0 | 977 | 0.002047 | from ert_gui.models.ert_connector import ErtConnector
from ert_gui.models.mixins import SpinnerModelMixin
class HistoryLengthModel(ErtConnector, SpinnerModelMixin):
def __init__(self):
self.__value = self.getMaxValue()
super(HistoryLengthModel, self).__init__()
#todo: notify when the his... | elf):
self.setSpinnerValue(self.getMaxValue())
def setToMin(self):
self.setSpinnerValue(self.getMinValue())
def getHistoryLength(self):
""" @rtype: int """
return self.ert(). | getHistoryLength()
|
n3wb13/OpenNfrGui-5.0-1 | lib/python/Plugins/Extensions/bmediacenter/src/MC_AudioPlayer.py | Python | gpl-2.0 | 56,958 | 0.032182 | from enigma import eTimer, iServiceInformation, iPlayableService, ePicLoad, RT_VALIGN_CENTER, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, gFont, eListbox, ePoint, eListboxPythonMultiContent, eServiceCenter, getDesktop
from Components.MenuList import MenuList
from Screens.Screen import Screen
from Screens.Service... | t ScrollLabel
from Components.Sources.List import List
from Screens.MessageBox import MessageBox
from Screens.HelpMenu impo | rt HelpableScreen
from twisted.internet import reactor, defer
from twisted.web import client
from twisted.web.client import HTTPClientFactory, downloadPage
from Components.ServiceEventTracker import ServiceEventTracker
from Components.Playlist import PlaylistIOInternal, PlaylistIOM3U, PlaylistIOPLS
from Components.Conf... |
njvack/ge-mri-rtafni | upload-host/vendor/dicom/util/dump.py | Python | mit | 3,417 | 0.001171 | # dump.py
"""Utility functions used in debugging writing and reading"""
# Copyright (c) 2008-2012 Darcy Mason
# This file is part of pydicom, relased under an MIT license.
# See the file license.txt included with this distribution, also
# available at http://pydicom.googlecode.com
from __future__ import print_fu... | % x for x in row]) # string of two digit hex bytes
str_out.wri | te(byte_string)
str_out.write(blanks[:byteslen - len(byte_string)]) # if not 16, pad
str_out.write(' ')
str_out.write(''.join([print_character(x) for x in row])) # character rep of bytes
str_out.write("\n")
return str_out.getvalue()
def pretty_print(ds, indent=0, indent_chars="... |
CiuffysHub/MITMf | mitmflib-0.18.4/mitmflib/dnslib/label.py | Python | gpl-3.0 | 8,406 | 0.007257 | # -*- coding: utf-8 -*-
"""
DNSLabel/DNSBuffer - DNS label handling & encoding/decoding
"""
from __future__ import print_function
import fnmatch
from mitmflib.dnslib.bit import get_bits,set_bits
from mitmflib.dnslib.buffer import Buffer, BufferError
class DNSLabelError(Exception):
pass
class DNSLabel(obje... | 253:
raise DNSLabelError("Domain label too long: %r" % name)
| name = list(name.label)
while name:
element = name.pop(0)
if len(element) > 63:
raise DN |
MihaiBalint/birdseye-server | test-data/species-import.py | Python | mit | 2,428 | 0.000824 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gevent.monkey; gevent.monkey.patch_all()
import gevent
import csv
import requests
import sys
def post_species(scientific, common, labels):
resp = requests.post('https://birdseye.space/v1/species', json={
'names': {
'scientific': scientific.l... | )
assert resp.status_code in (200, 201), 'Unexpected code: {}.'.format(
resp.status_code)
def main(filename):
print('Importing {}'.format(filename))
group_singular = {
| 'conifers': [
'conifer', 'plant', 'land plant', 'botany'],
'reptiles': [
'reptile', 'animal', 'cold blood', 'cold bloded', 'vertebrate',
'fauna'],
'turtles (non-marine)': [
'turtle', 'animal', 'non-marine', 'cold blood', 'cold bloded',
'... |
Aloomaio/googleads-python-lib | examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py | Python | apache-2.0 | 1,972 | 0.007099 | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | in(client):
# Initialize appropriate service.
custom_field_service = client.GetService(
'CustomFieldService', version='v201808')
# Create a statement to select custom fields.
statement = (ad_manager.StatementBuilder(version='v201808')
| .Where('entityType = :entityType')
.WithBindVariable('entityType', 'LINE_ITEM'))
# Retrieve a small amount of custom fields at a time, paging
# through until all custom fields have been retrieved.
while True:
response = custom_field_service.getCustomFieldsByStatement(
stat... |
unomena/suds | suds/client.py | Python | lgpl-3.0 | 25,982 | 0.002386 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... | lassmethod
def items(cls, sobject):
"""
Extract the I{items} from a suds object much like the
items() method works on I{dict}.
@param sobject: A suds obj | ect
@type sobject: L{Object}
@return: A list of items contained in I{sobject}.
@rtype: [(key, value),...]
"""
return sudsobject.items(sobject)
@classmethod
def dict(cls, sobject):
"""
Convert a sudsobject into a dictionary.
@param sobject: A s... |
wagnerand/zamboni | apps/reviews/models.py | Python | bsd-3-clause | 8,152 | 0.000245 | from datetime import datetime, timedelta
import logging
from django.conf import settings
from django.core.cache import cache
from django.db import models
import bleach
from celeryutils import task
from tower import ugettext_lazy as _
import amo.models
from amo.helpers import shared_url
from translations.fields impor... | objects = ReviewManager()
class Meta:
db_table = 'reviews'
ordering = ('-created',) |
def get_url_path(self):
if 'mkt.ratings' in settings.INSTALLED_APPS:
return '/app/%s/ratings/%s' % (self.addon.app_slug, self.id)
return shared_url('reviews.detail', self.addon, self.id)
def flush_urls(self):
urls = ['*/addon/%d/' % self.addon_id,
'*/addon/... |
cjgrady/irksome-broccoli | extras/surfaceGenerator.py | Python | gpl-2.0 | 4,244 | 0.027804 | """
@summary: This script will generate a surface using cones and ellipsoids
@author: CJ Grady
"""
from math import sqrt
import numpy as np
from random import randint
# .............................................................................
class SurfaceGenerator(object):
"""
@summary: This class is used t... | #s = SurfaceGe | nerator(1000, 1000, 0, 0, 0.05, defVal=0)
s = SurfaceGenerator(20, 20, 0, 0, 1.0, defVal=0)
#s.addEllipsoid(5, 5, 4, 3, 10)
#s.addEllipsoid(7, 7, 2, 5, 10)
#s.addCone(14, 14, 5, 20)
#s.writeGrid('/home/cjgrady/testSurface.asc')
s.addRandom(numCones=10, numEllipsoids=10, maxHeight=10, maxRad=10)
#s.... |
Darthkpo/xtt | openpyxl/writer/tests/test_dump.py | Python | mit | 8,954 | 0.00134 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
import datetime
import decimal
from io import BytesIO
from openpyxl.xml.functions import tostring, xmlfile
from openpyxl.utils.indexed_list import IndexedList
from openpyxl.utils.datetime import CALENDAR_WINDOWS_1900
from openpyxl.styles im... | assert diff is None, diff
@pytest.mark.parametrize("row", ("string", dict()))
def test_invalid_append(DumpWorksheet, row):
ws = DumpWorksheet
with pytest.raises(TypeError):
ws.append(row)
@pytest.mark.lxml_required
def test_cell_comment(DumpW | orksheet):
ws = DumpWorksheet
from openpyxl.comments import Comment
from .. dump_worksheet import WriteOnlyCell
cell = WriteOnlyCell(ws, 1)
comment = Comment('hello', 'me')
cell.comment = comment
ws.append([cell])
assert ws._comments == [comment]
ws.close()
with open(ws.filename... |
streety/Home | app/jinja_filters.py | Python | mit | 429 | 0 | import re
from jinja2 import Markup, escape, evalcontextfilter
from app import app
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@ | app.template_filter('nl2br')
@evalcontextfilter
def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
for p in _paragra | ph_re.split(escape(value)))
if eval_ctx.autoescape:
result = Markup(result)
return result
|
adam2392/clinicaltrials | populatedb.py | Python | apache-2.0 | 574 | 0.015679 | # Run t | his in the Django shell
from clinicalsearch.models import ClinicalTrial
import csv
with open('clinicalsearch/trials_ranked.csv', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print row
t = ClinicalTrial(id=row[0], sponsor=row[1], published=(row[2]=="TRUE"), state=row[3], url=r... | st_changed=row[10], min_age=int(row[11]), max_age=int(row[12]), genders=row[13], health=(row[14] == "True"), ranking=int(row[15]))
t.save() |
Akakiis/pythonintask | IVTa/2014/SHCHUKIN_F_O/task_2_30.py | Python | apache-2.0 | 1,344 | 0.002134 | # Задача 1. Вариант 30.
'''
Напишите программу, которая будет выводить на экран
наиболее понравившееся вам высказывание, автором кото | рого
является Али ибн Абу Талиб. Не забудьте о том, что автор
должен бы | ть упомянут на отдельной строке.
'''
# SHCHUKIN F. O.
# 24.02.2016
from sys import stdout as c
from time import sleep
quote = dict(
text='Самое большое богатство - разум.\nСамое большое наследство \
- воспитанность.\nСамая большая нищета - невежество.\n\
(Нет лучшего богатства, чем мудрость;\nнет страшнее нищеты,... |
crs4/orchestrator | dispatcher/components/api.py | Python | gpl-2.0 | 1,535 | 0 | # -*- coding:utf-8 -*-
# Copyright 2014 CRS4
# All Rights Reserved.
#
# Licensed under the GNU General Public License, version 2 (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.gnu.org/licenses/gpl-2.0.html
#
... | ted 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.
"""
.. include:: isonum.txt
:copyright: |copy| 2014 by CRS4.
:license: gpl-2, see License for more details.
Description
~~~~~~~~~~~
Base file where parent routines are defined and from where
these wi... |
skylerberg/third-party-ci-tools | monitoring/ciwatch/ciwatch/cache.py | Python | apache-2.0 | 1,165 | 0 | # | Copyright (c) 2015 Tintri. 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 appli... | riting, 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.
from functools import wraps
from flask impo... |
reillysiemens/curriculum | source/conf.py | Python | apache-2.0 | 8,585 | 0.007105 | # -*- coding: utf-8 -*-
#
# OSU DevOps Bootcamp documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 15 12:20:17 2013.
#
# 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 f... | cellaneous'),
]
# Documents to append a | s an appendix to all manuals.
#texinfo_appendices = []
# If false, no module |
samdroid-apps/sugar | src/jarabe/__init__.py | Python | gpl-2.0 | 1,029 | 0 | """OLPC Sugar Graphical "Shell" Interface
Provides the shell-level operations for managing
the OLPC laptop computers. It interacts heavily
with (and depends upon) the Sugar UI libraries.
This is a "graphical" shell, the name does not
refer to a command-line "shell" interface.
"""
# Copyright (C) 2006-2007, Red Hat,... | it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 | of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have... |
uw-it-aca/mdot-developers | setup.py | Python | apache-2.0 | 1,212 | 0.0033 | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).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='mdotdevs',
version='0.1',
packages=['mdotdevs'],
inclu... | or='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License', # example license
'Operating System :: OS Independent',
... | guage :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
rennancockles/gigapy | View/VisualizarTransportadoraView.py | Python | mit | 3,770 | 0.002918 | # -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text... | ra(object):
def setupUi(self, VisualizarTransportadora):
VisualizarTransportadora.setObjectName(_fromUtf8("VisualizarTransportadora"))
VisualizarTransportadora.resize(403, 300)
VisualizarTransportadora.move(550, 250)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8... | adora)
self.tblTransportadora.setGeometry(QtCore.QRect(0, 0, 401, 300))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tblTransportadora.siz... |
gunan/tensorflow | tensorflow/python/keras/engine/training_dataset_test.py | Python | apache-2.0 | 21,265 | 0.003997 | # Copyright 2018 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... | .python.data.ops import dataset_ops
from tensorflow.python.framework import ops
from tensorflow.python.keras import callbacks
from tensorflow.python.keras import keras_par | ameterized
from tensorflow.python.keras import metrics as metrics_module
from tensorflow.python.keras import testing_utils
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
class BatchCounterCallback(callbacks.Callback):... |
erudit/zenon | eruditorg/erudit/migrations/0066_issue_force_free_access.py | Python | gpl-3.0 | 505 | 0.001984 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-20 22:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
d | ependencies = [
('erudit', '0065_auto_20170202_1152'),
]
operations = [
migrations.AddField(
model_name='issue',
name='force_free_access',
field=models.BooleanField(default=False, verbose_name='Contraindre en libre accès'),
),
| ]
|
fabiencro/knmt | nmt_chainer/dataprocessing/aligned_parse_reader.py | Python | gpl-3.0 | 2,892 | 0.00242 | #!/usr/bin/env python
"""aligned_parse_reader.py: read parsed and aligned files"""
__author__ = "Fabien Cromieres"
__license__ = "undecided"
__version__ = "1.0"
__email__ = "fabien.cromieres@gmail.com"
__status__ = "Development"
from __future__ import absolute_import, division, print_function, unicode_literals
import... | ment.append((left, right))
return id_, score, alignment
def load_aligned_corpus(src_fn, tgt_fn, align_fn, skip_empty_align=True, invert_alignment_links=False):
src = io.open(src_fn, 'rt', encoding="utf8")
tgt = io.open(tgt_fn, 'rt', encoding="utf8")
align_f = io.open(align_fn, 'rt', encoding="utf8")
... | _parse_info_from_file_object(tgt)
id_align, score_align, alignment = read_one_align_info_from_file_object(
align_f)
except exceptions.EOFError:
return
if skip_empty_align and len(alignment) == 0:
log.warn("skipping empty alignment %i %s" % (num_sentenc... |
sethbrin/QM | version2/python/calculate_energy_new_coords_general.py | Python | mit | 32,462 | 0.011306 | import os,sys
from trans_rot_coords import *
import numpy as np
from read_energy_force_new import *
from grids_structures_general import DS,Grid_Quarts
from orient_struct_2 import OrientDS as OrientDS_2
from orient_struct_3 import OrientDS as OrientDS_3
AU2KCAL = 23.0605*27.2116
R2D = 180.0/3.14159265358979
## np.pi/... | self.OperateNdx.append(2)
self.Operation.append([ax, ang])
self.IsOriented = True
self._spherical_x()
def ReorientToOldVec(self):
ax, ang = self.Operation[self.OperateNdx.index(2)]
self.force = rotate(self.force, ax, -1*ang)
sel | f.torque = rotate(self.torque, ax, -1*ang)
ax, ang = self.Operation[self.OperateNdx.index(1)]
self.force = rotate(self.force, ax, -1*ang)
self.torque = rotate(self.torque, ax, -1*ang)
def _spherical_x(self):
"""
Calculate the coords in spherical coordination system for molec... |
EdisonAlgorithms/ProjectEuler | vol4/197.py | Python | mit | 265 | 0.007547 | # import matplotlib.pyplot as plt
def u(n):
| f = lambda x: int(2 ** (30.403243784 - x * x)) * 1e-9
return -1 if n == 0 else f(u(n - 1))
if __name__ == "__main__":
i = 0
| while abs(u(i + 2) - u(i)) > 1e-10:
i += 101
print u(i) + u(i + 1)
|
funkyfuture/cerberus | cerberus/tests/__init__.py | Python | isc | 4,450 | 0.001124 | import re
import pytest
from cerberus import errors, Validator, SchemaError
from cerberus.base import DocumentError
from cerberus.tests.conftest import sample_schema
def assert_exception(exception, document={}, schema=None, validator=None, msg=None):
"""
Tests whether a specific exception is raised. Optiona... | False):
"""Tests whether a validation succeeds."""
if validator is None:
validator = Validator(sample_schema)
result = validator(document, schema, update)
assert isinstance(result, bool)
if not result:
raise AssertionError(validator.errors)
def assert_has_error(_errors, d_path, s_p... | ce(info, tuple):
info = (info,)
assert isinstance(_errors, errors.ErrorList)
for i, error in enumerate(_errors):
assert isinstance(error, errors.ValidationError)
try:
assert error.document_path == d_path
assert error.schema_path == s_path
assert erro... |
MuriloFerraz/Intel-Edison-Webcam-Bot-Telegram | msg_sender.py | Python | gpl-3.0 | 199 | 0.005025 | #!/usr/bin/python
import telepot
TOKEN = 'sua | chave'
bot = telepot.Bot(TOKEN)
mensagem = 'Esta eh uma mensagem enviada \n automaticament | e por: \n Intel Edison'
bot.sendMessage(111111111, mensagem)
|
jonludlam/planex | planex/build.py | Python | lgpl-2.1 | 9,798 | 0.00347 | #!/usr/bin/env python
# Build a bunch of SRPMs
import argparse
import getopt
import sys
import os
import glob
import subprocess
import shutil
import rpm
import hashlib
import time
from planex.globals import (BUILD_ROOT_DIR, SRPMS_DIR, RPMS_DIR, BUILD_DIR,
SPECS_GLOB)
from planex.util imp... | _items_in_deps = reduce(set.union,
data.itervalues()) - set(data.iterkeys())
# Add empty dependences where needed
extra = {}
| for item in extra_items_in_deps:
extra[item] = set()
data.update(extra)
result = []
while True:
ordered = set(item for item, dep in data.iteritems() if not dep)
if not ordered:
break
result.append(ordered)
newdata = {}
for item, dep in data.iterit... |
chainsawriot/cy_learn | scap.py | Python | mit | 3,345 | 0.008072 | # -*- coding: utf-8 -*-
### Quick and dirty script to pull data from mep.gov.cn
### Answer to this question: https://www.facebook.com/groups/hkrusers/permalink/793249694038527
from bs4 import BeautifulSoup
import urllib2
import csv
import re
#import iconv_codecs
indexpage = "http://www.ceo.gov.hk/chi/press/press2012.... | serial'] = alltd[0].get_text()
# res['city'] = alltd[1].get_text()
# res['date'] = alltd[2].get_text()
# res['pollIndex'] = alltd[3].get_text()
# res['major'] = alltd[4].get_text()
# res['pollClass'] = alltd[5].get_text()
# res['pollCondition'] = alltd[6].get | _text()
# return res
# extracted_data = [extractTr(tr) for tr in alltr if checkGoodtr(tr)]
# def export_csv(extracted_data, csvfilename):
# keys = extracted_data[0].keys()
# f = open(csvfilename, "wb")
# csvwriter = csv.writer(f)
# csvwriter.writerow(keys)
# for row in extracted_data:
# ... |
rspavel/spack | var/spack/repos/builtin/packages/py-junit-xml/package.py | Python | lgpl-2.1 | 688 | 0.00436 | # Copyright 2013-2020 Lawrence | Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyJunitXml(PythonPackage):
"""Creates JUnit XML test result documents that can be read by tools
such as Jenkins"""
... | = "https://pypi.io/packages/source/j/junit-xml/junit-xml-1.7.tar.gz"
version('1.7', sha256='5bc851b53e3e2153dcc62278ce2aa796a8ae9208f1dec36d1507b5af445ce355')
depends_on('py-setuptools', type='build')
depends_on('py-six', type=('build', 'run'))
|
chapel-lang/pychapel | docs/source/examples/test_inline_arbitrary_chapel.py | Python | apache-2.0 | 1,131 | 0.004421 | from pych.extern import Chapel
import os.path
currentloc = os.path.dirname(os.path.realpath(__file__))
# Don't have a way to specify where the Chapel module arbitraryfile would live
# The intention seems to be the addition of an argument lib to @Chapel
@Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')... | use arbitraryfile;
writeln(foo(1, 2));
// Should be 6
writeln(bar());
// Should be: 14 14 3 14 14
// 14 14 3 14 14
writeln(baz());
// Should be: (contents = 3 | .0)
// (contents = 3.0)
"""
return None
if __name__ == "__main__":
useArbitrary()
import testcase
# contains the general testing method, which allows us to gather output
def test_using_other_chapel_code():
"""
ensures that an inline definition of a Chapel function with a use statement
wil... |
cysuncn/python | study/test/Test-9-1.py | Python | gpl-3.0 | 2,116 | 0.000945 | import pygame, sys
def lineleft():
plotpoints = []
for x in range(0, 640):
y = -5 * x + 1000
plotpoints.append([x, y])
pygame.draw.lines(screen, [0, 0, 0], False, plotpoints, 5)
pygame.display.flip()
def lineright():
plotpoints = []
for x in range(0, 640):
y = 5 * x -... | e.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
looper = looper - 50
if looper < -132:
| looper = 480
if event.key == pygame.K_DOWN:
looper = looper + 50
if looper > 480:
looper = -132
loadtext(310, looper)
screen.fill([255, 255, 255])
loadtext(310, looper)
l... |
adamhaney/airflow | airflow/operators/bash_operator.py | Python | apache-2.0 | 5,565 | 0.000539 | # -*- coding: utf-8 -*-
#
# 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
#... | ow_context_vars.items()]))
self.env.update(airflow_context_vars)
self.lineage_data = self.bash_command
with TemporaryDirectory(prefix='airflowtmp') as tmp_dir:
with NamedTemporaryFile(dir=tmp_dir, prefix=self.task_id) as tmp_file:
tmp_file.write(bytes(self.bash_comm... | , script_location)
def pre_exec():
# Restore default signal disposition and invoke setsid
for sig in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
if hasattr(signal, sig):
signal.signal(getattr(signal, sig), signal.SIG_DFL)... |
zstars/weblabdeusto | server/src/weblab/db/upgrade/regular/versions/3fab9480c190_professor_instructor.py | Python | bsd-2-clause | 681 | 0.016153 | """pro | fessor => instructor
Revision ID: 3fab9480c190
Revises: 31ded1f6ad6
Create Date: 2014-02-17 00:56:12.566690
"""
# revision identifiers, used by Alembic.
revision = '3fab9480c190'
down_revision = '31ded1f6ad6'
from alembic import op
import sqlalchemy as sa
metadata = sa.MetaData()
role = sa.Table('Role', metadata,
... | (role.c.name == 'professor').values(name = 'instructor')
op.execute(update_stmt)
def downgrade():
update_stmt = role.update().where(role.c.name == 'instructor').values(name = 'professor')
op.execute(update_stmt)
|
kleinfeld/medpy | medpy/features/__init__.py | Python | gpl-3.0 | 1,324 | 0.008308 | """
@package medpy.features
Functionality to extract features from images and present/manipulate them.
Packages:
- histogram: Functions to create and manipulate (fuzzy) histograms.
- intensity: Functions to extracts voxel-wis | e intensity based features from (medical) images.
- texture: Run-time optimised features extraction on images. (experimental)
- utilities: Utilities for feature handling. C | urrently only for features from the @see medpy.features.intensity package.
"""
# determines the modules that should be imported when "from metric import *" is used
__all__ = []
# if __all__ is not set, only the following, explicit import statements are executed
from histogram import fuzzy_histogram, triangular_member... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/packet_capture.py | Python | mit | 2,633 | 0.002279 | # 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 ... | 'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'},
}
def __init__(self, target, storage_location, bytes_to_capture_per_packet=0, tot | al_bytes_per_session=1073741824, time_limit_in_seconds=18000, filters=None):
super(PacketCapture, self).__init__()
self.target = target
self.bytes_to_capture_per_packet = bytes_to_capture_per_packet
self.total_bytes_per_session = total_bytes_per_session
self.time_limit_in_seconds... |
siosio/intellij-community | python/testData/refactoring/move/fromImportAliases/before/src/lib.py | Python | apache-2.0 | 54 | 0 | def function1():
pass
|
def funct | ion2():
pass
|
rylans/typeguess | setup.py | Python | apache-2.0 | 932 | 0.002146 | #!/usr/bin/env python
from codecs impo | rt open
from setuptools im | port setup, find_packages
def read(f):
return open(f, encoding='utf-8').read()
setup(name='typeguess',
version='0.0.2',
description='Data type guesser',
long_description=read('README.rst'),
author='Rylan Santinon',
author_email='rylans@gmail.com',
url='https://github.com/rylans... |
702nADOS/sumo | tools/turn-defs/turndefinitions.py | Python | gpl-3.0 | 12,375 | 0.000404 | # -*- coding: utf-8 | -*-
"""
@file turndefinitions.py
@author Karol Stosiek
@author Michael Behrisch
@date 2011-10-26
@version $Id: turndefinitions.py 22608 2017- | 01-17 06:28:54Z behrisch $
Operations and classes necessary to work on SUMO turn definitions.
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2011-2017 DLR (http://www.dlr.de/) and contributors
This file is part of SUMO.
SUMO is free software; you can redistribute it and/or modify
it under ... |
miguelgrinberg/slam | slam/cli.py | Python | mit | 28,330 | 0 | from __future__ import print_function
from datetime import datetime
import inspect
import json
import logging
import os
try:
import pkg_resources
except ImportError: # pragma: no cover
pkg_resources = None
import random
import re
import subprocess
import shutil
import string
import sys
import time
import bot... | e_file) as f:
template = f.read()
template = render_template(template, name=name, description=description,
module=module, app=app, bucket=bucket,
timeout=timeout, memory=memory,
| requirements=requirements, stages=stages,
devstage=stages[0], runtime=runtime)
with open(config_file, 'wt') as f:
f.write(template)
# plugins
config = _load_config(config_file)
for name, plugin in plugins.items():
# write plugin documentation as a ... |
justinbois/bebi103_utils | legacy/bebi103.py | Python | mit | 61,231 | 0.000294 | """
Utilities for Caltech BE/Bi 103.
Author: Justin Bois
"""
import collections
import random
import warnings
import numbers
import matplotlib.path as path
import numpy as np
import pandas as pd
import scipy.odr
import scipy.stats as st
import statsmodels.tools.numdiff as smnd
import skimage.io
import skimage.measu... | outside of range')
elif x == x_range[1]:
return rgb_frac_to_hex(palette[-1])
# Fractional position of x in x_range
f = (x - x_range[0]) / (x_range[1] - x_range[0])
return rgb_frac_to_hex(palette[int(f * len(palette))])
def im_merge_cmy(im_cyan, im_magenta, im_yellow=None):
"""
Merge... | make RGB image that has cyan, magenta, and
yellow.
Parameters
----------
im_cyan: array_like
Image represented in cyan channel. Must be same shape
as `im_magenta` and `im_yellow`.
im_magenta: array_like
Image represented in magenta channel. Must be same shape
as `... |
neiljdo/readysaster-icannhas-web | readysaster-icannhas-web/hazard/utils.py | Python | bsd-3-clause | 2,477 | 0.001211 | import json
import urllib
import urllib2
from django.core.files import File
from django.conf import settings
from django.contrib.gis.geos import Point
from .models import FloodMap, ReturnPeriod
|
def get_geoserver_baseurl():
'''
Just input the layer name, height, width and boundarybox
'''
url = settings.NOAH_GEOSERVER_URL + '?'
url += urllib.urlencode({
'request': 'GetMap',
'service': 'WMS',
'versio | n': '1.1.1',
'srs': 'EPSG:4326',
'format': 'kml',
})
return url
def get_floodmap_kml_file(layers, bbox, height=720, width=330, styles=''):
url = get_geoserver_baseurl() + '&' + urllib.urlencode({
'layers': layers,
'styles': styles,
'height': height,
'width':... |
AssembleSoftware/IoTPy | examples/distributed_examples/example_2_subscriber.py | Python | bsd-3-clause | 2,279 | 0.00351 | """
This module is used with VM_publisher_test.py to test
APMQ/pika. Execute
python VM_publisher_test.py
in one shell and
execute
python VM_publisher_test.py
in another shell.
The publisher publishes p*1, p*2, p*3, ... , p*num_steps on a stream
with global name 'sequence'. Currently num_steps is set to 10 and p ... | ames= | ['out'],
connect_sources=[],
name='process_3')
def compute_3(in_streams, out_streams):
stream_to_file(
in_streams[0], 'result.dat')
proc_3 = distributed_process(
compute_func=compute_3,
in_stream_names=['in'],
out_stream_names=[],... |
cloudkick/libcloud | libcloud/compute/deployment.py | Python | apache-2.0 | 3,855 | 0.002335 | # 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 use ... | oyment to the others already in this object.
"""
if add is not None:
add = add if isinstance(add, (list, tuple)) else [add]
self.steps.extend(add)
def run(self, node, client):
"""
Run each deployment that has been added.
See also L{Deployment.run}
... | node = s.run(node, client)
return node
|
metacloud/python-openstackclient | openstackclient/identity/v3/endpoint.py | Python | apache-2.0 | 8,024 | 0 | # Copyright 2012-2013 OpenStack Foundation
#
# 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 la... | parsed_args.service)
endpoint = identity_client.endpoints.create(
service.id,
| parsed_args.url,
parsed_args.interface,
parsed_args.region,
parsed_args.enabled
)
info = {}
info.update(endpoint._info)
info['service_name'] = service.name
info['service_type'] = service.type
return zip(*sorted(six.iteritems... |
amarandon/django-audiotracks | audiotracks/urls.py | Python | mit | 955 | 0 | from django.conf.urls import url
from audiotracks import feeds
from audiotracks import views
urlpatterns = [
url(r"^$", views.index, name="audiotracks"),
url(r"^(?P<page_number>\d+)/?$", views.index, name="audiotracks"),
url(r"^track/(?P<track_slug>.*)$", views.track_detail,
name="track_detail"),... | _index" | ),
url(r"^feed/?$", feeds.choose_feed, name="tracks_feed"),
url(r"^player.js$", views.player_script, name="player_script"),
url(r"^m3u/?$", views.m3u, name="m3u"),
]
|
saintdragon2/python-3-lecture-2015 | homework_checker/zest_hw2/hw_zest_15039029.py | Python | mit | 394 | 0.036932 | def baesoo(a):
if a%3==0:
if a%5 != 0:
ret | urn'3의 배수입니다'
elif a%5 == 0:
return'3과 5의 공배수입니다'
elif a%3 !=0 and a%5 ==0:
return'5의 배수입니다'
else:
return a
def dan(a):
ggg = ''
x=0
while x<9:
x= x+1
| # print(a*x,end='\t')
return (ggg)
a = dan(3)
print(a) |
tfmorris/pyokc | pyokc/helpers.py | Python | mit | 12,502 | 0.002724 | from json import loads
from re import search
from lxml import html
try:
from pyokc.errors import AuthenticationError, ProfileNotFoundError
except ImportError:
from errors import AuthenticationError, ProfileNotFoundError
CHAR_REPLACE = {
"′": "'",
'″': '"',
'“': '"',
'”': '"',
"’": "'",
... | element
Element used by xpath.
Returns
---------
bool
Whether you've contacted this user or not.
"""
return bool(div.xpath(".//span[@class = 'fancydate']"))
def get_profile_basics(div, profiles):
"""
Parse a <div> element fro | m a search result page to get basic
information of a profile.
Returns
----------
list of str, int
"""
profile_info = {}
if ('id' in div.attrib and len(div.attrib['id']) >= 4 and
'class' in div.attrib and div.attrib['class'] == 'match_card opensans'):
name = div.attrib['id'][4:]
... |
mattihappy/mtibattery | mtibattery/mtibattery.py | Python | gpl-3.0 | 17,206 | 0.003662 | """This module allows the user to conveniently access the
output of a MtiCorp Battery Analizer through a python
interface and to run several computations and to plot/output |
the data.
"""
import sys
import os.path as path |
from io import StringIO
import collections
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
from .helper import bstr2seconds, str2timedelta
class CellReadings(object):
""" Easy access to data from mticorp battery analyzer output.
"""
def __init__(self, filename):
""" In... |
skylifewww/pangolin-fog | product/templatetags/category_tags.py | Python | mit | 2,627 | 0.002284 | from django import template
from django.shortcuts import render_to_r | esponse, redirect, get_object_or_404
# from product.models import Slide
register = template.Library()
# @register.inclusion_tag('slides/slides.html')
# def get_main_slides():
# slides = Slide.objects.filter(published_main=1).order_by('ordering')
# return {'slides': slides}
# @register.inclus... | = Comments.objects.filter(paket=paket, item_model=item_model,item_id=item_id, published=1)
# return {'nodes':nodes, 'paket':paket, 'item_model':item_model, 'item_id':item_id}
# @register.filter(name='suit_conf')
# def suit_conf(name):
# value = get_config(name)
# return mark_safe(value) if isinstance(valu... |
venkey-ariv/fullerite | src/diamond/collectors/elb/test/testelb.py | Python | apache-2.0 | 8,323 | 0.00024 | #!/usr/bin/python
# coding=utf-8
import datetime
import mock
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
from test import run_only
from mock import Mock
from diamond.collector import Collector
from elb import ElbCollector
def run_only_if... | u'Count'}],
]
| cloudwatch.connect_to_region = Mock()
cloudwatch.connect_to_region.return_value = cw_conn
collector = ElbCollector(config, handlers=[])
target = ts + datetime.timedelta(minutes=1)
with mock.patch.object(datetime, 'datetime',
mock.Mock(wraps=datetime.da... |
andreftavares/django-yapi | setup.py | Python | bsd-3-clause | 1,143 | 0.003503 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).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='django-yapi',
vers... | include_package_data=True,
license=' | BSD License', # example license
description='A mini-framework for Django for creating RESTful APIs.',
#long_description=README,
#url='http://www.example.com/',
author='André Tavares',
author_email='github@andretavares.com',
classifiers=[
'Environment :: Web Environment',
'Framew... |
LowieHuyghe/edmunds | edmunds/foundation/concerns/middleware.py | Python | apache-2.0 | 1,120 | 0.000893 |
from threading import Lock
class Middleware(object):
"""
This class concerns middleware code for Application to extend from
"""
def middleware(self, class_):
"""
Add Application middleware
:param class_: The class of the middleware
:type class_: edmunds.foundation.... | return
self. | extensions[middleware_key].append(class_)
# add wsgi application
self.wsgi_app = class_(self)
|
thmttch/sc2castsclient | tests/tests.py | Python | bsd-3-clause | 2,367 | 0.000845 | #!/usr/bin/env python
'''
#from sc2casts_parser import *
from sc2casts_client import *
import json
from pprint import *
parser = SC2CastsParser()
client = SC2CastsClient()
TEST_DATA_DIR = 'data'
# test cases:
def test_titles():
pass
# test cases:
def test_casts():
with open(TEST_DATA_DIR + '/all', 'r') as... | s are | still valid
# client tests
def test_client_matchups():
actual = client.matchups()
assert len(actual) == 6
'''
|
hgl888/chromium-crosswalk | chrome/test/chromedriver/run_buildbot_steps.py | Python | bsd-3-clause | 19,323 | 0.011851 | #!/usr/bin/env python
# Copyright (c) 2013 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.
"""Runs all the buildbot steps for ChromeDriver except for update/compile."""
import bisect
import csv
import datetime
import glob... | EDRIVER_RELEASE_URL = 'http://chromedriver.storage.googleapis.com'
GS_CONTINUOUS_URL = GS_CHROMEDRIVER_DATA_BUCKET + '/continuous'
GS_PREBUILTS_URL = GS_CHROMEDRIVER_DATA_BUCKET + '/prebuilts'
GS_SERVER_LOGS_URL = GS_CHROMEDRIVER_DATA_BUCKET + '/server_logs'
SERVER_LOGS_LINK = (
'http://chromedriver-data.storage.go... | osition: refs/heads/master@{#(\d+)}')
CR_REV_URL = 'https://cr-rev.appspot.com/_ah/api/crrev/v1/redirect/%s'
SCRIPT_DIR = os.path.join(_THIS_DIR, os.pardir, os.pardir, os.pardir, os.pardir,
os.pardir, os.pardir, os.pardir, 'scripts')
SITE_CONFIG_DIR = os.path.join(_THIS_DIR, os.pardir, os.par... |
myvoice-nigeria/myvoice | myvoice/survey/migrations/0005_auto__del_field_surveyquestion_statistic.py | Python | bsd-2-clause | 12,627 | 0.008236 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'SurveyQuestion.statistic'
db.delete_column(u'survey_sur... | 'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rapidsms.Contact']", 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary... | .fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'staff_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.... |
Micronaet/micronaet-bom | bom_migration/migrate.py | Python | agpl-3.0 | 2,742 | 0.004012 | # -*- coding: utf-8 -*-
###############################################################################
#
# ODOO (ex OpenERP)
# Open Source Management Solution
# Copyright (C) 2001-2015 Micronaet S.r.l. (<http://www.micronaet.it>)
# Developer: Nicola Riolini @thebrush (<https://it.linkedin.com/in/thebrush>)
# This pro... | #######################################################################
import os
import sys
import logging
import openerp
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from o... | DATETIME_FORMATS_MAP,
float_compare)
_logger = logging.getLogger(__name__)
class MrpBomMigrateWizard(orm.TransientModel):
''' Wizard for migrate
'''
_name = 'mrp.bom.migrate.wizard'
# --------------------
# Wizard button event:
# --------------------
def action_migrate(self, cr,... |
aerialhedgehog/VyPy | trunk/VyPy/regression/active_subspace/__init__.py | Python | bsd-3-clause | 139 | 0 |
import learn
import inject
import project
from build_surrogate import build_surr | ogate
from ActiveSu | bspace import ActiveSubspace
|
odoousers2014/odoo | addons/l10n_hr/__init__.py | Python | agpl-3.0 | 1,096 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Module: l10n_hr
# Author: Goran Kliska
# mail: goran.kliska(AT)slobodni-programi.hr
# Copyright (C) 2011- Slobodni programi d.o.o., Zagreb
# Contrib... | n, either version 3 of the
# License, or (at your option) any later ver | sion.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU A... |
aselle/tensorflow | tensorflow/contrib/lite/testing/generate_examples.py | Python | apache-2.0 | 108,708 | 0.005731 | # 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... | ample["outputs"]:
wri | te_tensor(fp, i)
def write_test_cases(fp, model_name, examples):
"""Given a dictionary of `examples`, write a text format representation.
The file format is protocol-buffer-like, even though we don't use proto due
to the needs of the Android team.
Args:
fp: File-like object to write to.
model_name: ... |
cfelton/rhea | rhea/vendor/vendor.py | Python | mit | 351 | 0 |
class Vendor(object):
def | __init__(self):
self._vendor = None # altera, lattice, xilinx
self._model = None # vendor model
@property
def vendor( | self):
return self._vendor
@vendor.setter
def vendor(self, v):
assert v.lower() in ('altera', 'lattice', 'xilinx')
self._vendor = v.lower()
|
h4ck3rm1k3/FEC-Field-Documentation | fec/version/v8_0/SH3.py | Python | unlicense | 794 | 0.002519 | import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER COMMITTEE ID NUMBER', 'number': '2'},
{'name': 'TRANSACTION ID NUMBER', 'number': '3'... | 'EVENT TYPE', 'number': '6'},
{'name': 'EVENT/ACTIVITY ID/NAME', 'number': '7'},
{'name': 'RECEIPT DATE', 'number': '8'},
{'name': 'TOTAL AMOUNT TRANSFERRED', 'number': | '9'},
{'name': 'TRANSFERRED AMOUNT', 'number': '10'},
]
self.fields_names = self.hash_names(self.fields)
|
berkmancenter/mediacloud | apps/topics-base/tests/python/topics_base/stories/test_merge_foreign_rss_stories.py | Python | agpl-3.0 | 2,758 | 0.003263 | from operator import itemgetter
from mediawords.db import connect_to_db
from mediawords.dbi.downloads.store import store_content
from mediawords.test.db.create import create_test_topic, create_test_medium, create_test_feed, create_test_story
from topics_base.stories import merge_foreign_rss_stories
def test_merge_f... | ge_foreign_rss_stories()."""
db = connect_to_db()
topic = create_test_topic(db, 'foo')
medium = create_test_medium(db, 'norss')
feed = create_test_feed(db=db, label='norss', me | dium=medium)
num_stories = 10
stories = [
create_test_story(db=db, label=str(i), feed=feed)
for i in range(num_stories)
]
rss_medium = create_test_medium(db, 'rss')
rss_medium = db.query(
"update media set foreign_rss_links = 't' where media_id = %(a)s returning *",
... |
twelch/weather-station | pi2/FireflyDHT.py | Python | mit | 2,827 | 0.013088 | #!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries, Dots.Connect
# Author: Tony DiCola, Tim Welch
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | in!
if humidity is not None and temperature is not None:
print '{{"temp":{0:0.1f},"humidity":{1:0.1f}}}'.format(temperature, humidity)
else:
print 'Failed to get reading'
# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
'22': Adaf | ruit_DHT.DHT22,
'2302': Adafruit_DHT.AM2302 }
if len(sys.argv) >= 3 and sys.argv[1] in sensor_args and is_number(sys.argv[2]):
sensor = sensor_args[sys.argv[1]]
pin = sys.argv[2]
interval = None
#Fetch optional time interval
if len(sys.argv) == 4:
interval = float(sys.argv[3])
else:
print 'usag... |
ericdill/databroker | databroker/tests/test_v2/test_dask_filler.py | Python | bsd-3-clause | 1,490 | 0 | from event_model import Filler
import event_model
from bluesky.plans import count |
import numpy
from ophyd.sim import NumpySeqHandler
def test_fill_event(RE, hw):
docs = []
def callback(name, doc):
docs.append((name, doc))
| RE(count([hw.img]), callback)
docs
dask_filler = Filler({'NPY_SEQ': NumpySeqHandler}, coerce='delayed',
inplace=False)
filled_docs = []
for name, doc in docs:
filled_docs.append(dask_filler(name, doc))
filled_docs
_, dask_filled_event = filled_docs[-2]
arr... |
ujjwal96/mitmproxy | test/mitmproxy/addons/test_dumper.py | Python | mit | 5,783 | 0.000173 | import io
import shutil
import pytest
from unittest import mock
from mitmproxy.test import tflow
from mitmproxy.test import taddons
from mitmproxy.test import tutils
from mitmproxy.addons import dumper
from mitmproxy import exceptions
from mitmproxy import http
def test_configure():
d = dumper.Dumper()
with... | f)
assert "textToBeTruncated" not in sio.getvalue() |
sio.truncate(0)
class TestContentView:
@pytest.mark.asyncio
async def test_contentview(self):
with mock.patch("mitmproxy.contentviews.auto.ViewAuto.__call__") as va:
va.side_effect = exceptions.ContentViewException("")
sio = io.StringIO()
d = dumper.Dumper(... |
OCA/project | project_duplicate_subtask/tests/test_project_duplicate_subtask.py | Python | agpl-3.0 | 1,104 | 0.002717 | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
super().setUp()
self.project1 = self.env["project.project"].create({"name": ... | id": self.task1.id}
)
def test_check_subtasks(self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
le | n(new_task.child_ids), 2, "Two subtasks should have been created"
)
|
rtavenar/tslearn | tslearn/docs/examples/clustering/plot_barycenters.py | Python | bsd-2-clause | 3,323 | 0.000301 | # -*- coding: utf-8 -*-
"""
Barycenters
===========
This example shows three methods to compute barycenters of time series.
For an overview over the available methods see the :mod:`tslearn.barycenters`
module.
*tslearn* provides three methods for calculating barycenters for a given set of
time series:
* *Euclidean b... | ycenter of them
plt.plot(barycenter.ravel(), "r-", linewidth=2)
# plot the four variants with the same number of iterations and a tolerance of
# 1e-3 where applicable
ax1 = plt.subplot(4, 1, 1)
plt.title("Euclidean barycenter")
plot_helper(euclidean_barycenter(X))
plt.subplot(4, 1, 2, sharex=ax1)
plt.title("DBA ... | , max_iter=50, tol=1e-3))
plt.subplot(4, 1, 3, sharex=ax1)
plt.title("DBA (subgradient descent approach)")
plot_helper(dtw_barycenter_averaging_subgradient(X, max_iter=50, tol=1e-3))
plt.subplot(4, 1, 4, sharex=ax1)
plt.title("Soft-DTW barycenter ($\gamma$=1.0)")
plot_helper(softdtw_barycenter(X, gamma=1., max_iter=5... |
tech-blogging/sdataflow | sdataflow/debug/mermaid_page.py | Python | mit | 4,847 | 0 | # -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import os
from io import open
from sdataflow.shared import Entity, Outcome
MODE_DEFAULT = 0
MODE_OUTCOME_AS_LINK_TEXT = 1
MODE_IGNORE_OUTCOME = 2
HTML_TEMPLAGE = '''
<html>
<head>
<sc... | for outcome in src_entity.get_adjacent_vertices():
for dst_entity in outcome.get_adjacent_vertices():
self.statements.append(
self.render_link(
src_entity,
outcome,
dst... | )
class IgnoreOutcomeMode(OutcomeAsLinkTextMode):
def render_link(self, src_entity, outcome, dst_entity):
return '{0} --> {1}'.format(
NameContainer.get_name(src_entity),
NameContainer.get_name(dst_entity),
)
def generate_mermaid_page(linear_ordering, mode):
... |
heke123/chromium-crosswalk | tools/json_schema_compiler/compiler.py | Python | bsd-3-clause | 8,474 | 0.008497 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generator for C++ structs from api json files.
The purpose of this tool is to remove the need for hand-written code that
convert... | dir, impl_dir)
else:
output_dir = os.path.join(destdir, src_path)
if | not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(os.path.join(output_dir, filename), 'w') as f:
f.write(code)
# If multiple files are being output, add the filename for each file.
if len(generators) > 1:
output_code += [filename, '', code, '']
else:
output... |
simodalla/pympa-affarigenerali-OLD | docs/conf.py | Python | bsd-3-clause | 8,210 | 0.007552 | # -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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.
#
# ... | s to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch descrip... | on must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'openpa-organigrammidoc'
# -- Options for LaTeX output --------------... |
VertNet/dwc-indexer | lib/oauth2client/appengine.py | Python | lgpl-3.0 | 17,712 | 0.006323 | # Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowProperty, self).validate(value)
def empty(self, value):
return not value
class CredentialsProperty(db.Property):
"""App Engine datastore Property for Crede... | asy storage and retrieval of
oath2client.Credentials
"""
# Tell what the user type is.
data_type = Credentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
logging.info("get: Got type " + str(type(model_instance)))
cred = super(CredentialsProperty,
... |
ptonini/m2m-watchdog | lib/classes.py | Python | unlicense | 5,152 | 0.0033 | __author__ = 'ptonini'
import os
import sys
import socket
import time
import subprocess
import re
import psutil
class CommandRunner:
devnull = open(os.devnull, 'w')
class Service(CommandRunner):
need_restart = False
def __init__(self, name, pidfile, script, port, is_java, sampling, threshold):
... | lf.need_restart = True
return True
else:
status_line = output.split('\n')[1].lstrip()
values = re.split('\s{1,}', status_line)
eden.append(float(values[2]))
old.append(float(values[3]))
... | f self.__check_usage(self.eden_avg) and self.__check_usage(self.old_avg):
self.need_restart = True
return True
else:
return False
else:
return False
def daemon(self, option):
try:
subprocess.check_output(['/usr/sbin... |
sasmita/upm | examples/python/grovegsr.py | Python | mit | 2,008 | 0.001992 | #!/usr/bin/python
# Author: Zion Orent <zorent@ics.com>
# Copyright (c) 2015 Intel Corporation.
#
# 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 limi... | E
# 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.
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_grovegsr as u... | veGSR(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This lets you run code on exit, including functions from myGSR
def exitHandler():
print("Exiting")
sys.exit(0)
# Regi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.