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 |
|---|---|---|---|---|---|---|---|---|
jeffrey4l/nova | nova/tests/unit/api/openstack/compute/contrib/test_block_device_mapping.py | Python | apache-2.0 | 13,826 | 0.000072 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | arams = {'block_device_mapping': '/dev/vdb'}
self.assertRaises(self.validation_error,
self._test_create, self.params)
def test_create_instance_with_device_name_empty(self):
self.bdm[0]['device_name'] = ''
old_create = compute_api.API.create
def create(*ar... | bdm)
return old_create(*args, **kwargs)
self.stubs.Set(compute_api.API, 'create', create)
params = {block_device_mapping.ATTRIBUTE_NAME: self.bdm}
self.assertRaises(self.validation_error,
self._test_create, params, no_image=True)
def test_create_insta... |
ptitjes/quodlibet | quodlibet/ext/events/seekbar.py | Python | gpl-2.0 | 4,402 | 0 | # Copyright 2016 Christoph Reiter
#
# 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.
import contextlib
from gi.repository import GObject, Gtk
from quodlibet import _
from quodlibet i | mport app
from quodlibet.plugins.events import EventPlugin
from quodlibet.qltk import Icons
from quodlibet.qltk.seekbutton import TimeLabel
from quodlibet.qltk.tracker import TimeTracker
from quodlibet.qltk import Align
from quodlibet.util import connect_destroy
class SeekBar(Gtk.Box):
def __init__(self, player,... |
nrgaway/qubes-core-admin | qubes/vm/templatevm.py | Python | gpl-2.0 | 4,118 | 0.001457 | #
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
# Copyright (C) 2016 Marek Marczykowski <marmarek@invisiblethingslab.com>)
# Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
#
# This library is free software; you ca... | 'volatile': {
'name': 'volatile',
'size': defaults['root_img_size'],
'snap_on_start': False,
'save_on_stop': False,
'rw': True,
},
'kernel': {
'name': 'kernel',
'snap_on_start': Fals... | vents.handler('property-set:default_user',
'property-set:kernel',
'property-set:kernelopts',
'property-set:vcpus',
'property-set:memory',
'property-set:maxmem',
'pr... |
MattPerron/esper | esper/query/management/commands/score.py | Python | apache-2.0 | 14,310 | 0.004892 | from __future__ import print_function
from __future__ import division
from django.core.management.base import BaseCommand
from query.models import Video, Face, LabelSet, Frame
from scannerpy import ProtobufGenerator, Config
import os
import cv2
import math
import numpy as np
import tensorflow as tf
import align.detect_... | frames = self.remove_duplicates(ground_truth_frames)
return (ground_truth_frames, g_faces_dict)
def fetch_automatic_detections(self, video, label = "Talking Heads"):
| d_labelset = video.detected_labelset() # prediction
#d_faces = Face.objects.filter(frame__labelset=d_labelset).prefetch_related('frame').all()
#d_faces = Face.objects.filter(frame__labelset=d_labelset, frame__number__in=ground_truth_frames).prefetch_related('frame').all()
d_faces = Face.objects... |
reingart/gui2py | gui/event.py | Python | lgpl-3.0 | 6,795 | 0.003974 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's Event Model (encapsulates wx.Event)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart"
__license__ = "LGPL 3.0"
# Initial implementation was inspired on PythonCard's event module, altought
# it was... | aDown()
| self.left_button = wx_event.LeftIsDown()
self.right_button = wx_event.RightIsDown()
self.middle_button = wx_event.MiddleIsDown()
if name=="mousewheel":
self.wheel_delta = wx_event.GetWheelDelta()
class KeyEvent(Event):
"Keyboard related event (wrapper for wx.KeyEvent)"
... |
harisbal/pandas | pandas/core/apply.py | Python | bsd-3-clause | 12,744 | 0 | import warnings
import numpy as np
from pandas import compat
from pandas._libs import reduction
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.common import (
is_extension_type,
is_dict_like,
is_list_like,
is_sequence)
from pandas.util._decorators import cache_ | readonly
from pandas.io.formats.printing import pprint_thing
def frame_apply(obj, func, axis=0, broadcast=None,
raw=False, reduce=None, result_type=None,
ignore_failures=False,
args=None, kwds=None):
""" construct and return a row or column based frame apply object... | owApply
elif axis == 1:
klass = FrameColumnApply
return klass(obj, func, broadcast=broadcast,
raw=raw, reduce=reduce, result_type=result_type,
ignore_failures=ignore_failures,
args=args, kwds=kwds)
class FrameApply(object):
def __init__(self, ob... |
census-instrumentation/opencensus-python | tests/unit/stats/test_measure_to_view_map.py | Python | apache-2.0 | 16,207 | 0 | # Copyright 2018, OpenCensus 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 applicable law or agreed to in w... | UNT = CountAggregation()
REQUEST_COUNT_VIEW = View(
REQUEST_COUNT_VIEW_NAME,
"number of requests broken down by methods",
[METHOD_KEY], REQUEST_COUNT_MEASURE, COUNT)
class TestMeasureToViewMap(unittest.TestCase):
@staticmethod
def _get_target_class():
re | turn measure_to_view_map_module.MeasureToViewMap
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_constructor(self):
measure_to_view_map = measure_to_view_map_module.MeasureToViewMap()
self.assertEqual({},
measure_to_view... |
misnyo/searx | tests/unit/engines/test_btdigg.py | Python | agpl-3.0 | 19,083 | 0.002626 | # -*- coding: utf-8 -*-
from collections import defaultdict
import mock
from searx.engines import btdigg
from searx.testing import SearxTestCase
class TestBtdiggEngine(SearxTestCase):
def test_request(self):
query = 'test_query'
dicto = defaultdict(dict)
dicto['pageno'] = 0
params... | <span class="attr_val">5</span>
</td>
| <td>
<span class="attr_name">Temps:</span>
<span class="attr_val">417.8 jours</span>
</td>
<td>
<span class="at... |
acenario/Payable | Payable/PayableCore/admin.py | Python | mit | 217 | 0.013825 | from django.contrib import admin
from django.contrib.auth import get_user_model
| class SignUpAdmin(admin.Mo | delAdmin):
class Meta:
model = get_user_model()
admin.site.register(get_user_model(), SignUpAdmin) |
TechInvestLab/dot15926 | editor_qt/extensions/__init__.py | Python | lgpl-3.0 | 1,249 | 0.001601 | """Copyright 2012 TechInvestLab.ru dot15926@gmail.com
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following di... | ions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with th | e distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EX... |
behave/behave-django | tests/acceptance/steps/using_pageobjects.py | Python | mit | 1,207 | 0 | from behave import then, when
from bs4 import BeautifulSoup
from bs4.element import Tag
from pageobjects.pages import About, Welcome
@when(u'I instantiate the Welcome page object')
def new_pageobject(context):
context.page = Welcome(context)
@then(u'it provides a valid Beautiful Soup document')
def pageobject_w... | of %s (not %s)" % (
Tag.__name__, context.about_link.__class__.__name__)
@when('I call click() on the link')
def linkelement_click(contex | t):
context.next_page = context.about_link.click()
@then('it loads a new PageObject')
def click_returns_pageobject(context):
assert About(context) == context.next_page
|
mikeh77/mi-instrument | mi/platform/util/node_configuration.py | Python | bsd-2-clause | 2,911 | 0.012367 | #!/usr/bin/env python
"""
@package ion.agents.platform.util.node_configuration
@file ion/agents/platform/util/node_configuration.py
@author Mike Harrington
@brief read node configuration files
"""
__author__ = 'Mike Harrington'
__license__ = 'Apache 2.0'
from ooi.logging import log
from mi.platform.exceptions ... | parse yaml node specific config file : %s" % (str(e),node_config_filename))
except Exception as e:
raise NodeConfigurationFileException(msg="% | s Cannot open node specific config file : %s" % (str(e),node_config_filename))
self._node_yaml = NodeYAML.factory(node_config)
self._node_yaml.validate()
def Print(self):
log.debug("%r Print Config File Information for: %s\n\n", self._platform_id, self.node_meta_data['node_id_na... |
zrhans/python | exemplos/wakari/scripts-examples-webplot_example.py | Python | gpl-2.0 | 885 | 0.00339 | from webplot import p
p.use_doc('webplot example')
import numpy as np
import datetime
import time
x = np.arange(100) / 6.0
y = np.sin(x)
z = np.cos(x)
data_source = p.make_source(idx=range(100), x=x, y=y, z=z)
p.plot(x, y, 'orange')
p.figure()
p.plot('x', 'y', color='blue', data_source=data_source, title='sincos')
p.pl... | source)
p.figure()
p.hold(False)
p.scatter('x', 'y', 'orange', data_source=data_source)
p.scatter('x', 'z', | 'red', data_source=data_source)
p.plot('x', 'z', 'yellow', data_source=data_source)
p.plot('x', 'y', 'black', data_source=data_source)
print "click on the plots tab to see results"
|
GarySparrow/mFlaskWeb | venv/Lib/site-packages/pygments/lexers/_openedge_builtins.py | Python | mit | 48,362 | 0 | # -*- coding: utf-8 -*-
"""
pygments.lexers._openedge_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Builtin list for the OpenEdgeLexer.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
OPENEDGEKEYWORDS = (
'ABSOLUTE',
'ABS',
... | 'CONVERT-TO-OFFSET',
'CONVERT-TO-OFFS',
'CONVERT-TO-OFFSE',
'COPY-DATASET',
'COPY-LOB',
'COPY-SAX-ATTRIBUTES',
'COPY-TEMP-TABLE',
'COUNT',
'COUNT-OF',
'CPCASE',
'CPCOLL',
'CPINTERNAL',
'CPLOG',
'CPPRINT',
'CPRCODEIN',
'CPRCODEOUT',
'CPSTREAM',
| 'CPTERM',
'CRC-VALUE',
'CREATE',
'CREATE-LIKE',
'CREATE-LIKE-SEQUENTIAL',
'CREATE-NODE-NAMESPACE',
'CREATE-RESULT-LIST-ENTRY',
'CREATE-TEST-FILE',
'CURRENT',
'CURRENT_DATE',
'CURRENT-CHANGED',
'CURRENT-COLUMN',
'CURRENT-ENVIRONMENT',
'CURRENT-ENV',
'CURRENT-ENVI'... |
mark-in/securedrop-app-code | tests/test_unit_store.py | Python | agpl-3.0 | 1,563 | 0.00064 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
import zipfile
import config
import store
import common
from db import db_session, Source
import crypto_util
# Set environment variable so config.py uses a test environment
os.environ['SECUREDROP_ENV'] = 'test'
class TestStore(unittest.TestCase)... | verify(self):
with self.assertRaises(store.PathException):
store.verify(os.path.join(config.STORE_DIR, '..', 'etc', 'passwd'))
with self.assertRaises(store.PathException):
store.verify(config.STORE_DIR + "_backup")
def test_get_zip(self):
sid = 'EQZGCJBRGISGOTC2NZVWG... | on.add(source)
db_session.commit()
files = ['1-abc1-msg.gpg', '2-abc2-msg.gpg']
filenames = common.setup_test_docs(sid, files)
archive = zipfile.ZipFile(store.get_bulk_archive(filenames))
archivefile_contents = archive.namelist()
for archived_file, actual_file in zip(... |
PacktPublishing/OpenCV-Computer-Vision-Projects-with-Python | Module 2/1/image_filters.py | Python | mit | 2,407 | 0.02742 | # http://lodev.org/cgtutor/filtering.html
import cv2
import numpy as np
#img = cv2.imread('../images/input_sharp_edges.jpg', cv2.IMREAD_GRAYSCALE)
img = cv2.imread('../images/input_tree.jpg')
rows, cols = img.shape[:2]
#cv2.imshow('Original', img)
###################
# Motion Blur
size = 15
kernel_motion_blur = np.z... | mshow('Excessive Sharpening', output_2)
#cv2.imshow('Edge Enhancement', output_3)
###################
# Embossing
img_emboss_input = cv2.imread('../images/input_house.jpg')
kernel_emboss_1 = np.array([[0,-1,-1],
[1,0,-1],
[1, | 1,0]])
kernel_emboss_2 = np.array([[-1,-1,0],
[-1,0,1],
[0,1,1]])
kernel_emboss_3 = np.array([[1,0,0],
[0,0,0],
[0,0,-1]])
gray_img = cv2.cvtColor(img_emboss_input,cv2.COLOR_BGR2GRAY)
output_1 = cv2.filter2D(... |
eneldoserrata/marcos_openerp | marcos_addons/marcos_ncf/account_invoice.py | Python | agpl-3.0 | 10,032 | 0.004288 | # -*- encoding: utf-8 -*-
from openerp.osv import osv, fields
from idvalidator import is_ncf
from openerp.osv.osv import except_osv
from openerp import netsvc
from datetime import datetime
from openerp.tools.translate import _
import time
class account_invoice(osv.Model):
_inherit = "account.invoice"
_name =... | scal_position', False):
fiscal_type = self.pool.get("account.fiscal.position").browse(cr, uid, vals['fiscal_position']).fiscal_type
vals['reference_type'] = fiscal_type
elif vals.get('type', False) == "in_refund" and vals.get('fiscal_position', False):
vals['reference'] = val... | fiscal_type = self.pool.get("account.fiscal.position").browse(cr, uid, vals['fiscal_position']).fiscal_type
vals['reference_type'] = fiscal_type
inv = super(account_invoice, self).create(cr, uid, vals, context)
return inv
# go from canceled state to draft state
def ac... |
Tong-Chen/genomics-tools | mapreduce-python/mapreduce/model.py | Python | apache-2.0 | 39,526 | 0.006274 | #!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by | applicable law or agreed to in writing, software
# distribut | ed 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.
"""Model classes which are used to communicate between parts of implementation.
The... |
nschloe/quadpy | tools/lebedev/import_lebedev.py | Python | mit | 4,694 | 0.000639 | """
This little helper takes Lebedev point and weight data from [1] and produces JSON files.
[1]
https://people.sc.fsu.edu/~jburkardt/datasets/sphere_lebedev_rule/sphere_lebedev_rule.html
"""
import os
import re
import numpy as np
def read(filename):
data = np.loadtxt(filename)
azimuthal_polar = data[:, :2]... | data["a3"].append([weights[c[0]]])
elif len(c) == 24:
if any(abs(azimuthal_polar[c, 1] - 0.5) < 1.0e-12):
# polar == pi/2 => X == [p, q, 0].
# Find the smallest positive phi that's paired with `polar ==
# pi/2`; the symmetry is fully characteri... | abs(azimuthal_polar[c, 1] - 0.5) < 1.0e-12)[0]
assert len(k) == 8
k2 = np.where(azimuthal_polar[c, 0][k] > 0.0)[0]
azimuthal_min = np.min(azimuthal_polar[c, 0][k][k2])
data["pq0"].append([weights[c[0]], azimuthal_min])
else:
# X... |
patjouk/djangogirls | applications/migrations/0002_auto_20150308_2229.py | Python | bsd-3-clause | 1,002 | 0.002994 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('applications', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='question',
name=... | her',
field=models.BooleanField(default=False, help_text=b"Used only with 'Choices' question type", verbose_name=b"Allow for 'Other' answer?"),
),
migrations.AlterField(
model_name='questio | n',
name='is_multiple_choice',
field=models.BooleanField(default=False, help_text=b"Used only with 'Choices' question type", verbose_name=b'Are there multiple choices allowed?'),
),
migrations.AlterField(
model_name='question',
name='is_required',
... |
rhololkeolke/apo-website | src/application/generate_keys.py | Python | bsd-3-clause | 2,126 | 0.003293 | #!/usr/bin/env python
# encoding: utf-8
"""
generate_keys.py
Generate CSRF and Session keys, output to secret_keys.py file
Usage:
generate_keys.py [-f]
Outputs secret_keys.py file in current folder
By default, an existing secret_keys file will not be replaced.
Use the '-f' flag to force the new keys to be writt... | ME IN'
))
if os.path.exists(file_name):
if options.force is None:
print "Warning: secret_keys.py file exists. Use '-f | ' flag to force overwrite."
else:
write_file(output)
else:
write_file(output)
def main():
r = options.randomness
csrf_key = generate_randomkey(r)
session_key = generate_randomkey(r)
generate_keyfile(csrf_key, session_key)
if __name__ == "__main__":
main()
|
brian-team/brian2genn | brian2genn/correctness_testing.py | Python | gpl-2.0 | 1,039 | 0.005775 | '''
Definitions of the configuration for correctness testing.
'''
import brian2
import os
import shutil
import sys
import brian2genn
from brian2.tests.features import (Configuration, DefaultConfiguration,
run_feature_tests, run_single_feature_test)
__all__ = ['GeNNConfiguration',
... | eNNConfiguration(Configuration):
name = 'GeNN'
def before_run(self):
brian2.prefs.codegen.cpp.extra_compile_args = []
brian2.prefs._backup()
brian2.set_device('genn')
class GeNNConfigurationCPU | (Configuration):
name = 'GeNN_CPU'
def before_run(self):
brian2.prefs.codegen.cpp.extra_compile_args = []
brian2.prefs._backup()
brian2.set_device('genn', use_GPU=False)
class GeNNConfigurationOptimized(Configuration):
name = 'GeNN_optimized'
def before_run(self):
brian2... |
fuzzycode/RoboPi | main.py | Python | mit | 2,261 | 0.002655 | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2015 Björn Larsson
#
# 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 conditions:
#
# The above ... | ND, 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,... |
lefteye/superroutingchioce | create_loss_width_thoughtout.py | Python | gpl-2.0 | 1,854 | 0.006608 | # -*- coding:UTF-8 -*-
#用于产生吞吐量、可用带宽、抖动、丢包率
import csv
f = open('iperf_13.csv')
c = f.readlines()
csvfile1 = open('iperf_133.csv', 'ab')
writer1 = csv.writer(csvfile1)
for i in c:
# try:
t = i.split()
# print t
# print len(t)
ll = []
if len(t)==14:
| a= t[5]
# print type(a)
e=float(a)
# print type(a)
# print a
if e > 10:
# print "helloworld"
h = e * 0.001
k = str(h)
| ll.append(k)
else:
a = t[5]
ll.append(a)
b = t[7]
c = t[-5]
d = t[-1]
ll.append(b)
ll.append(c)
if len(d) == 6:
t = d[1:4]
ll.append(t)
# writer1.writerow(d)... |
bp-kelley/rdkit | rdkit/ML/UnitTestBuildComposite.py | Python | bsd-3-clause | 7,293 | 0.000137 | # $Id$
#
# Copyright (C) 2003-2008 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
"""unit testing code ... | ', '\n').encode('utf-8')
pklTF.close()
| with io.BytesIO(buf) as pklF:
refCompos = pickle.load(pklF)
# first make sure the data are intact
self._init(refCompos)
self.details.limitDepth = 3
self.details.lessGreedy = 1
compos = BuildComposite.RunIt(self.details, saveIt=0)
self.compare(compos, re... |
kirkwor/py | buildingGui_2.py | Python | mit | 1,732 | 0.008083 | '''
Created on 13 Jul 2017
@author: T
https://www.youtube.com/watch?v=6isuF_bBiXs
Tkinter:
+ standard lib
+ lightweight
+ good enough
- limited widgets
- strange import
- ugly
Python 3x
- ttk module (theme for better)
* run in transparent loop
* widgets are with parents
Geometry:
: absolute (avoid this)... | )
menubar.add_cascade(menu=menu_file, label="File")
def build_window(self):
label = Label(self.frame, text="How do I look?")
# label.pack(side="top")
label.grid(row=0, column=1)
button_bad = Button(self.frame, text="Terrible", command=self.quit)
# ... | ide="left")
button_bad.grid(row=0, column=0)
# button_bad.grid(row=0, column=0, sticky="E")
button_good = Button(self.frame, text="not bad", command=self.quit)
# button_good.pack(side="right")
button_good.grid(row=0, column=2)
# button_good.grid(row=0, column... |
chuckbutler/shoutcast-charm | lib/charmhelpers/core/hookenv.py | Python | mit | 14,883 | 0 | "Interactions with the Juju environment"
# Copyright 2013 Canonical Ltd.
#
# Authors:
# Charm Helpers Developer | s <juju@lists.ubuntu.com>
import os
import json
import yaml
import subprocess
import sys
import UserDict
from subprocess import CalledProcessError
CRITICAL = "CRITICAL"
ERROR = "ERROR"
WARNING = "WARNING"
INFO = "INFO"
DEBUG = "DEBUG"
MARKER = object()
cache = {}
def | cached(func):
"""Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls.
"""
def wrapper(*args, **kwargs):
global cach... |
Risto-Stevcev/iac-protocol | iac/app/libreoffice/calc.py | Python | bsd-3-clause | 3,484 | 0.003731 | """
To start UNO for both Calc and Writer:
(Note that if you use the current_document command, it will open the Calc's current document since it's the first switch passed)
libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc --writer
To ... | g.startswith("'") and string.endswith("'")):
string = string[1:-1]
cell.setString(string)
return True
@staticmethod
def get_text(cell):
"""[cell].get_text()"""
return cell.getString()
@staticmethod
def weight(cell, bold):
"""[cell].weight(['bold'])"... | cell.CharWeight = BOLD
return True
else:
return False
|
smart-classic/smart_server | smart/models/records.py | Python | apache-2.0 | 5,560 | 0.001079 | """
Records for SMART Reference EMR
Ben Adida & Josh Mandel
"""
from base import *
from django.utils import simplejson
from django.conf import settings
from smart.common.rdf_tools.rdf_ontology import ontology
from smart.common.rdf_tools.util import rdf, foaf, vcard, sp, serialize_rdf, parse_rdf, bound_graph, URIRef, ... | es_at = models.DateTimeField(null=False)
def save(self, *args, **kwargs):
if not self.token:
self.token = utils.random_string(30)
if self.expires_at is None:
minutes_to_expire = 30
try:
minutes_to_expire = settings.MINUTES_TO_EXPIRE_DIRECT_ACCES... | tes_to_expire)
super(RecordDirectAccessToken, self).save(*args, **kwargs)
class Meta:
app_label = APP_LABEL
class RecordAlert(Object):
record = models.ForeignKey(Record)
alert_text = models.TextField(null=False)
alert_time = models.DateTimeField(auto_now_add=True, null=False)
trig... |
ricjon/quarterapp | quarterapp/settings.py | Python | gpl-3.0 | 3,199 | 0.004689 | #
# Copyright (c) 2013 Markus Eliasson, http://www.quarterapp.com/
#
# 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... | ue)
self.settings[key] = value
else:
logging.warning("Trying to update a settings key t | hat does not exists! (%s)", key)
raise Exception("Trying to update a settings key that does not exists!")
def create_default_config(path):
"""Create a quarterapp.conf file from the example config file"""
import shutil, os.path
target = os.path.join(path, 'quarterapp.conf')
if os.path.exists... |
JLLeitschuh/allwpilib | wpilibj/src/athena/cpp/nivision/get_struct_size.py | Python | bsd-3-clause | 308 | 0.006494 | from __future__ import print_function
import sys
def main():
for line | in sys.stdin:
line = line.strip()
if not | line.startswith("#STRUCT_SIZER"):
continue
line = line[14:]
line = line.replace("#", "")
print(line)
if __name__ == "__main__":
main()
|
deepmind/acme | acme/tf/networks/distributions_test.py | Python | apache-2.0 | 2,618 | 0.00382 | # Copyright 2018 DeepMind Technologies Limited. 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 ... | , 5),
((), (3, 4), 5),
((2,), (3, 4), 5),
((2, 6), (3, 4), 5),
)
def test_constructor(self, batch_shape, event_shape, num_values):
logits_shape = batch_shape + event_shape + (num_values,)
logits_size = np.prod(logits_shape)
logits = np.arange(logits_size, dtype=float).reshape(logit... | num=num_values,
axis=-1)
distribution = distributions.DiscreteValuedDistribution(values=values,
logits=logits)
# Check batch and event shapes.
self.assertEqual(distribution.batch_shape, batch_shape)
self.assertEqual(di... |
Akrog/cinder | cinder/tests/test_dellscapi.py | Python | apache-2.0 | 155,946 | 0 | # Copyright (c) 2015 Dell 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 a... | u'volumeFolderPath': u'devstackvol/fcvm/',
u'hostCacheEna | bled': False,
u'usedByLegacyFluidFsNasVolume': False,
u'inRecycleBin': False,
u'volumeFolderIndex': 17,
u'instanceName': u'volume-37883deb-85cd-426a-9a98-62eaad8671ea',
u'statusMessage': u'',
u'status': u'Up',
u'storageTyp... |
NoneGG/aredis | tests/cluster/conftest.py | Python | mit | 3,388 | 0.000885 | # -*- coding: utf-8 -*-
# python std lib
import asyncio
import os
import sys
import json
# rediscluster imports
from aredis import StrictRedisCluster, | StrictRedis
# 3rd party imports
import pytest
from distutils.version import StrictVersion
# put our path in front so we can be sure we are testing locally not against the global package
basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(1, basepath)
_REDIS_VERSIONS = {}
def get... | loop = asyncio.get_event_loop()
info = loop.run_until_complete(client.info())
_REDIS_VERSIONS[key] = {key: value['redis_version'] for key, value in info.items()}
return _REDIS_VERSIONS[key]
def _get_client(cls=None, **kwargs):
if not cls:
cls = StrictRedisCluster
params = {
... |
dchirikov/luna | luna/utils/ip.py | Python | gpl-3.0 | 5,972 | 0.002009 | '''
Written by Dmitry Chirikov <dmitry@chirikov.ru>
This file is part of Luna, cluster provisioning tool
https://github.com/dchirikov/luna
This file is part of Luna.
Luna 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 Foun... | raise RuntimeError, err_msg
def aton(ip, ver=4):
"""
Convert the IP ip from the IPv4 numbers-and-dots
notation into binary form (in network byte order)
"""
try:
absnum = int(hexlify(socket.inet_pton(af[ | ver], ip)), 16)
return long(absnum)
except:
err_msg = "Cannot convert IP '{}' to C format".format(ip)
log.error(err_msg)
raise RuntimeError, err_msg
def reltoa(num_net, rel_ip, ver):
"""
Convert a relative ip (a number relative to the base of the
network obtained using... |
ProjectQ-Framework/ProjectQ | projectq/ops/_command_test.py | Python | apache-2.0 | 12,405 | 0.000564 | # -*- coding: utf-8 -*-
# Copyright 2017, 2021 ProjectQ-Framework (www.projectq.ch)
#
# 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.... | and.Command(main_engine, gate, input_tuple)
for ordered_qubit, expected_qubit in zip(cmd.qubits, expected_tuple):
assert ordered_qubit[0].id == expected_qubit[0].id
def test_command_interchangeable_qubit_indices(main_engine):
gate = BasicGate()
gate.interchangeable_qubit_indices = [[0, 4, 5], [1, ... | ureg([Qubit(main_engine, 2)])
qubit3 = Qureg([Qubit(main_engine, 3)])
qubit4 = Qureg([Qubit(main_engine, 4)])
qubit5 = Qureg([Qubit(main_engine, 5)])
input_tuple = (qubit4, qubit5, qubit3, qubit2, qubit1, qubit0)
cmd = _command.Command(main_engine, gate, input_tuple)
assert (
cmd.interch... |
bioidiap/bob.bio.spear | bob/bio/spear/config/extractor/cqcc20.py | Python | gpl-3.0 | 328 | 0.003049 | import numpy
imp | ort bob.bio.spear
# The authors of CQCC features recommend to use only first 20 features, plus deltas and delta-deltas
# feature vector is 60 in this case
cqcc20 = bob.bio.spear.extractor.CQCCFeatures(
features_mask=numpy.r_[
nump | y.arange(0, 20), numpy.arange(30, 50), numpy.arange(60, 80)
]
)
|
beni55/SimpleCV | SimpleCV/MachineLearning/TestTemporalColorTracker.py | Python | bsd-3-clause | 1,136 | 0.033451 | from SimpleCV import Camera, Image, Color, TemporalColorTracker, ROI, Display
import matplotlib.pyplot as plt
cam = Camera(1)
tct = TemporalColorTracker()
img = cam.getImage()
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
tct.train(cam,roi=roi,maxFrames=250,pkWndw=20)
# Matplot Lib exampl... | plt.grid()
plt.savefig('temp.png')
plt.clf()
plotImg = Image('temp.png')
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
roi.draw(width=3)
img.drawText(str(result),20,20,color=Color.RED,fontsize=32)
| img = img.applyLayers()
img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5)
img.save(disp)
|
butwhywhy/yamltempl | yamltempl/yaml_templates_command.py | Python | mit | 1,406 | 0.000711 | #! /usr/bin/env python
import argparse
import sys
from yamltempl import yamlutils, vtl
def main():
parser = argparse.ArgumentParser(
description="Merge yaml data into a Velocity Template Language template")
parser.add_argument('yamlfile',
metavar='filename.yaml',
... | n,
help='the template file. If omitted, the template '
'is read from standard input')
parser.add_argument('-o', '--output',
metavar='file',
| type=argparse.FileType('w'),
default=sys.stdout,
help='the output file, where the result should be '
'written. Standard output is used if omitted')
args = parser.parse_args()
yamldata = yamlutils.ordered_load(args.yamlfi... |
x4dr/NossiNet | NossiSite/extra.py | Python | gpl-2.0 | 9,041 | 0.001106 | import random
import time
from flask import (
request,
session,
flash,
redirect,
u | rl_for,
Response,
render_template,
)
fr | om NossiPack.Cards import Cards
from NossiPack.User import Userlist
from NossiPack.VampireCharacter import VampireCharacter
from NossiPack.krypta import DescriptiveError
from NossiSite.base import app as defaultapp, log
from NossiSite.helpers import checklogin
def register(app=None):
if app is None:
app =... |
EKT/pyrundeck | tests/unit_tests/test_native_conversion.py | Python | bsd-3-clause | 34,251 | 0 | # Copyright (c) 2015, National Documentation Centre (EKT, www.ekt.gr)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# Redistributions of source code must retain the above copyright
# n... | with open(multiple_jobs) as jobs_fl:
multiple_jobs = etree.fromstring(jobs_fl.read())
expected = {
'count': 3,
'list': [
{
'id': "3b8a86d5-4fc3-4cc1-95a2-8b51421c2069",
'name': 'job_with_args',
'... | },
{
'id': "ea17d859-32ff-45c8-8a0d-a16ac1ea3566",
'name': 'long job',
'group': '',
'project': 'API_client_development',
'description': 'async testing'
},
{
... |
georgemarshall/django | tests/utils_tests/test_inspect.py | Python | bsd-3-clause | 1,501 | 0.002665 | import unittest
from django.utils import inspect
class Person:
def no_arguments(self):
return None
def one_argument(self, something):
return something
def just_args(self, *args):
return args
def all_kinds(self, name, address='home', age=25, *args, **kwargs):
return ... | , False)
def test_method_has_no_args(self):
self.assertIs(inspect.method_has_no_args(Person.no_arguments), True)
self.assertIs(inspect.method_has_no_args(Person.one_argument), False)
self.assertIs(inspect.method_has_no_args(Person().no_arguments), True)
self.assertIs(inspect.method_... | ().one_argument), False)
|
zbuc/imaghost | ghost_exceptions/__init__.py | Python | bsd-2-clause | 120 | 0 | fro | m __future__ import (absolute_import, print_function, division)
class NotImplementedException(Exception):
| pass
|
owlabs/incubator-airflow | tests/test_utils/db.py | Python | apache-2.0 | 2,430 | 0.000823 | # -*- 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
#... | create | _default_connections, \
create_session
def clear_db_runs():
with create_session() as session:
session.query(DagRun).delete()
session.query(TaskInstance).delete()
def clear_db_dags():
with create_session() as session:
session.query(DagTag).delete()
session.query(DagModel).... |
svebk/DeepSentiBank_memex | cu_image_search/www/manager/locker.py | Python | bsd-2-clause | 868 | 0.004608 | import threading
# lock for each project or domain
# treat it as a singleton
# all file operation should be in lock region
class Locker(object):
_lock = {}
def acquire(self, name):
# create lock if it is not there
if name not in self._lock:
self._lock[name] = threading.Lock()
... | ase()
except:
pass
def remove(self, name):
# acquire lock first!!!
| if name not in self._lock:
return
try:
l = self._lock[name]
del self._lock[name] # remove lock name first, then release
l.release()
except:
pass
|
tiborsimko/invenio-ext | invenio_ext/fixtures/registry.py | Python | gpl-2.0 | 1,417 | 0.000706 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio 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... | SA.
"""Registry definition for fixture datasets."""
from flask_registry import RegistryProxy
from inveni | o_ext.registry import ModuleAutoDiscoveryRegistry
from invenio_utils.datastructures import LazyDict
fixtures_proxy = RegistryProxy(
'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures')
def fixtures_loader():
"""Load fixtures datasets."""
out = {}
for fixture in fixtures_proxy:
for data in get... |
Ban3/Limnoria | src/utils/crypt.py | Python | bsd-3-clause | 1,697 | 0 | ###
# Copyright (c) 2008, James McCoy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, ... | n binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the d | istribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND... |
eayunstack/fuel-ostf | fuel_health/tests/smoke/test_vcenter.py | Python | apache-2.0 | 20,161 | 0.000198 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2015 Mirantis, 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... | k that public IP 8.8.8.8 can be pinged from instance.
7. Disassociate server floating ip.
8. Delete floating ip
9. Delete server.
Duration: 300 s.
Available since release: 2014.2-6.1
| Deployment tags: nova_network, use_vcenter
"""
self.check_image_exists()
if not self.security_groups:
self.security_groups[self.tenant_id] = self.verify(
25, self._create_security_group, 1,
"Security group can not be created.",
... |
vortex-ape/scikit-learn | sklearn/preprocessing/__init__.py | Python | bsd-3-clause | 1,775 | 0 | """
The :mod:`sklearn.preprocessing` module includes scaling, centering,
normalization, binarization and imputation methods.
"""
from ._function_transformer import FunctionTransformer
from .data import Binarizer
from .data import KernelCenterer
from .data import MinMaxScaler
from .data import MaxAbsScaler
from .data ... | otEncoder
from ._encoders import OrdinalEncoder
from .label import label_binarize
from .label import LabelBinarizer
from .label import LabelEncoder
from .label import MultiLabelBinarizer
from ._discretization import KBinsDiscretizer
from .imputation import Imputer
# stub, remove in version 0.21
from .data import Ca... | ',
'MultiLabelBinarizer',
'MinMaxScaler',
'MaxAbsScaler',
'QuantileTransformer',
'Normalizer',
'OneHotEncoder',
'OrdinalEncoder',
'PowerTransformer',
'RobustScaler',
'StandardScaler',
'add_dummy_feature',
'PolynomialFeatures',
'binarize',
'normalize',
'scale',... |
enigmampc/catalyst | catalyst/testing/core.py | Python | apache-2.0 | 47,204 | 0.000021 | from abc import ABCMeta, abstractmethod, abstractproperty
from contextlib import contextmanager
from functools import wraps
import gzip
from inspect import getargspec
from itertools import (
combinations,
count,
product,
)
import operator
import os
from os.path import abspath, dirname, join, realpath
import... | loat64
EPOCH = pd.Timestamp(0, tz='UTC')
def seconds_to_ | timestamp(seconds):
return pd.Timestamp(seconds, unit='s', tz='UTC')
def to_utc(time_str):
"""Convert a string in US/Eastern time to UTC"""
return pd.Timestamp(time_str, tz='US/Eastern').tz_convert('UTC')
def str_to_seconds(s):
"""
Convert a pandas-intelligible string to (integer) seconds since ... |
jaybo/OpenCVGraph | TemcaGraphPy/temca_graph.py | Python | apache-2.0 | 21,780 | 0.007714 | """
Python wrapper for functionality exposed in the TemcaGraph dll.
@author: jayb
"""
from ctypes import *
import logging
import threading
import time
import os
import sys
import numpy as np
from pytemca.image.imageproc import fit_sin
from numpy.ctypeslib import ndpointer
if sys.flags.debug:
rel = "../x64/Debug... | eturns c_int
class CameraInfo(Structure):
'''
Information about the current camera in use.
'''
_fields_ = [
("width | ", c_int),
("height", c_int),
("format", c_int),
("pixel_depth", c_int),
("camera_bpp", c_int),
("camera_model", c_char * 256),
("camera_id", c_char * 256)
]
class FocusInfo(Structure):
'''
Information about focus quality.
'''
_fields_ = [
... |
kinddevil/aatest | python/mik.py | Python | mit | 831 | 0.049338 | #!/usr/bin/env python
import paramiko
from datetime import datetime
#hostname='192.168.0.102'
hostname='172.28.102.250'
username='root'
password='abc'
#port=22
if __name__=='__main__':
paramiko.util.log_to_file('paramiko.log')
s=paramiko.SSHClient()
#s.load_system_host_keys()
... | rname, password=password)
stdin,stdout,stderr=s.exec_command('ifconfig;free;df -h')
print stdout.read()
except:
print "fuck"
f = file('paramiko.log','w')
f.write(" ".join([str(datetime.now()), | "fuck\n"]))
f.close()
else:
print "how"
finally:
print "super fuck"
s.close()
|
AntonSax/plantcv | plantcv/roi_objects.py | Python | mit | 4,848 | 0.004332 | # Find Objects Partially Inside Region of Interest or Cut Objects to Region of Interest
import cv2
import numpy as np
from . import print_image
from . import plot_image
from . import fatal_error
def roi_objects(img, roi_type, roi_contour, roi_hierarchy, object_contour, obj_hierarchy, device, debug=None):
"""Find... | tal object pixel area
:param img: numpy array
:param roi_type: str
:param roi_contour: list
:param roi_hierarchy: list
:param object_contour: list
:param obj_hierarchy: list
:param device: int
:param debug: str
:return device: int
:retur | n kept_cnt: list
:return hierarchy: list
:return mask: numpy array
:return obj_area: int
"""
device += 1
if len(np.shape(img)) == 3:
ix, iy, iz = np.shape(img)
else:
ix, iy = np.shape(img)
size = ix, iy, 3
background = np.zeros(size, dtype=np.uint8)
ori_img = np... |
abadger/ansible | test/lib/ansible_test/_internal/cli/compat.py | Python | gpl-3.0 | 22,147 | 0.004425 | """Provides compatibility with first-generation host delegation options in ansible-test."""
from __future__ import annotations
import argparse
import dataclasses
import enum
import os
import types
import typing as t
from ..constants import (
CONTROLLER_PYTHON_VERSIONS,
SUPPORTED_PYTHON_VERSIONS,
)
from ..uti... | ""
def __init__(self, context):
super().__init__(f'A Python version was not specified for environment `{context}`. Use the `--python` option to specify a Python version.')
class ControllerNotSupportedError(ApplicationError):
"""Option(s) were specified which do not provide support for the controller a... | def __init__(self, context):
super().__init__(f'Environment `{context}` does not provide a Python version supported by the controller.')
class OptionsConflictError(ApplicationError):
"""Option(s) were specified which conflict with other options."""
def __init__(self, first, second):
super()._... |
bfontecc007/osbs-client | osbs/build/__init__.py | Python | bsd-3-clause | 314 | 0 | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This softwa | re may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import absolute_import
from .build_response import BuildResponse # noqa
from .pod_response im | port PodResponse # noqa
|
SureshMatsui/SpeedCoin | contrib/linearize/linearize.py | Python | mit | 3,357 | 0.034257 | #!/usr/bin/python
#
# linearize.py: Construct a linear, no-fork, best version of the blockchain.
#
#
# Copyright (c) 2013 The SpeedCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
im... | pc, settings, n):
hash = rpc.getblockhash(n)
hexdata = rpc.getblock(hash, False)
data = hexdata.decode('hex')
return data
def get_blocks(settings):
rpc = SpeedCoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpassword'])
outf = open(settings['output'] | , 'ab')
for height in xrange(settings['min_height'], settings['max_height']+1):
data = getblock(rpc, settings, height)
outhdr = settings['netmagic']
outhdr += struct.pack("<i", len(data))
outf.write(outhdr)
outf.write(data)
if (height % 1000) == 0:
sys.stdout.write("Wrote block " + str(height) + "\n... |
mcnowinski/various-and-sundry | lightcurve/windows/firstlook.py | Python | mit | 10,661 | 0.001782 | # this program requires the 32 bit version of Python!!
import os
import glob
import math
import subprocess
import re
import sys
import string
from decimal import Decimal
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
from scipy.ndimage i... | th *with* ending forward slash
input_path = './'
# output path *with* ending forward slash
sex_output_path = './firstlook/'
# bad path
bad_path = './ | bad/'
# suffix for output files, if any...
sex_output_suffix = '.sex'
# log file name
log_fname = './log.firstlook.txt'
# path to sextractor executable and config files (incl. the filenames!)
sextractor_bin_fname = os.path.dirname(
os.path.realpath(__file__)) + '\\' + 'sextractor.exe'
sextractor_cfg_fname = os.path... |
MM1nd/worldengine | worldengine/simulations/humidity.py | Python | mit | 1,502 | 0.000666 | from worldengine.simulations.basic import find_threshold_f
import numpy
class HumiditySimulation(object):
@staticmethod
def is_applicable(world):
return world.has_precipitations() and world.has_irrigation() and (
not world.has_humidity())
def execute(self, world, seed):
asser | t seed is not None
data, quantiles = self._calculate(world)
world.humidity = (data, quantiles)
@staticmethod
def _calculate(world):
humids = world.humids
precipitationWeight = 1.0
irrigationWeight = 3
data = numpy.zeros((world.height, world.width), dtype=float)
... | world.layers['irrigation'].data * irrigationWeight)/(precipitationWeight + irrigationWeight)
# These were originally evenly spaced at 12.5% each but changing them
# to a bell curve produced better results
ocean = world.layers['ocean'].data
quantiles = {}
quantiles['12'] = find_... |
vitmod/dvbapp | lib/python/Plugins/SystemPlugins/SoftwareManager/Flash_online.py | Python | gpl-2.0 | 18,755 | 0.028686 | from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
from Components.Button import Button
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.MenuList import MenuList
from Components.FileList import FileList
from Components.Task import Task, Job, job_manager, ... | " valign="top" transparent="1" />
<widget name="info-local" position="10,150" zPosition="1" size="450,200" font="Regular;20" halign="left" valign="top" transparent="1" />
</screen>"""
def __init__(s | elf, session):
Screen.__init__(self, session)
self.session = session
Screen.setTitle(self, _("Flash On the Fly"))
self["key_yellow"] = Button("Local")
self["key_green"] = Button("Online")
self["key_red"] = Button(_("Exit"))
self["key_blue"] = Button("")
self["info-local"] = Label(_("Local = Fl... |
privateip/ansible-modules-core | database/mysql/mysql_user.py | Python | gpl-3.0 | 22,945 | 0.005709 | #!/usr/bin/python
# (c) 2012, Mark Theunissen <mark.theunissen@gmail.com>
# Sponsored by Four Kitchens http://fourkitchens.com.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software... | ANTABILITY 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: mysql_user
short_description: Adds or removes ... | description:
- name of the user (role) to add or remove
required: true
password:
description:
- set the user's password. (Required when adding a user)
required: false
default: null
encrypted:
description:
- Indicate that the 'password' field is a `mysql_native_password` has... |
XueqingLin/tensorflow | tensorflow/python/training/sync_replicas_optimizer.py | Python | apache-2.0 | 40,433 | 0.003067 | # Copyright 2016 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... |
# Please note that the gradients from replicas are averaged instea | d of summed
# (as in the old sync_replicas_optimizer) so you need to increase the learning
# rate according to the number of replicas. This change is introduced to be
# consistent with how gradients are aggregated (averaged) within a batch in a
# replica.
class SyncReplicasOptimizerV2(optimizer.Optimizer):
"""Class t... |
arrayfire/arrayfire-python | setup.py | Python | bsd-3-clause | 4,514 | 0.005981 | #!/usr/bin/env python
#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
###############################... | arrayfire binaries or
# just with python wrapper files, the AF_BUILD_LOCAL
# environment var determines whether to build the arrayfire
# binaries locally rather than searching in a system install
AF_BUILD_LOCAL_LIBS = os.environ.get('AF_BUILD_LOCAL_LIBS')
print(f'AF_BUILD_LOCAL_LIBS={AF_BUILD_LOCAL_LIBS}')
if AF_BUIL... | se:
print('Skipping binaries installation, only python files will be installed')
AF_BUILD_CPU = os.environ.get('AF_BUILD_CPU')
AF_BUILD_CPU = 1 if AF_BUILD_CPU is None else int(AF_BUILD_CPU)
AF_BUILD_CPU_CMAKE_STR = '-DAF_BUILD_CPU:BOOL=ON' if (AF_BUILD_CPU == 1) else '-DAF_BUILD_CPU:BOOL=OFF'
AF_BUILD_CUDA = os.... |
MarsZone/DreamLand | evennia/evennia/locks/lockhandler.py | Python | bsd-3-clause | 20,024 | 0.002497 | """
A *lock* defines access to a particular subsystem or property of
Evennia. For example, the "owner" property can be impmemented as a
lock. Or the disability to lift an object or to ban users.
A lock consists of three parts:
- access_type - this defines what kind of access this lock regulates. This
just a stri... | string")
A lock definition is a string with a special syntax. It is added to
each object's lockhandler, making that lock available from then on.
The lock definition looks like this:
'access_type:[NOT] func1(args)[ AND|OR][NOT] func2() ...'
That is, the access_type, a colon followed by calls to lock functions
combi... |
Example:
We want to limit who may edit a particular object (let's call this access_type
for 'edit', it depends on what the command is looking for). We want this to
only work for those with the Permission 'Builders'. So we use our lock
function above and define it like this:
'edit:perm(Builders)'
Here, the lock-... |
NoyaInRain/tornado | tornado/web.py | Python | apache-2.0 | 138,158 | 0.000637 | #
# Copyright 2009 Facebook
#
# 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, s... | version produced by `.RequestHandler.create_signed_value`.
May be overridden by passing a ``version`` keyword argument.
.. versionadded:: 3.2.1
"""
DEFAULT_SIGNED_VALUE_MIN_VERSION = 1
"""The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.
May be overridd | en by passing a ``min_version`` keyword argument.
.. versionadded:: 3.2.1
"""
class _ArgDefaultMarker:
pass
_ARG_DEFAULT = _ArgDefaultMarker()
class RequestHandler(object):
"""Base class for HTTP request handlers.
Subclasses must define at least one of the methods defined in the
"Entry points" s... |
adviti/melange | thirdparty/google_appengine/google/appengine/api/prospective_search/prospective_search_pb.py | Python | apache-2.0 | 60,260 | 0.020179 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | (self):
if self.has_sub_id_:
self.has_sub_id_ = 0
self.sub_id_ = ""
def has_sub_id(self): return self.has_sub_id_
def lease_duration_sec(self): return self.lease_duration_sec_
def set_leas | e_duration_sec(self, x):
self.has_lease_duration_sec_ = 1
self.lease_duration_sec_ = x
def clear_lease_duration_sec(self):
if self.has_lease_duration_sec_:
self.has_lease_duration_sec_ = 0
self.lease_duration_sec_ = 0.0
def has_lease_duration_sec(self): return self.has_lease_duration_sec_
... |
haijieg/SFrame | oss_src/unity/python/sframe/data_structures/__init__.py | Python | bsd-3-clause | 841 | 0.005945 | """
GraphLab Create offers several data structures for data analysis.
Concise descriptions of the data str | uctures and their methods are contained in
the API documentation, along with a small number of simple examples. For more
detailed descriptions and examples, please see the `User Guide
<https://dato.com/learn/userguide/>`_, `API Translator
<https://dato.com/learn | /translator/>`_, `How-Tos
<https://dato.com/learn/how-to/>`_, and data science `Gallery
<https://dato.com/learn/gallery/>`_.
"""
'''
Copyright (C) 2015 Dato, Inc.
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
'''
__all__ = ['s... |
b-jesch/service.fritzbox.callmonitor | resources/lib/PhoneBooks/pyicloud/vendorlibs/keyrings/alt/_win_crypto.py | Python | gpl-2.0 | 3,477 | 0.000575 |
from ctypes import Structure, POINTER, c_void_p, cast, create_string_buffer, \
c_char_p, byref, memmove
from ctypes import windll, WinDLL, WINFUNCTYPE
try:
from ctypes import wintypes
except ValueError:
# see http://bugs.python.org/issue16396
raise ImportError("wintypes")
from keyring.util.escape impo... | f(blobin),
u('python-keyring-lib.win32crypto' | ),
None, None, None,
CRYPTPROTECT_UI_FORBIDDEN,
byref(blobout)):
raise OSError("Can't encrypt")
encrypted = create_string_buffer(blobout.cbData)
memmove(encrypted, blobout.pbData, blobout.cbData)
windll.kernel32.Loc... |
laszewsm/backuper | backup.py | Python | gpl-2.0 | 1,456 | 0.013049 | #!/usr/bin/env python
''' W celu poprawniego dzialania ponizszego skryptu, trzeba skonigurowac
logowanie RSA / DSA na maszynie na ktora, bedziemy przenosic nasza kopie zapasowa. Sposob konfiguracji mozna znalezc tutaj
http://www.nerdokracja.pl/linux-logowanie-ssh-klucze-rsa/
'''
import os
import os.path
print ('Tw... | any
print ('Wysylanie backupu ...')
cmd3 = "scp ~/tmp/backup.zip konto@jakis_aders_ip:/home/backup"
print('Usuniecie folderu tymczasowego')
cmd4 = "rm -R ~/tmp"
#wykonianie zdefiniowanych wczesniej polecen
os.system(cmd)
os.system(cmd1)
os.system(cmd2)
os.system(cmd | 3)
os.system(cmd4)
|
g10k/sw_tts | sw_tts/settings.py | Python | mit | 5,058 | 0.000989 | """
Django settings for sw_tts project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# ... | sageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sw_tts.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors' | : [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.contrib.auth.context_processors.auth... |
mfrey/baltimore | persistence/__init__.py | Python | gpl-3.0 | 74 | 0 | __all__ = ['persistence', | 'baltimorejsondecoder', 'bal | timorejsonencoder']
|
cchristelis/inasafe | safe/report/test/test_template_composition.py | Python | gpl-3.0 | 4,573 | 0.000219 | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Template Composition Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as publishe... | age)
# There are missing elements
component_ids = [
'white-inasafe-logo',
'north-arrow',
'organisation-logo',
'impact | -map', 'impact-legend',
'i-added-element-id-here-nooo']
template_composition.component_ids = component_ids
message = 'There should be no missing elements, but it gets: %s' % (
template_composition.missing_elements)
expected_result = ['i-added-element-id-here-nooo']
... |
qvazzler/Flexget | flexget/plugins/plugin_aria2.py | Python | mit | 22,207 | 0.003017 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
import re
import xmlrpc.client
from flexget import plugin
from flexget.event import event
from flexget.utils.template | import RenderError
from flexget.plugin import get_plugin_by_name
from socket import error as socket_error
log = logging.getLogger('aria2')
# TODO: stop using torrent_info_hash[0:16] as the GID
# for RENAME_CONTENT_FILES:
# to rename TV episodes, content_is_episodes must be set to yes
class OutputAria2(object):
... | ver: Where aria2 daemon is running. default 'localhost'
port: Port of that server. default '6800'
username: XML-RPC username set in aria2. default ''
password: XML-RPC password set in aria2. default ''
do: [add-new|remove-completed] What action to take with incoming
... |
jayanthkoushik/torch-gel | gel/__init__.py | Python | mit | 160 | 0 | impor | t gel.gelcd
import gel.gelfista
import gel.gelpaths
import gel.ridgepaths
__version__ = "2.0.0"
__all__ = ["gelcd", "gelfista", "gelpaths", "ridg | epaths"]
|
jrziviani/ziviani.net | build.py | Python | gpl-3.0 | 1,772 | 0.004515 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# blog.py - maps requests to methods and handles them accordingly.
# Copyright (C) 2017 Jose Ricardo Ziviani
#
# 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 Softwa... | ealpath(__file__))
# --
# IMPLEMENTATION
# --
def run_command(cmd):
'''
Runs arbitrary com | mand on shell
'''
proc = subprocess.Popen(cmd.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
if err:
print err
#sys.exit(1)
return out
def create_feeds():
'''
Creates the feed.xml file based on the published p... |
null-none/OpenGain | default_set/staticpages/migrations/0001_initial.py | Python | gpl-2.0 | 1,523 | 0.005909 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='StaticPage',
fields=[
('id', models.AutoField(s... | {
'verbose_name_plural': 'static pages',
'ordering': ('url',),
'verbose_name': 'static page',
| },
bases=(models.Model,),
),
]
|
iwoca/django-deep-collector | deep_collector/compat/serializers/django_1_9.py | Python | bsd-3-clause | 2,672 | 0.004117 | from django.core.serializers.json import Serializer
from ..builtins import StringIO
class CustomizableLocalFieldsSerializer(Serializer):
"""
This is a not so elegant copy/paste from django.core.serializer.base.Serializer serialize method.
We wanted to add parent fields of current serialized object becaus... | tream = options.pop("stream", StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_foreign_keys = options.pop('use_natural_foreign_ke | ys', False)
self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False)
progress_bar = self.progress_class(
options.pop('progress_output', None), options.pop('object_count', 0)
)
self.start_serialization()
self.first = True
for count, obj i... |
hfp/tensorflow-xsmm | tensorflow/python/keras/backend.py | Python | apache-2.0 | 160,654 | 0.006648 | # Copyright 2015 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... | ph and TF optimizers created in
# the graph.
_GRAPH_TF_OPTIMIZERS = weakref.WeakKeyDictionary()
@keras_export('keras.backend.backend')
def backend():
"""Publicly accessible method for determining the current backend.
Only exist | s for API compatibility with multi-backend Keras.
Returns:
The string "tensorflow".
"""
return 'tensorflow'
@keras_export('keras.backend.epsilon')
def epsilon():
"""Returns the value of the fuzz factor used in numeric expressions.
Returns:
A float.
Example:
```python
>>> keras.backe... |
DreamSourceLab/DSView | libsigrokdecode4DSL/decoders/ir_nec/lists.py | Python | gpl-3.0 | 1,471 | 0.008158 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Uwe Hermann <uwe@hermann-uwe.de>
##
## 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 Li... | 27: ['Program up', 'P+'],
30: ['Volume down', 'Vol-'],
| 31: ['Program down', 'P-'],
68: ['AV', 'AV'],
}.items())),
}
|
nicovillanueva/obsidian-core | src/screenshots/Capture.py | Python | gpl-2.0 | 836 | 0 | class Capture(object):
"""
Generic Capture entity. Base class
that both Screenshot and Pdiff can inherit from.
"""
def __init__(self, img_path):
if img_path is not None:
try:
self.path = img_path
self.hashvalue = self._set_hash()
except... | None
def _set_hash(self):
from hashlib import md5
md5hasher = md5()
with open(self.path, 'r') as f: |
data = f.read()
md5hasher.update(data)
return str(md5hasher.hexdigest())
def to_string(self):
entity = ""
for each in self.__dict__:
if each[0] != "_":
entity += "%s: %s \n" % (each, self.__dict__.get(each))
return entity
|
mrkm4ntr/incubator-airflow | tests/dags/test_on_kill.py | Python | apache-2.0 | 1,647 | 0 | #
# 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... | rt time
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils.timezone import datetime
class DummyWithOnKill(DummyOperator):
def execute(self, context):
import os
# This runs extra processes, so that we can be sure that we correctly
... | self.log.info("Executing on_kill")
with open("/tmp/airflow_on_kill", "w") as f:
f.write("ON_KILL_TEST")
# DAG tests backfill with pooled tasks
# Previously backfill would queue the task but never run it
dag1 = DAG(dag_id='test_on_kill', start_date=datetime(2015, 1, 1))
dag1_task1 = DummyWithOnKi... |
california-civic-data-coalition/django-calaccess-processed-data | docs/conf.py | Python | mit | 8,077 | 0.007305 | # -*- coding: utf-8 -*-
import sys
import os
from datetime import date
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.... | to this direct | ory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style s... |
atzengin/OCC | occ/gui/Block.py | Python | gpl-3.0 | 8,149 | 0.006381 | """
Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
OpenCV Companion 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) a... | ree Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
from Element import Element |
import Utils
import Colors
from .. base import odict
from Constants import BORDER_PROXIMITY_SENSITIVITY
from Constants import \
BLOCK_LABEL_PADDING, \
PORT_SEPARATION, LABEL_SEPARATION, \
PORT_BORDER_SEPARATION, POSSIBLE_ROTATIONS
import pygtk
pygtk.require('2.0')
import gtk
import pango
BLOCK_MARKUP_TMPL... |
mesbahamin/chronophore | tests/conftest.py | Python | mit | 4,885 | 0 | import logging
import pathlib
import pytest
from datetime import date, time
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from chronophore.models import Base, Entry, User
logging.disable(logging.CRITICAL)
@pytest.fixture()
def nonexistent_file(tmpdir, request):
"""Return a path t... | 17),
time_in=time(10, 45, 48),
time_out=None,
user_id='888222222',
user_type='tutor',
), |
]
return test_entries
|
bbiped-platform/BBIPED | src/BBIPED-GUI/src/Automatization/templates/BackwardBlade3D_template/BackwardBlade3D_template_Calculations.py | Python | lgpl-3.0 | 12,276 | 0.039915 | from __future__ import division
from math import *
import numpy as np
import scipy
import matplotlib
# USER INPUT
def UserValues(VariablesToModify):
# Blade Geometry Definition
_DefinedValues_dict = dict()
_DefinedValues_dict["Blade_gamma"]=45 # Blade stagger angle
_DefinedValues_dict["Blade_B1"]=15 # angle of at... | efinedValues_dict["Mesh_INLET_max_area"] = 15
_DefinedValues_dict["Mesh_INLET_min_area"] = 1 | 0
for i in range(len(VariablesToModify)):
if VariablesToModify[i] in _DefinedValues_dict:
if type(VariablesToModify[i+1]) is not str:
_DefinedValues_dict[VariablesToModify[i]]=VariablesToModify[i+1]
else: raise RuntimeError, "After variable %s there isn't a number % dicc[VariablesToModify[i]]"
retur... |
Formlabs/djangocms-page-meta | djangocms_page_meta/admin.py | Python | bsd-3-clause | 1,842 | 0.001086 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from cms.extensions import PageExtensionAdmin, TitleExtensionAdmin
from django.conf import settings
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .forms import TitleMetaAdmi... | 'classes': ('collapse',)
}),
(_('Twitter Cards'), {
'fields': ('twitter_type', 'twitter_author'),
'classes': ('collapse',)
}),
(_('Google+ Snippets'), {
'fields': ('gplus_type', 'gplus_author'),
'cl | asses': ('collapse',)
}),
)
class Media:
css = {
'all': ('%sdjangocms_page_meta/css/%s' % (
settings.STATIC_URL, 'djangocms_page_meta_admin.css'),)
}
def get_model_perms(self, request):
"""
Return empty perms dict thus hiding the model fr... |
beaker-project/beaker | Server/bkr/server/alembic/versions/5ab66e956c6b_osversion_osmajor_id_non_nullable.py | Python | gpl-2.0 | 743 | 0.008075 | # This program is free software; you can redis | tribute 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.
"""Make osversion.osmajor_id non-NULLable
Revision ID: 5ab66e956c6b
Revises: 286ed23a5c1b
Create Date: 2017-12-20 15... | bic import op
from sqlalchemy import Integer
def upgrade():
op.alter_column('osversion', 'osmajor_id', existing_type=Integer, nullable=False)
def downgrade():
op.alter_column('osversion', 'osmajor_id', existing_type=Integer, nullable=True)
|
Applied-GeoSolutions/geokit | geokit/tests/util.py | Python | gpl-2.0 | 1,699 | 0.000589 | import logging
from django.db import connection
from django.con | trib.auth.models import User
from tenant_schemas.utils import get_tenant_model
from tenant_schemas.test.cases import TenantTestCase
import pytest
logger = logging.getLogger('tests.util')
def make_tenant(schema='test', domain='tenant.test.com', username='tester'):
"""Returns a tuple: (a tenant schema, an admi... | tenant are created if they don't already exist, and the db
connection is set to that tenant. Logs to tests.util, level INFO.
Tenant creation is conditional because it requires significant time.
"""
TenantTestCase.sync_shared()
# create or get the user
user, created = User.objects.get_or_create... |
nickhills81/tado_heating_for_splunk | bin/zone0.py | Python | mit | 2,916 | 0.03155 | #!/usr/bin/python
import urllib, urllib2, json, sys
import splunk.entity as entity
# access the credentials in /servicesNS/nobody/app_name/admin/passwords
def getCredentials(sessionKey):
myapp = 'tado'
try:
# list all credentials
entities = entity.getEntities(['admin', 'passwords'], namespace=myapp... | s(sessionKey)
token = getAuth(username, password)
homeId = getHomeId(token)
doRequest(token,homeId)
def getAuth(email, password):
data = dict(client_id="tado-webapp",grant_type="password",password=password,scope="home.user", username=email )
authUrl = "https://my.tado.co | m/oauth/token"
method = "POST"
handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
data = urllib.urlencode(data)
request = urllib2.Request(authUrl, data=data)
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
if... |
cuongnv23/curl2share | curl2share/__init__.py | Python | mit | 691 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
from curl2share.config import log_file, log_level
loglevel = {'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARN,
'INFO': logging.INFO,
'DEBUG... | 'NOTSET': logging.NOTSET}
logger = logging.getLogger(__name__)
logger.setLevel(loglevel[log_level])
fh = logging.FileHandler(log_file)
fh.setLevel(loglevel[log_level])
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s \
- | %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
|
berkeleybop/behave_core | tests/environment.py | Python | bsd-3-clause | 411 | 0.024331 | ####
#### S | etup gross testing environment.
####
#import time
from behave_core.environment import start_browser, define_target, quit_browser
from behave import *
## Run this before anything else.
def before_all(context):
#pass
start_browser(context)
define_target(context)
#time.sleep(10)
## Do this after com... | verything.
def after_all(context):
#pass
quit_browser(context)
|
ckprice/bedrock | bedrock/mozorg/helpers/social_widgets.py | Python | mpl-2.0 | 3,148 | 0.001271 | # 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/.
from __future__ import unicode_literals
from datetime import datetime
import urllib
import jingo
from lib.l10n_utils.do... | .quote(name.encode('utf8')), name)))
# URLs
for url in entities['urls']:
text = text.replace(url['url'],
('<a href="%s" title="%s">%s</a>'
% (url['url'], url['expanded_url'], url['display_url'])))
# Media
if entities.get('media'):
... | "%s" class="media">%s</a>'
% (medium['url'], medium['expanded_url'],
medium['display_url'])))
return text
@jingo.register.function
def format_tweet_timestamp(tweet):
"""
Return an HTML time element filled with a tweet timestamp.
@p... |
TheProjecter/kassie | src/bases/importeur.py | Python | bsd-3-clause | 10,203 | 0.00337 | # -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# l... | if module.statut == INITIALISE:
module.detruire()
def boucle(self):
"""Méthode appelée à chaque tour de boucle synchro.
Elle doit faire appel à la méthode boucle de chaque module primaire
ou secondaire.
"""
for module in self.__dict__.values():
... | n'a pas besoin du type du module, les modules primaires
et secondaires étant stockés de la même façon.
Attention: un module peut être chargé sans être instancié,
configuré ou initialisé.
"""
return nom in self.__dict__.keys()
def charger_module(self, parser_cmd, m... |
bwasti/caffe2 | caffe2/python/operator_test/cross_entropy_ops_test.py | Python | apache-2.0 | 3,643 | 0.000274 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
def sig... | hu.arrays(
dims=shape,
elements=st.sampled_from([0.0, 1.0]),
),
)
),
**hu.gcs
)
def test_sigmoid_cross_entropy_with_logits(self, inputs, gc, dc):
logits, targets = inputs
def sigmoid_xentr_logit_r... | )
return (m, )
def sigmoid_xentr_logit_grad_ref(g_out, outputs, fwd_inputs):
fwd_logits, fwd_targets = fwd_inputs
inner_size = fwd_logits.shape[-1]
m = fwd_targets - sigmoid(fwd_logits)
g_in = -np.expand_dims(g_out, axis=-1) * m / inner_size
... |
jmosky12/huxley | huxley/api/validators.py | Python | bsd-3-clause | 1,610 | 0.001882 | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import re
from rest_framework.serializers import ValidationError
def name(value):
'''Matches names of people, countries and and other thing... | .')
def phone_international(value):
'''Loosely matches phone numbers.'''
if re.mat | ch(r'^[\d\-x\s\+\(\)]+$', value) is None:
raise ValidationError('This is an invalid phone number.')
def phone_domestic(value):
'''Matches domestic phone numbers.'''
if re.match(r'^\(?(\d{3})\)?\s(\d{3})-(\d{4})(\sx\d{1,5})?$', value) is None:
raise ValidationError('This is an invalid phone num... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tornado/escape.py | Python | bsd-2-clause | 14,393 | 0.000208 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | of character encodings.
result = _parse_qs(qs, keep_blank_values, strict_parsing,
encoding='latin1', errors='strict')
encoded = {}
for k, v in result.items():
encoded[k] = [i.encode('latin1') for i in v]
return encoded
_UTF8_TYPES = (bytes, type(... | pe: (typing.Union[bytes,unicode_type,None])->typing.Union[bytes,None]
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
"""
if isinstance(value, _UTF8_TYPES):
... |
awsdocs/aws-doc-sdk-examples | python/example_code/comprehend/test/test_comprehend_demo_resources.py | Python | apache-2.0 | 4,823 | 0.000622 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Unit tests for comprehend_demo_resources.py
"""
from io import BytesIO
import json
import tarfile
import time
from unittest.mock import MagicMock
import uuid
import boto3
from botocore.exceptions import Clie... | icy_arn)
runner.add(iam_s | tubber.stub_attach_role_policy, role_name, policy_arn)
if error_code is None:
demo_resources.setup(demo_name)
assert demo_resources.bucket.name == bucket_name
assert demo_resources.data_access_role.name == role_name
else:
with pytest.raises(ClientError) as exc_info:
... |
generica/euler | 18.py | Python | gpl-2.0 | 782 | 0.001279 | #!/usr/bin/python
y = '''75
95 64
17 47 82 |
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 9... | :
tally += int(a[y_pos][x_pos])
print int(a[y_pos][x_pos])
next_l = int(a[y_pos+1][x_pos])
next_r = int(a[y_pos+1][x_pos+1])
if next_l < next_r:
x_pos += 1
print int(a[y_pos+1][x_pos])
tally += int(a[y_pos+1][x_pos])
print tally
|
tseaver/google-cloud-python | pubsub/google/cloud/pubsub_v1/_gapic.py | Python | apache-2.0 | 2,637 | 0.000758 | # Copyright 2019, Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | functools.wraps(wrapped_fx)(fx)
def actual_decorator(cls):
# Reflectively iterate over most of the met | hods on the source class
# (the GAPIC) and make wrapped versions available on this client.
for name in dir(source_class):
# Ignore all private and magic methods.
if name.startswith("_"):
continue
# Ignore anything on our blacklist.
if name... |
marcelor/django_info | django_info/views.py | Python | mit | 1,879 | 0.001064 | # -*- coding: utf-8 -*-
import os
import sys
from django.contrib.auth.decorators import login_required
from django import get_version as get_django_version
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.conf import settings
from django_info import __version__
de... | on
def get_database_engine():
return settings.DATABASES['default']['ENGINE'].split('.')[-1]
def get_installed_apps | ():
return settings.INSTALLED_APPS
def get_debug_mode():
return settings.DEBUG
def get_template_debug_mode():
return settings.TEMPLATE_DEBUG
def is_dev_server(request):
"""
http://stackoverflow.com/a/1291858/1503
"""
server_software = request.META.get('SERVER_SOFTWARE', None)
retur... |
linkian209/Destiny_RNN | create.py | Python | mit | 3,091 | 0.019088 | # encoding=utf8
import utils
import pickle
import zipfile
import os
from tqdm import tqdm
from pprint import pprint
# Globals
#[Special, Heavy, Primary]
bucketHashes = [2465295065,953998645,1498876634]
# Load in Manifest
print 'Loading Manifest...'
with open('manifest.pickle','rb') as f:
data = pickle.loads(f.rea... | _archive).st_size <= 3900000000):
# Create a contents file for the archive
with open('contents.txt','w') as f:
for i in hash_l | ist:
f.write('%d.txt' % i)
zf = zipfile.ZipFile(cur_archive, 'a', zipfile.ZIP_DEFLATED, allowZip64=True)
zf.write('contents.txt')
zf.close()
os.remove('contents.txt')
cur_arch += 1
hash_list = []
# Open zipfile
zf = zipfile.ZipFile(cur_archive, 'a', zipfile.ZIP_DEF... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.