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 |
|---|---|---|---|---|---|---|---|---|
patrickbeeson/diy-trainer | diytrainer/guides/urls.py | Python | mit | 651 | 0.003072 | from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = patterns('',
url(
regex=r' | ^(?P<guide_version>\d+)/$',
view=views.EmailSignUpCreateView.as_view(),
name='email_signup'
),
url(
regex=r'^(?P<guide_version>\d+)/feedback/$',
view=views.FeedbackCreateView.as_view(),
name='guide_feedback'
),
url(
regex=r'^(?P<guide_version>\d+)/feedback... | $',
view=TemplateView.as_view(template_name='guides/feedback_submitted.html'),
name='guide_feedback_thanks'
)
)
|
Fisiu/calendar-oswiecim | webapp/calendars/migrations/0005_auto_20150718_1537.py | Python | agpl-3.0 | 451 | 0.002217 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('calendars', '0004_auto_20150718_1529'),
]
operations = [
migrations.AlterField(
model_name='event',
... | ank=True, verbose_name='Koniec wydarzenia', nu | ll=True),
),
]
|
SCOAP3/scoap3 | rawtext_search.py | Python | gpl-2.0 | 9,093 | 0.00176 | # -*- 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 opt... | tuple)):
self._print_tree(split, indentation_level+1)
else:
print indentation + '\t' + split
#SEARCH STUFF
def _is_regex(self, searchterm):
if searchterm.startswith(self.regex_search_delimiter):
return True
return False
def _get_activ... | earch_delimiter):
return searchterm.replace(self.normal_search_delimiter, '')
if searchterm.startswith(self.regex_search_delimiter):
return searchterm.replace(self.regex_search_delimiter, '')
return searchterm
def _perform_search(self, raw_text, searchterm):
if not ... |
Kazade/NeHe-Website | public/post_to_twitter.py | Python | bsd-3-clause | 2,865 | 0.001396 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <arthur.furlan@gmail.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 2 of the License, or
# (at your option) an... | return u'%s' % self.text
def get_absolute_url(self):
return self.link
# the following method is optional
def get_twitter_message(self):
return u'my-custom-twitter-me | ssage: %s - %s' \
% (self.text, self.link)
models.signals.post_save.connect(post_to_twitter, sender=MyModel)
"""
# avoid to post the same object twice
if not kwargs.get('created'):
return False
# check if there's a twitter account configured
try:
us... |
oduwsdl/ipwb | setup.py | Python | mit | 2,128 | 0 | #!/usr/bin/env python
from setuptools import setup
from ipwb import __version__
with open('README.md') as f:
long_description = f.read()
desc = """InterPlanetary Wayback (ipwb): Web Archive integration with IPFS"""
setup(
name='ipwb',
version=__version__,
url='https://github.com/oduwsdl/ipwb',
do... | e :: Information Technology',
'Intended Audience :: Science/Research',
'Topic :: Internet :: WWW/HTTP',
'Topic :: System :: Archiving',
'Topic :: System :: Archiving :: Backup',
'Topic :: System :: Archiving :: Mirroring',
'Topic :: Utilities',
]
)
# Pu | blish to pypi:
# rm -rf dist; python setup.py sdist bdist_wheel; twine upload dist/*
|
WISDEM/pyFrame3DD | setup.py | Python | gpl-3.0 | 1,499 | 0.00934 | # setup.py
# only if building in place: ``python setup.py build_ext --inplace``
import os
import sys
import platform
import glob
from setuptools import setup, find_packages
from numpy.distutils.core import setup, Extension
os.environ['NPY_DISTUTILS_APPEND_FLAGS'] = '1'
#if os.name == 'nt': # Windows.
# extra_com... | py_io.c',
froot+'py_main.c'])
setup(
name='pyFrame3DD',
version='1.1.1',
description='Python bindings to Frame3DD', |
author='NREL WISDEM Team',
author_email='systems.engineering@nrel.gov',
#package_dir={'': 'src'},
#py_modules=['pyframe3dd'],
package_data={'pyframe3dd': []},
packages=['pyframe3dd'],
license='Apache License, Version 2.0',
ext_modules=[pyframeExt],
zip_safe=False
)
|
Smart-Torvy/torvy-home-assistant | homeassistant/components/alarm_control_panel/demo.py | Python | mit | 462 | 0 | """
Demo platform that has two fake alarm control panels.
For more details about this pla | tform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import homeassistant.components.alarm_control_panel.manual | as manual
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Demo alarm control panel platform."""
add_devices([
manual.ManualAlarm(hass, 'Alarm', '1234', 5, 10, False),
])
|
googlecreativelab/beat-blender | main.py | Python | apache-2.0 | 859 | 0.004657 | #!/usr/bin/env python
#
# Copyright 2017 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... | is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import webapp2
import urllib2
c | lass Redirect( webapp2.RequestHandler ):
def get(self):
self.redirect('/ai/beat-blender/view/')
app = webapp2.WSGIApplication([
('/ai/beat-blender/view', Redirect),
('/', Redirect),
], debug=True)
|
teitei-tk/ice-pick | tests/test_recorder.py | Python | mit | 2,731 | 0 | import unittest
from nose.tools import ok_, eq_
import datetime
from pymongo import MongoClient
from tests.config import DB_HOST, DB_PORT, DB_NAME
from icePick.recorder import get_database, Structure, Recorder
db = get_database(DB_NAME, DB_HOST, DB_PORT)
class TestStructureModel(Structure):
pass
class TestR... | record.string)
self.record.string = "update"
self.record.save()
eq_("update", self.record.string)
def test_get(self):
self.record.string = "new_str"
self.record.save()
exist_record = TestRecorderModel.get(self.rec | ord.key())
eq_(exist_record.key(), self.record.key())
eq_(exist_record.string, self.record.string)
def test_find(self):
result = TestRecorderModel.find()
eq_(0, result.__len__())
self.record.save()
result = TestRecorderModel.find()
eq_(1, result.__len__())
... |
jodal/comics | comics/comics/rutetid.py | Python | agpl-3.0 | 442 | 0 | from comics.aggregator.crawler import DagbladetCrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
| name = "Rutetid"
language = "no"
url = "http://www.dagbladet.no/tegneserie/rutetid/"
rights = "Frode Øverli"
active = False
class Crawler(DagbladetC | rawlerBase):
time_zone = "Europe/Oslo"
def crawl(self, pub_date):
return self.crawl_helper("rutetid", pub_date)
|
arcticio/ice-bloc-hdr | handlers/gablog/contact.py | Python | mit | 4,409 | 0.016103 | # The MIT License
#
# Copyright (c) 2008 William T. Katz
#
# 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, mod... | st.get('subject') | or 'No Subject Given',
body = (reply_to + " wrote:\n\n" + self.request.get('message')) or 'No Message Given'
)
logging.info("MAIL: %s, ref: %s", reply_to, referer)
view.ViewPage(cache_time=36000).render(self)
|
adamnew123456/jqueue | test_all.py | Python | bsd-2-clause | 1,476 | 0.003388 | """
This tests both the server and the client, by uppercasing the content of
different files.
"""
import os
import tempfile
import threading
import time
from jqueue import quickstart, server
# These are the names of the jobs, as well as the | ir content
IN_FILES = {
'A': 'a lowercase test',
'B': 'miXeD-caSe',
'C': 'UPPER CASE'
}
OUT_FILES = {
'A.result': 'A LOWERCASE TEST',
'B.result': 'MIXED-CASE',
'C.result': 'UPPER-CASE'
}
svr = server.Server()
def server_thread_runner():
svr.run([fname.encode('ascii') for fname in IN_FILES... | kstart.process_jobs('localhost', handler, ttl=5)
with tempfile.TemporaryDirectory() as tmpdir:
os.chdir(tmpdir)
for fname in IN_FILES:
with open(fname, 'w') as fstream:
fstream.write(IN_FILES[fname])
server_thread = threading.Thread(target=server_thread_runner, name='Server')
clien... |
chetan51/nupic.research | projects/rsm/util.py | Python | gpl-3.0 | 11,475 | 0.00061 | # Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2019, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it unde... | y in distrs:
activity_arr = distrs[key]
dist = torch.stack(activity_arr)
ax = axs[i][j]
mean_act = activity_square(dist.mean(dim=0).cpu())
side = mean_act.size(0)
ax.imshow(mean_act, origin | ="bottom", extent=(0, side, 0, side))
else:
ax.set_visible(False)
ax.axis("off")
ax.set_title(key, fontsize=5)
return fig
def plot_activity(distrs, n_labels=10, level="column"):
"""
Plot column activations for each combination of input and actual next in... |
ACRMGroup/canonicals | extras/src/python/create_pdb_file_list.py | Python | gpl-3.0 | 2,213 | 0.009038 | #!/usr/bin/env python
#************************************************************#
# #
# Author: jacob Hurst #
# File name: create_pdb_file_list.py #
# Date: Wednesday 18 Mar 2009 ... | append(pdb_file_name)
fIn.close()
###******************************************************#
def write_file(self, outfilename):
""" files are written """
fOut = open(outfilename, "w")
for pdb_id in self.pdb_ids:
fOut.write("%s/%s\n" %(self.location, pdb_id))
... | ******************************#
def usage():
print "./create_pdb_file_list.py <saxsfile> <pdblocation> <outfilename>"
sys.exit(1)
#************************************************************#
if __name__ == "__main__":
if len(sys.argv)!=4:
usage()
cL = CreateList(sys.argv[1], sys.argv[2], sys.a... |
utmi-2014/utmi-ros-enshu | enshu20141204/scripts/group15/test_detect_face.py | Python | mit | 2,428 | 0.00557 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# test_detect_face.py
import rospy
from std_msgs.msg import Bool
from sensor_msgs.msg import CompressedImage
import sys
import cv2
import numpy as np
class DetectFace:
def __init__(self):
rospy.init_node('detect_face')
self.pub = rospy.Publisher('/en... | int facerect
# 認識結果の保存
cv2.imwrite("/tmp/test_detect_face.jpeg", image_gray)
if len(facerect) <= 0:
self.detected = False
print "callback: ", False
return
# 検出した顔を囲む矩形の作成
# for rect in facerect:
# cv2.rectangle(image, tuple(rect[... | "callback: ", True
def main():
detect_face = DetectFace()
while not rospy.is_shutdown():
detect_face.pub.publish(Bool(detect_face.detected))
print "main: ", detect_face.detected
rospy.sleep(0.5)
if __name__ == '__main__':
main()
|
mwhit74/moving_loads | ml/mlob.py | Python | mit | 30,601 | 0.005784 | # -*- coding: utf-8 -*-
"""The mlob module calculates the maximum effects of a vehicle on a simply
supported span including the pier reaction for two adjacent simply supported
spans of differing lengths.
"""
import pdb
def analyze_vehicle(axle_spacing, axle_wt, span_length1, span_length2,
num_user_... | ode in span 1
V_corr1 (list of floats): corresponding shear to maximum moment at each
analysis node in span 1
V_max2 (list of f | loats): maximum moment at each analysis node in span 2
M_corr22 (list of floats): corresponding moment to maximum shear at each
analysis node in span 2
M_max2 (list of floats): maximum moment at each analysis node in span 2
V_corr2 (list of floats): correspondin... |
openstack/manila | manila/tests/network/linux/test_ovs_lib.py | Python | apache-2.0 | 2,893 | 0 | # Copyright 2014 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 by applicable law or agre... |
class OVS_Lib_Test(test.TestCase):
"""A test suite to exercise the OVS libraries."""
def setUp(self):
super(OVS_Lib_Test, self).setUp()
self.BR_NAME = "br-int"
self.TO = "--timeout=2"
self.br = ovs_lib | .OVSBridge(self.BR_NAME)
self.execute_p = mock.patch('manila.utils.execute')
self.execute = self.execute_p.start()
def tearDown(self):
self.execute_p.stop()
super(OVS_Lib_Test, self).tearDown()
def test_reset_bridge(self):
self.br.reset_bridge()
self.execute.ass... |
timj/scons | test/update-release-info/update-release-info.py | Python | mit | 7,263 | 0.014457 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | It doesn't matter what goes here...
""")
pave_write(SConstruct, """
month_year = 'March 1945'
copyright_years = '2001, 2002, 2003, 2004, 2005, 2006, 2007'
default_version = '0.98.97'
""")
pave_write(README, """
These files are a part of 33.22.11:
scon | s-33.22.11.tar.gz
scons-33.22.11.win32.exe
scons-33.22.11.zip
scons-33.22.11.rpm
scons-33.22.11.deb
scons-33.22.11.beta.20012122112.suffix
""")
pave_write(TestSCons, """
copyright_years = Some junk to be overwritten
default_version = More junk
python_version_unsupported = Yep, ... |
MLnick/spark | python/pyspark/sql/tests.py | Python | apache-2.0 | 110,593 | 0.002297 | # -*- encoding: utf-8 -*-
#
# Licensed to the Apache Soft | ware Fou | ndation (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 this file except in compliance with
#... |
Xarthisius/girder | girder/api/v1/user.py | Python | apache-2.0 | 19,521 | 0.000922 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... | ending a valid one.
if not user:
authHeader = cherrypy.request.headers.ge | t('Girder-Authorization')
if not authHeader:
authHeader = cherrypy.request.headers.get('Authorization')
if not authHeader or not authHeader[0:6] == 'Basic ':
raise RestException('Use HTTP Basic Authentication', 401)
try:
credentials ... |
pcmoritz/ray-1 | rllib/examples/partial_gpus.py | Python | apache-2.0 | 152 | 0 | # File | has been renamed.
raise DeprecationWarning("This file has been renamed to `fractional_gpus.py` "
| "in the same folder!")
|
eadgarchen/tensorflow | tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver_test.py | Python | apache-2.0 | 5,570 | 0.003232 | # 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 applicable ... | ture__ import print_function
from tensorflow.contrib.cluster_resolver.python.training.tpu_cluster_resolver import TPUClusterResolver
from tensorflow.python.platform import tes | t
from tensorflow.python.training import server_lib
mock = test.mock
class MockRequestClass(object):
def __init__(self, name, tpu_map):
self._name = name
self._tpu_map = tpu_map
def execute(self):
if self._name in self._tpu_map:
return self._tpu_map[self._name]
else:
raise KeyError... |
mfem/PyMFEM | mfem/_par/geom.py | Python | bsd-3-clause | 22,071 | 0.004621 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# 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 as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
POINT = _geom.Geometry_POINT
SEGMENT = _geom.Geometry_SEGMENT
TRIANGLE = _geom.Geometry_TRIANGLE
SQUARE = _geom.Geometry_SQUARE
TETRAHEDRON = _geom.Geometry_TETRAHEDRON
CUBE = _geom.Geometry_CUBE
PRISM = _geom.Geometry_PRISM
PYRAMID = _geom.Geometry... | m.Geometry_NUM_GEOMETRIES
NumGeom = _geom.Geometry_NumGeom
MaxDim = _geom.Geometry_MaxDim
Name = property(_geom.Geometry_Name_get, _geom.Geometry_Name_set, doc=r"""Name : a(mfem::Geometry::NumGeom).p.q(const).char""")
def __init__(self):
r"""__init__(Geometry self) -> Geometry"""... |
jburel/openmicroscopy | examples/Training/python/Json_Api/Login.py | Python | gpl-2.0 | 3,163 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2017 University of Dundee & Open Microscopy Environment.
# All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
import requests
from Parse_OMERO_Properties import USERNAME, PASSWORD, OMERO_WEB_HOST, \
... | ersions = r.json()['data']
# use most recent version...
version = versions[-1]
# get the 'base' url
base_ur | l = version['url:base']
r = session.get(base_url)
# which lists a bunch of urls as starting points
urls = r.json()
servers_url = urls['url:servers']
login_url = urls['url:login']
projects_url = urls['url:projects']
save_url = urls['url:save']
schema_url = urls['url:schema']
# To login we need to get CSRF token
token_u... |
Staffjoy/client_python | staffjoy/resources/role.py | Python | mit | 1,528 | 0.000654 | from staffjoy.resource import Resource
from staffjoy.resources.worker import Worker
from staffjoy.resources.schedule import Schedule
from staffjoy.resources.shift import Shift
from staffjoy.resources.shift_query import ShiftQuery
from staffjoy.resources.recurring_shift import RecurringShift
class Role(Resource):
... | ions/{location_id}/roles/{role_id}"
ID_NAME = "role_id"
def get_workers(self, **kwargs):
return Worker.get_all(parent=self, **kwargs)
def get_worker(self, id=id):
return Worker.get(parent=self, id=id)
def create_worker(self, **kwargs):
return Worker.create(parent=self, **kwarg... | hedule.get(parent=self, id=id)
def get_shifts(self, **kwargs):
return Shift.get_all(parent=self, **kwargs)
def get_shift(self, id):
return Shift.get(parent=self, id=id)
def create_shift(self, **kwargs):
return Shift.create(parent=self, **kwargs)
def get_shift_query(self, **kw... |
code-for-india/sahana_shelter_worldbank | controllers/org.py | Python | mit | 10,621 | 0.005932 | # -*- coding: utf-8 -*-
"""
Organization Registry - Controllers
"""
module = request.controller
resourcename = request.function
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
# -----------------------------------------------------------------------------
def index(... | ultiple Controllers | for unified menus
return s3db.org_organisation_controller()
# -----------------------------------------------------------------------------
def org_search():
"""
Organisation REST controller
- limited to just search_ac for use in Autocompletes
- allows differential access permissions
... |
rfreiberger/Automate-the-Boring-Stuff | ch15/countdown.py | Python | bsd-2-clause | 317 | 0.0347 | #! python3
# countdown.py - A simple countdown script.
import time, subprocess
timeLeft = 60
while | timeLeft > 0:
print(timeLeft, end='')
time.sleep(1)
timeLeft = t | imeLeft - 1
# TODO: At the end of the countdown, play a sound file.
subprocess.Popen(['start', 'alarm.wav'], shell=True)
|
hufeiya/leetcode | python/73_Set_Matrix_Zeroes.py | Python | gpl-2.0 | 1,004 | 0.002988 | class Sol | ution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
width,height = len(matrix[0]),len(matrix)
for i in xrange(height):
foundzero = False
for j in... | if matrix[i][j] == 0:
foundzero = True
matrix[i][j] = float("inf")
if not foundzero:
continue
for j in xrange(width):
if matrix[i][j] != float("inf"):
matrix[i][j] = 0
for i in xrange(width):
... |
syoamakase/Re-ROS | re_environments/src/soccer_PK/soccer_PK_reward.py | Python | apache-2.0 | 1,763 | 0.003971 | #!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
import numpy as np
import soccer_PK.utils
rospy.init_node("reward")
pub = rospy.Publisher("reward", Float32, queue_size=10)
rate = rospy.Rate(3)
rospy.wait_for_service('/gazebo/get_model_state')
soccer_PK.utils.reset_world()
# intial postion
ball_p... | ginfo("GOAL!!!")
# | save log file ($HOME/.ros/)
f = open('episode_result.log', 'a')
f.write('episode'+str(episode)+': 4.5\n')
f.close()
# reset
episode += 1
reward = 10
done = True
rospy.set_param("reward_value",[reward, done])
tic ... |
wyrdmeister/OnlineAnalysis | OAGui/src/Control/Ui/Ui_OAMultiplot.py | Python | gpl-3.0 | 6,385 | 0.002819 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/media/Home/Documents/SoftProjects/LDM/OAGui/src/Control/Ui/OAMultiplot.ui'
#
# Created: Tue Apr 16 14:32:36 2013
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, Qt... | ry(QtCore.QRect(10, 130, 131, 27))
self.plot_hist2d.setObjectName(_fromUtf8("plot_hist2d"))
self.zmin_slider = QtGui.QSlider(self.control_frame)
self.zmin_slider.setGeometry(QtCore.QRect(10, 270, 131, 29))
self.zmin_slider.setOrientation(QtCore.Qt.Horizontal)
self.zmin_slider.set... | tf8("zmin_slider"))
self.zmax_slider = QtGui.QSlider(self.control_frame)
self.zmax_slider.setGeometry(QtCore.QRect(10, 320, 131, 29))
self.zmax_slider.setProperty("value", 99)
self.zmax_slider.setOrientation(QtCore.Qt.Horizontal)
self.zmax_slider.setObjectName(_fromUtf8("zmax_sli... |
ckc6cz/osf.io | tests/test_sanitize.py | Python | apache-2.0 | 2,081 | 0.002883 | import unittest
from nose.tools import * # flake8: noqa
from website.util import sanitize
class TestSanitize(unittest.TestCase):
def test_escape_html(self):
assert_equal(
sanitize.clean_tag('<script> evil code </script>'),
'<script> evil code </script>',
)
... | )
def test_safe_json(self):
"""Add escaping of forward slashes, but only where string literal contains closing markup"""
assert_equal(
sanitize.safe_json("I'm a string with / containing </closingtags>"),
| '"I\'m a string with / containing <\\/closingtags>"'
)
|
SuperV1234/scelta | conanfile.py | Python | mit | 777 | 0.003861 | from conans import ConanFile, tools, CMake
import os
class SceltaConan(ConanFile):
name = "scelta"
version = "0.1"
| url = "https://github.com/SuperV1234/scelta.git"
build_policy = "missing"
settings = "os", "compiler", "build_type", "arch"
def source(self):
self.run("git clone https://github.com/SuperV1234/scelta.git")
self.run("cd scelta && git checkout v0.1 && git submodule update --init")
def bu... | uild . %s" % cmake.build_config)
def package(self):
self.copy("*.hpp", dst="include", src="scelta/include")
def package_info(self):
self.info.header_only()
|
Ever-Never/smalisca | smalisca/controller/controller_parser.py | Python | mit | 10,504 | 0.000476 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------
# File: controller/controller_parser.py
# Created: 2015-01-17
# Purpose: Controll commandline arguments for parsing files
#
# Copyright
# ------------------------------------... | ir(dirpath)) and (depth == self.depth):
| log.info("Adding %s to list" % dirpath)
dirs_list.append(dirpath)
# Collect files
for filename in files:
filepath = os.path.join(root, filename)
if os.path.isfile(filepath):
file_list.append(filepath)
... |
Dlyma/keras-plus | keras/datasets/stock.py | Python | mit | 1,315 | 0.008365 | # -*- coding: utf-8 -*-
import cPickle
import sys, os
import numpy as np
# written by zhaowuxia @ 2015/5/22
# used for generate datasets for the adding problem
def generate_data(pkl_path, T, norm):
dataset = []
for f in os.listdir(pkl_path):
data = cPickle.load(open(os.path.join(pkl_path, f), 'rb'))
... | a)
dataset = np.array(dataset) #[sz, T, nfea]
mins = []
maxs = []
if norm == 'minmax':
mins = dataset.min(axis=1, keepdims=True)
maxs = dataset.max(axis=1, keepdims=True) + 1e-4
dataset = (dataset-mins.repeat(T+1, 1)) / np.repeat(maxs - mins, T+1, 1)
dataset[dataset>... | += np.random.random(dataset.shape)/100
X = dataset[:, :T, :]
Y = dataset[:, -1, :]
return (X, Y, mins, maxs)
def load_data(pkl_path, T, path='stock.pkl', norm='minmax'):
data = []
if not os.path.exists(path):
print(path, 'not exists', T)
data = generate_data(pkl_path, T, norm)
... |
robin900/sqlalchemy | test/orm/inheritance/test_basic.py | Python | mit | 94,636 | 0.005653 | import warnings
from sqlalchemy.testing import eq_, is_, assert_raises, assert_raises_message
from sqlalchemy import *
from sqlalchemy import exc as sa_exc, util, event
from sqlalchemy.orm import *
from sqlalchemy.orm.util import instance_str
from sqlalchemy.orm import exc as orm_exc, attributes
from sqlalchemy.testing... | :
"""deals with inheritance and one-to-many relationships"""
@classmethod
def define_tables(cls, metadata):
global foo, bar, blub
foo = Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincr | ement=True),
Column('data', String(20)))
bar = Table('bar', metadata,
Column('id', Integer, ForeignKey('foo.id'), primary_key=True),
Column('bar_data', String(20)))
blub = Table('blub', metadata,
Column('id', Integer, ForeignKey('bar.id'), primary_key=Tr... |
public-ink/public-ink | server/appengine/lib/graphql_relay/connection/arrayconnection.py | Python | gpl-3.0 | 4,642 | 0.00237 | from promise import Promise
from ..utils import base64, unbase64, is_str
from .connectiontypes import Connection, PageInfo, Edge
def connection_from_list(data, args=None, **kwargs):
'''
A simple function that accepts an array and connection arguments, and returns
a connection object for use in GraphQL. I... | ')
if list_slice_length is None:
list_slice_length = len(list_slice)
slice_end = slice_start + list_slice_length
before_offset = | get_offset_with_default(before, list_length)
after_offset = get_offset_with_default(after, -1)
start_offset = max(
slice_start - 1,
after_offset,
-1
) + 1
end_offset = min(
slice_end,
before_offset,
list_length
)
if isinstance(first, int):
... |
shiftcontrol/UnityOpenCV | opencv/tests/swig_python/highgui/size_bmp32.py | Python | gpl-3.0 | 739 | 0.016238 | #! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of an .avi file containing uncompressed 32bit Bitmap frames. |
"""
# name if this test and it's requirements
TESTNAME = "size_bmp32"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# na... | create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
|
mancoast/CPythonPyc_test | fail/301_test_decimal.py | Python | gpl-3.0 | 53,155 | 0.006095 | # Copyright (c) 2004 Python Software Foundation.
# All rights reserved.
# Written by Eric Price <eprice at tjhsst.edu>
# and Facundo Batista <facundo at taniquetil.com.ar>
# and Raymond Hettinger <python at rcn.com>
# and Aahz (aahz at pobox.com)
# and Tim Peters
"""
These are the test cases for the Decim... | TH or
context.Emax > DEC_MAX_MATH or
-context.Emin > DEC_MAX_MATH):
return True
if not v._is_special an | d v and (
len(v._int) > DEC_MAX_MATH or
v.adjusted() > DEC_MAX_MATH or
v.adjusted() < 1-2*DEC_MAX_MATH):
return True
return False
class DecimalTest(unittest.TestCase):
"""Class which tests the Decimal class against the test cases.
Changed for unittest.
"""
def setUp... |
jpbarrette/moman | finenight/python/iadfaTest.py | Python | mit | 146 | 0.013699 | from iadfa import | Inc | rementalAdfa
f = ["append", "appendice", "bappend"]
fsa = IncrementalAdfa(f, sorted = True)
fsa.graphVizExport("test.dot")
|
johnnyliu27/openmc | openmc/plotter.py | Python | mit | 38,526 | 0.000182 | from numbers import Integral, Real
from itertools import chain
import string
import numpy as np
import openmc.checkvalue as cv
import openmc.data
# Supported keywords for continuous-energy cross section plotting
PLOT_TYPES = ['total', 'scatter', 'elastic', 'inelastic', 'fission',
'absorption', 'capture... | TY_MT],
'slowing-down power': [2] + _INELASTIC + [XI_MT],
'damage': [444]}
# Operations to use when combining MTs the first np.add is used in reference
# to zero
PLOT_TYPES_OP = {'total': (np.add,),
'scatter': (np.add,) * (len(PLOT_TYPES_MT['scatter']) - 1),
... | 'absorption': (),
'capture': (), 'nu-fission': (),
'nu-scatter': (np.add,) * (len(PLOT_TYPES_MT['nu-scatter']) - 1),
'unity': (),
'slowing-down power':
(np.add,) * (len(PLOT_TYPES_MT['slowing-down power']) - 2) + (np.multiply,),
... |
KiChjang/servo | tests/wpt/web-platform-tests/tools/manifest/manifest.py | Python | mpl-2.0 | 18,236 | 0.001206 | import io
import os
import sys
from atomicwrites import atomic_write
from copy import deepcopy
from multiprocessing import Pool, cpu_count
from six import ensure_text
from . import jsonlib
from . import vcs
from .item import (ConformanceCheckerTest,
CrashTest,
ManifestItem,
... | assert self.tests_root is not None
source_file = SourceFile(self.tests_root,
path,
self.url_base,
file_hash)
hash_changed = False # type: bool
... | None:
file_hash = source_file.hash
remaining_manifest_paths.remove(path_parts)
old_type = types[path_parts]
old_hash = data[old_type].hashes[path_parts]
if old_hash != file_hash:
hash_changed ... |
joansalasoler/auale | src/auale/gui/actors/label.py | Python | gpl-3.0 | 3,526 | 0 | # -*- coding: utf-8 -*-
# Aualé oware graphic user interface.
# Copyright (C) 2014-2020 Joan Sala Soler <contact@joansala.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... | ository import GObject
from gi.repository import Pango
from gi.repository import PangoCairo
class Label(Clutter.Canvas):
"""Draws a canvas containing some text"""
__gtype_name__ = 'Label'
def __init__(self):
super(Label, self).__init__()
self._markup = ''
self._font = Pango.font... | ow_color = (0.10, 0.10, 0.10, 1.0)
self._text_color = (1.00, 1.00, 1.00, 1.0)
self.connect('draw', self.on_draw_request)
def get_markup(self):
"""Current text to display"""
return self._markup
def set_color(self, red, green, blue, alpha=1.0):
"""Color for the label's t... |
plotly/python-api | packages/python/plotly/plotly/validators/parcoords/dimension/_tickvals.py | Python | mit | 473 | 0.002114 | import _plotly_utils.basevalidators
class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, pl | otly_name="tickvals", parent_name="parcoords.dimension", **kwargs
):
super(TickvalsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
role=kwargs.pop("role", "data"),
**kwa | rgs
)
|
karlnapf/kameleon-mcmc | kameleon_mcmc/experiments/scripts/glass_ard/glass_ard_ground_truth.py | Python | bsd-2-clause | 4,033 | 0.011654 | """
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.
Written (W) 2013 Heiko Strathmann
"""
from kameleon_mcmc.distribution.Gauss... | print "example:"
prin | t "python " + str(sys.argv[0]).split(os.sep)[-1] + " /nfs/nhome/live/ucabhst/kameleon_experiments/ 3"
exit()
experiment_dir_base = str(sys.argv[1])
n = int(str(sys.argv[2]))
# loop over parameters here
experiment_dir = experiment_dir_base + str(os.path.abspath(sys.argv[0])).split(... |
nkgilley/home-assistant | homeassistant/components/homekit/type_thermostats.py | Python | apache-2.0 | 25,247 | 0.00103 | """Class to hold all thermostat accessories."""
import logging
from pyhap.const import CATEGORY_THERMOSTAT
from homeassistant.components.climate.const import (
ATTR_CURRENT_HUMIDITY,
ATTR_CURRENT_TEMPERATURE,
ATTR_HUMIDITY,
ATTR_HVAC_ACTION,
ATTR_HVAC_MODE,
ATTR_HVAC_MODES,
ATTR_MAX_TEMP,
... | EMPERATURE,
CHAR_TEMP_DISPLAY_UNITS,
DEFAULT_ | MAX_TEMP_WATER_HEATER,
DEFAULT_MIN_TEMP_WATER_HEATER,
PROP_MAX_VALUE,
PROP_MIN_VALUE,
SERV_THERMOSTAT,
)
from .util import temperature_to_homekit, temperature_to_states
_LOGGER = logging.getLogger(__name__)
HC_HOMEKIT_VALID_MODES_WATER_HEATER = {"Heat": 1}
UNIT_HASS_TO_HOMEKIT = {TEMP_CELSIUS: 0, TEMP... |
KNCT-KPC/RapidHouse | rapidhouse/lib/ui.py | Python | mit | 3,916 | 0.035291 | # -*- coding: utf-8 -*-
from ..algorithm import ga
import parameter
import tune
import sys
import os
import signal
import time
class Ui(object):
"""
This class handle both the CUI and the GUI.
:param rc: a instance of the `rapidconfig.RapidConfig`.
"""
def __init__(self, rc):
self.tuner = None
self.seq = N... | core.
:param pop: a population that having the score.
:return: the score.
"""
self.__notice("Score", score, pop)
return score
def notice_best(self, best_score, pop):
"""
Call self.__notice() | , and return a best score.
:param best_score: the best score.
:param pop: a population that having the best score.
:return: the best score.
"""
self.__notice("Best", best_score, pop)
return best_score
def notice_debug(self, type, contents):
"""
Give notice for debugging.
:param str type: a ident... |
jerryz1982/neutron | neutron/plugins/openvswitch/agent/openflow/ovs_ofctl/br_tun.py | Python | apache-2.0 | 10,433 | 0 | # Copyright (C) 2014,2015 VA Linux Systems Japan K.K.
# Copyright (C) 2014,2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
# 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 t... | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import functools
import netaddr
from neutron.agent.common import... | ent.openflow.ovs_ofctl import ovs_bridge
from neutron.plugins.openvswitch.common import constants
class OVSTunnelBridge(ovs_bridge.OVSAgentBridge,
br_dvr_process.OVSDVRProcessMixin):
"""openvswitch agent tunnel bridge specific logic."""
# Used by OVSDVRProcessMixin
dvr_process_table... |
Bernardinhouessou/Projets_Autres | Python-Projets/Scripts/Algorithms-master/dp/bellman_ford.py | Python | mit | 1,115 | 0.020628 | """ The bellman ford algorithm for calculating single source shortest
paths - CLRS style """
graph = {
's' : {'t':6, 'y':7},
't' : {'x':5, 'z':-4, 'y':8 },
'y' : {'z':9, 'x':-3},
'z' : {'x':7, 's': 2},
'x' : {'t':-2}
}
INF = float('inf')
dist = {}
predecessor = {}
def initialize_single_source(gr... | , s):
if bellman_ford(graph, s):
return dist
return "Graph contains a negative cycle"
print get_distan | ces(graph, 's')
|
USC-ACTLab/pyCreate2 | pyCreate2/__init__.py | Python | mit | 96 | 0 | from .create2 import *
| from .factory import *
__all__ = ["FactoryCreate", "FactorySim | ulation"]
|
platformio/platformio | platformio/commands/org.py | Python | apache-2.0 | 4,758 | 0.001471 | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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... | are
# 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.
# pylint: disable=unused-argument
import json
import click
from tab... |
@click.group("org", short_help="Manage Organizations")
def cli():
pass
def validate_orgname(value):
return validate_username(value, "Organization name")
@cli.command("create", short_help="Create a new organization")
@click.argument(
"orgname", callback=lambda _, __, value: validate_orgname(value),
)
... |
isandlaTech/cohorte-devtools | qualifier/deploy/cohorte-home/repo/cohorte/composer/node/criteria/distance/history.py | Python | apache-2.0 | 7,358 | 0.000136 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Gathers components according to their history.
This algorithm is a test: it can be a memory hog
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0... | e in sorted(crash)))
ballot.append_against(candidate)
break
else:
# Not a crashing solution
preference.append((len(components), candidate))
# TODO: tweak vote preferences to reduce the number of moves
... | emgetter(0), reverse=True)
_logger.info("Vote preference for %s: %s",
component_name, ', '.join(item[1].name or "Neutral"
for item in preference))
# Vote
for _, candidate in preference:
ballo... |
PMEAL/OpenPNM | tests/unit/algorithms/TransientAdvectionDiffusionTest.py | Python | mit | 2,595 | 0.001156 | import openpnm as op
from numpy.testing import assert_allclose
class TransientAdvectionDiffusionTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[4, 3, 1], spacing=1.0)
self.geo = op.geometry.GenericGeometry(network=self.net,
pores=self... | ()
ws.clear()
if __name__ == '__main__':
t = TransientAdvectionDif | fusionTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print(f'Running test: {item}')
t.__getattribute__(item)()
|
shrimo/node_image_tools | node_core.py | Python | gpl-3.0 | 2,317 | 0.025896 | # Node image tools (core)
# Copyright 2013 Victor Lavrentev
import json, sys
from node_lib import *
from PIL import Image, ImageDraw, ImageFilter
import numpy
print '\nNode image tools (core) v01a\n'
# Read node file *.json
try:
file_node=sys.argv[1]
except:
print '->Error. No script'
sys.... | width, height = img.size
cached[node.name] = numpy.array(img)
| print 'cached->', node.file,'(',width, height,')'
if (node.type=='cc'):
cached[node.name]=CC_(cached[node.link],node.bright,node.contrast)
if (node.type=='size'):
cached[node.name]=size_(cached[node.link],node.size,width,height)
if (node.type=='rotate'):
cached[node.name]... |
deepmind/neural_testbed | neural_testbed/likelihood/utils_test.py | Python | apache-2.0 | 1,794 | 0.005017 | # python3
# pylint: disable=g-bad-file-header
# Copyright 2021 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... | d.
# See the License for the specific language governing permissions and
# limitations under the License.
# =================== | =========================================================
"""Tests for neural_testbed.likelihood."""
from absl.testing import absltest
from absl.testing import parameterized
import chex
import jax
import jax.numpy as jnp
from neural_testbed.likelihood import utils
class LogSumProdTest(parameterized.TestCase):
@p... |
smjurcak/csm | csmserver/work_units/inventory_work_unit.py | Python | apache-2.0 | 4,795 | 0.002294 | # =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# 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 sour... | ef | start(self, db_session, logger, process_name):
host = None
inventory_job = None
try:
inventory_job = db_session.query(InventoryJob).filter(InventoryJob.id == self.job_id).first()
if inventory_job is None:
logger.error('Unable to retrieve inventory job: %s... |
cloudnull/tribble-api | tribble/common/rpc.py | Python | gpl-3.0 | 3,626 | 0 | # =============================================================================
# Copyright [2013] [Kevin Carter]
# License Information :
# This software has no warranty, it is provided 'as is'. It is your
# responsibility to validate the behavior of the routines and its accuracy
# using the code provided. Consult the ... | 'port', 5672),
userid=RPC_CFG.get('userid', 'guest'),
password=RPC_CFG.get('password', 'guest'),
virtual_host=RPC_CFG.get('virtual_host', '/')
)
def excha | nge(conn):
"""Bind a connection to an exchange.
:param conn: ``object``
:return: ``object``
"""
return kombu.Exchange(
RPC_CFG.get('control_exchange', 'tribble'),
type='topic',
durable=RPC_CFG.get('durable_queues', False),
channel=conn.channel()
)
def declare_... |
ndtran/compassion-modules | sponsorship_tracking/migrations/1.2/pre-migration.py | Python | agpl-3.0 | 1,284 | 0.000779 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | #######################################################################
import logging
logger = logging.getLogger()
def rename_columns(cr, column_spec):
"""
Rename table columns. Taken from OpenUpgrade.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples con... | ("table %s, column %s: renaming to %s", table, old, new)
cr.execute('ALTER TABLE %s RENAME %s TO %s' % (table, old, new,))
cr.execute('DROP INDEX IF EXISTS "%s_%s_index"' % (table, old))
def migrate(cr, version):
if not version:
return
# rename field last_sds_state_ch... |
Lysxia/dissemin | notification/settings.py | Python | agpl-3.0 | 173 | 0 | from __future__ i | mport unicode_literals
notification_settings = {
# PostgreSQL backend with JSON fields
'STORAGE_BACKEND': 'no | tification.backends.DefaultBackend'
}
|
erudit/eruditorg | eruditorg/core/authorization/rules.py | Python | gpl-3.0 | 501 | 0.001996 | # -*- coding: utf-8 -*-
import rules
from rules.predicat | es import is_staff
from rules.predicates import is_superuser
from core.journal.predicates import is_journal_member
from .defaults import AuthorizationConfig as AC
from .predicates import HasAuthorization
# This permission | assume to use a 'Journal' object to perform the perm check
rules.add_perm(
"authorization.manage_authorizations",
is_superuser | is_staff | is_journal_member & HasAuthorization(AC.can_manage_authorizations),
)
|
wujuguang/motor | test/tornado_tests/test_motor_client.py | Python | apache-2.0 | 11,652 | 0.000086 | # Copyright 2012-2015 MongoDB, 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 writin... | foo')
def test_database_named_delegate(self):
self.assertTrue(
isinstance(self.cx.delegate, pymongo.mongo_client.MongoClient))
self. | assertTrue(isinstance(self.cx['delegate'],
motor.MotorDatabase))
@gen_test
def test_connection_failure(self):
# Assuming there isn't anything actually running on this port
client = motor.MotorClient('localhost', 8765, io_loop=self.io_loop,
... |
CantemoInternal/pyxb | tests/trac/test-trac-0218.py | Python | apache-2.0 | 1,347 | 0.012621 | # -*- | coding: utf-8 -*-
im | port logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="topLevel">
... |
DakRomo/2017Challenges | challenge_3/python/kar-moore/src/challenge3.py | Python | mit | 496 | 0.090726 | def maj_element(array):
maj = len(array)/2 #py | thon does flooring on int division
num_dict = {}
for num in array:
if num in num_dict:
num_dict[num] += 1
else:
num_dict[num] = 1
for element in num_dict:
if num_dict[element] >= maj:
return element
array = [2,2,3,7,5,7,7,7,4,7,2,7,4,5,6,7,
7,8,6... | maj_element(array)
b_array = [1,1,2,2,2,2,2]
print maj_element(b_array) |
tejaswi2492/pmip6ns3.13new | src/tools/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 172,830 | 0.014749 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | AD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_fr | om_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', impo... |
rdo-management/neutron | neutron/tests/unit/hyperv/test_hyperv_security_groups_driver.py | Python | apache-2.0 | 7,747 | 0 | # Copyright 2014 Cloudbase Solutions SRL
# 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 r... | self, mock_method):
fake_rule = self._create_security_rule()
mock_method.return_value = {
self._FAKE_PARAM_NAME: self._FAKE_PARAM_VALUE}
| self._driver._create_port_rules(self._FAKE_ID, [fake_rule])
self._driver._utils.create_security_rule.assert_called_once_with(
self._FAKE_ID, fake_param_name=self._FAKE_PARAM_VALUE)
def test_convert_any_address_to_same_ingress(self):
rule = self._create_security_rule()
actual ... |
mcgov/fishpaste | FileStats.py | Python | mit | 3,515 | 0.013656 | #!/usr/bin/python3
"""
FileStats object, abstraction to take in HTML and spit out all the stats and
stuff that we want.
ALso has a handy function for returning a tuple for instertion into SQL databases.
@author mgmcgove
"""
import os
import get_tags as gt
import stats_lib
import url_validator as url... | ist(set(self.outgoing_links))
for url in urls:
if url in deduped_links:
| #print( "removing",url )
deduped_links.remove(url)
else:
#print("%s wasn't in the set of links"%url)
pass
values = [self.hash, self.url, self.title, self.body, 0, self.outgoing_link_count, deduped_links, 0 , json.dumps(self.n_grams, sort_k... |
WarrenWeckesser/numpy | benchmarks/benchmarks/bench_avx.py | Python | bsd-3-clause | 4,701 | 0.008722 | from .common import Benchmark
import numpy as np
avx_ufuncs = ['sin',
'cos',
'exp',
'log',
'sqrt',
'absolute',
'reciprocal',
'square',
'rint',
'floor',
'ceil' ,
'tr... | uncname)
except AttributeError:
raise NotImplementedError()
N = 10000
self.arr = np.ones(stride*N, dtype)
def time_ufunc(self, ufuncname, stride, dtype):
self.f(self.arr[:: | stride])
avx_bfuncs = ['maximum',
'minimum']
class AVX_BFunc(Benchmark):
params = [avx_bfuncs, dtype, stride]
param_names = ['avx_based_bfunc', 'dtype', 'stride']
timeout = 10
def setup(self, ufuncname, dtype, stride):
np.seterr(all='ignore')
try:
self.f = g... |
scigghia/account-invoicing | account_invoice_validation_workflow/__openerp__.py | Python | agpl-3.0 | 1,645 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joël Grand-Guillaume (Camptocamp)
# Copyright 2010-2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pub... | # T | his 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 Affero General ... |
walterbender/turtle3D | TurtleArtActivity.py | Python | mit | 79,936 | 0.000851 | # -*- coding: utf-8 -*-
#Copyright (c) 2007, Playful Invention Company
#Copyright (c) 2008-14, Walter Bender
#Copyright (c) 2009-13 Raul Gutierrez Segales
#Copyright (c) 2012 Alan Aguiar
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (... | ivity.widgets import (ActivityToolbarButton, StopButton)
from sugar.graphics.toolbarbox import (ToolbarBox, ToolbarButton)
HAS_TOOLBARBOX = True
except ImportError:
HAS_TOOLBARBOX = False
from sugar.graphics.toolbutton import ToolButton
from sugar.graphics.radiotoolbutton import RadioToolButton
from sugar.g... | t style
from sugar.graphics.icon import Icon
from sugar.graphics.xocolor import XoColor
from sugar.datastore import datastore
from sugar import profile
import os
import glob
import tarfile
import subprocess
import ConfigParser
import shutil
import tempfile
try:
import gconf
HAS_GCONF = True
except ImportError:... |
holmes-app/holmes-api | holmes/validators/title.py | Python | mit | 2,893 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from holmes.validators.base import Validator
from holmes.utils import _
class TitleValidator(Validator):
@classmethod
def get_violation_definitions(cls):
return {
'page.title.not_found': {
'title': _('Page title not found'),
... | points=50
)
return
if title_count > 1:
self.add_violation(
key='page.title.multiple',
value={
| 'page_url': self.reviewer.page_url,
'title_count': title_count
},
points=50
)
elif max_title_size and len(title) > int(max_title_size):
self.add_violation(
key='page.title.size',
value={
... |
stvstnfrd/configuration | playbooks/callback_plugins/sqs.py | Python | agpl-3.0 | 6,158 | 0.001786 | # Copyright 2013 John Jarvis <john@jarv.org>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | n ['changed', 'failures', 'ok', 'processed', 'skipped']:
d[s] = getattr(stats, s)
self._send_queue_message(d, 'STATS')
def _send_queue_message(self, msg, msg_type):
| if self.enable_sqs:
from_start = time.time() - self.start_time
payload = {msg_type: msg}
payload['TS'] = from_start
payload['PREFIX'] = self.prefix
# update the last seen timestamp for
# the message type
self.last_seen_ts[msg_type] ... |
tedlaz/pyted | misthodosia/pyMisthodosia/src/tst.py | Python | gpl-3.0 | 11,303 | 0.045007 | #!/usr/bin/env python
#coding=utf-8
'''
Created on 06 Ιουν 2011
@author: tedlaz
'''
import functions as f
import decimal as decim
from datetime import datetime, date, time
class d():
def __init__(self,val=0, txt='',desc='',decimals=4):
self.decimals = decimals
self.val = f.dec(val,self.decimals)
... | return d(self.val+x,'','%s<%s> + %s' % (self.txt,self.val,x ))
elif isinstance(x,decim.Decimal):
return d(self.val+x,'','%s<%s> + %s' % (self.txt,self.val,x ))
elif isinstance(x,d):
return d(self.val+x.val,'','%s<%s> + %s<%s>' %(self.t | xt,self.val,x.txt,x.val))
else:
return d(0,'Error')
def __sub__(self,x):
if isinstance(x,int):
return d(self.val-x,'','%s<%s> - %s' % (self.txt,self.val,x ))
elif isinstance(x,decim.Decimal):
return d(self.val-x,'','%s<%s> - %s' % (self.txt,self.val,x ))
... |
erigones/esdc-ce | api/mon/backends/zabbix/__init__.py | Python | apache-2.0 | 379 | 0.002639 | from api.mon.backends.zabbix.monitor import Zabbi | x, get_zabbix, del_zabbix
from api.mon.backends.zabbix.server import ZabbixMonitoringServer
get_monitoring = get_zabbix
del_monitoring = del_zabbix
MonitoringBackendClass = Zabbix
MonitoringServerClass = ZabbixMonitoringServer
__all__ = ('get_monitoring', ' | del_monitoring', 'MonitoringBackendClass', 'MonitoringServerClass')
|
jujumo/gpsbip-configurator | source/task/path_tools_test.py | Python | mit | 2,315 | 0.000864 | #!/usr/bin/env python
import unittest
from os.path import realpath
from path_tools import create_filepath
class TestCreateFilepath(unittest.TestCase):
def test_identity(self):
original_filepath = realpath('E:/GoPro/2018-04-18/GH010926.MP4')
dest_filepath = create_filepath(original_filepath)
... | = realpath('C:/temp/GH010926.MP4')
dest_filepath = create_filepath(original_filepath, dest_dirpath='C:/temp')
dest_filepath = realpath(dest_filepath)
self.assertEqual(expected_filepath, dest_filepath)
def test_another_relative_dir(self):
original_filepath = realpath('E:/GoPro/2018-... | :/GoPro/', dest_dirpath='C:/temp')
dest_filepath = realpath(dest_filepath)
self.assertEqual(expected_filepath, dest_filepath)
if __name__ == '__main__':
unittest.main()
|
digling/cddb | datasets/Allen2007/raw/inventories.py | Python | gpl-3.0 | 838 | 0.002387 | from lingpy import *
from collections import defaultdict
invs = csv2list('inventories.tsv', strip_lines=False)
segments = defau | ltdict(dict)
langs = set()
for d, t, v, a, n in invs[1:]:
if a.strip():
allophone, context = a.split('/')
segments[allophone, t][d] = (v, context)
segments[v, t][d] = (a, n or 'X')
langs.add(d)
langs = sorted(langs)
with open('Allen2007.prf', 'w') as f:
f.write('GRAPHEMES\tTYPE\tAll | en2007\tCLPA\tSTRUCTURE\t'+'\t'.join(langs)+'\n')
for a, b in sorted(segments):
f.write('\t'.join([a, b, a, a, '']))
for lang in langs:
vals = segments[a, b].get(lang, ['', ''])
if vals[0] and vals[1]:
value = '/'.join(vals)
else:
v... |
gkc1000/pyscf | pyscf/nao/test/test_0100_fireball.py | Python | apache-2.0 | 441 | 0.013605 | from __future__ import print_function, division
import unittest, numpy as np
from pyscf.nao import mf
class KnowValues(unittest.TestCase):
def test_fireball(self):
""" Test computation of matrix elements of overlap after fireball """
sv | = mf(fireball="fireball.out", gen_pb=False)
s_ref = sv.hsx.s4_csr.to | array()
s = sv.overlap_coo().toarray()
#print(abs(s-s_ref).sum())
if __name__ == "__main__": unittest.main()
|
SurfasJones/djcmsrc3 | venv/lib/python2.7/site-packages/djangocms_link/forms.py | Python | mit | 1,320 | 0.00303 | from django.forms.models import ModelForm
from django.utils.translation import ugettext_lazy as _
from djangocms_link.models import Link
from cms.models import Page
from django.forms.widgets import Media
class LinkForm(ModelForm):
try:
from djangocms_link.fields import PageSearchField
page_link = ... | s'] + media._js
retur | n media
media = property(_get_media)
|
JaDogg/__py_playground | reference/ply-3.8/test/yacc_error7.py | Python | mit | 1,790 | 0.013966 | # -----------------------------------------------------------------------------
# yacc_error7.py
#
# Panic mode recove | ry test using deprecated functionality
# -----------------------------------------------------------------------------
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.yacc as yacc
from calclex import tokens
# Parsing rules
precedence = (
('left','PLUS','MINUS'),
('left','TIMES','DIVIDE... | ts : statements statement'
pass
def p_statements_1(t):
'statements : statement'
pass
def p_statement_assign(p):
'statement : LPAREN NAME EQUALS expression RPAREN'
print("%s=%s" % (p[2],p[4]))
def p_statement_expr(t):
'statement : LPAREN expression RPAREN'
print(t[1])
def p_expression_bin... |
xxjcaxx/openerp-learning-module2 | parking/__openerp__.py | Python | gpl-2.0 | 372 | 0.02957 | {
"name" : "parking",
"version" : "0.1",
"author" : "Castillo",
"website" | : "http://openerp.com",
"category" : "Unknown",
"description": """ Module for a parking """ | ,
"depends" : ['base'],
"init_xml" : [ ],
"demo_xml" : [ ],
"update_xml" : ['parking_view.xml'],
"installable": True
}
|
ArthurZey/toyproblems | projecteuler/0021_amicable_numbers.py | Python | mit | 1,028 | 0.013645 | #!/usr/bin/env python
'''
https://projecteuler.net/problem=20
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divi... | :
sum_of_divisors += possible_divisor
sum_of_divisors += int(n/possible_divisor)
return sum_of_divisors
sum_of_amicable_numbers = 0
for i in range(1, 10000):
if d(d(i)) == i and d(i) != i:
sum_of_amicable_numbers += i
prin | t(sum_of_amicable_numbers) |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/__init__.py | Python | gpl-3.0 | 46 | 0.021739 | ../ | ../../../share/pyshared/t | wisted/__init__.py |
NINAnor/sentinel4nature | Tree canopy cover/regression/GBRT_Hjerkinn_manual_FCLS.py | Python | gpl-2.0 | 8,852 | 0.0061 | # GBRT for Hjerkinn case study site
# Training data: manually digitized training areas, including water pixels
# Predictors: results of FCLS spectral unmixing
# Authors: Stefan Blumentrath
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble
from sklearn import datasets
from sklearn.utils i... | Case_Hjerkinn/regression/Hjerkinn_water_FCLS_GBRT_deviance.pdf',
'featureimportance': '/data/R/GeoSpatialData/Orthoimagery/Fenoscandia_Sentinel_2/temp_Avd15GIS/Case_Hjerkinn/regression/Hjerkinn_water_FCLS_GBRT_featureimportance.pdf',
'partialdependence': '/data/R/GeoSpatialData/Orthoimagery/Fenosc... | n/Hjerkinn_water_FCLS_GBRT_partial_dependence.pdf',
'crossval': '0.25',
'output': 'ForestCover_Hjerkinn_water_FCLS',
'spatial_term': None
}
cores = int(options['cores'])
spatial_term = options['spatial_term']
output = options['output']
deviance = options['devianc... |
Zanzibar82/streamondemand.test | servers_sports/iguide.py | Python | gpl-3.0 | 2,410 | 0.025726 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# streamondemand - XBMC Plugin
# Conector para iguide
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core impor... | r.info("data2="+data2)
'''
var token = "";
$.getJSON("http://www.iguide.to/serverfile.php?id=1422862766", function(json){
token = json.token;
setStream(token);
}); |
function setStream(token) {
jwplayer('dplayer').setup({
'id': 'dplayer',
'autostart': 'true',
'width': '730',
'height': '430',
'controlbar':'bottom',
'provider': 'rtmp',
'streamer': 'rtmp://live2.iguide.to/redirect',
'rtmp.tunneling':false,
'bufferLength':0.1,
'file': '0zznd3dk4sqr3xg.flv',
... |
metacloud/python-keystoneclient | keystoneclient/apiclient/exceptions.py | Python | apache-2.0 | 1,124 | 0 | # Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 Nebula, Inc.
# Copyright 2013 Alessio Ababilov
# 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
# ... | licable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Exception d... | warnings
from keystoneclient.exceptions import * # noqa
warnings.warn("The 'keystoneclient.apiclient.exceptions' module is deprecated "
"since v.0.7.1. Use 'keystoneclient.exceptions' instead of this "
"module.", DeprecationWarning)
|
suellenf/hearmecode | playtime/lesson2_pbj.py | Python | mit | 958 | 0.004175 | # Goal 1
bread = 4
pb = 3
jelly = 10
sandwich = 0
while bread >= 2 and pb >= 1 and jelly >= 1:
sandwich = sandwich + 1
print "I am making sandwich number {0}".format(sandwich)
bread = bread - 2
pb = pb - 1
jell | y = jelly - 1
p | rint "All done! I made {0} sandwich(es)".format(sandwich)
# Goal 2
bread = 10
pb = 10
jelly = 4
sandwich = 0
ran_out = [""]
while bread >= 2 and pb >= 1 and jelly >= 1:
sandwich = sandwich + 1
print "I am making sandwich number {0}".format(sandwich)
bread = bread - 2
pb = pb - 1
jell... |
EmreAtes/spack | var/spack/repos/builtin/packages/viennarna/package.py | Python | lgpl-2.1 | 2,706 | 0.002217 | ##############################################################################
# Copyright (c) 2013-2018, 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... | r to substantially speed up execution')
variant('perl', default=True, description='Build ViennaRNA with Perl interface')
variant('python', default=True, description='Build ViennaRNA with Py | thon interface')
depends_on('perl', type=('build', 'run'))
depends_on('python', type=('build', 'run'))
depends_on('libsvm')
depends_on('gsl')
def url_for_version(self, version):
url = 'https://www.tbi.univie.ac.at/RNA/download/sourcecode/{0}_x/ViennaRNA-{1}.tar.gz'
return url.forma... |
marioharper182/ComputationalMethodsFinance | Homework2/Options_American.py | Python | apache-2.0 | 1,728 | 0.004051 | __author__ = 'HarperMain'
import numpy as np
from scipy.stats import binom
class AmericanOption(object):
def __init__(self, strike, X, rate, volatility, T, n):
self.strike = strike
self.X = X
self.rate = rate
self.volatility = volatility
self.T = T
self.n = float(n)... | ))
d = np.exp((self.rate * h) - self.volatility * np.sqrt(h))
nodes = self.T+1
P = (np.exp(self.rate*h) - d) / (u - d)
Pc = 1-P
self.CallMatrix = []
self.PutMatrix = []
for j in range(0, T):
Call = []
Put = []
# jnodes = nodes... | llPayOff(spot, X) * binom.pmf(self.T - i, self.T, P)
putvar = self.PutPayOff(spot, X) * binom.pmf(self.T - i, self.T, Pc)
Call.append(callvar)
Put.append(putvar)
self.CallMatrix.append(Call)
self.PutMatrix.append(Put)
print('Loop Complete... |
7fever/script.pseudotv.live | utilities.py | Python | gpl-3.0 | 6,697 | 0.00881 | # Copyright (C) 2015 Kevin S. Graer
#
#
# This file is part of PseudoTV Live.
#
# PseudoTV 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 ver... | REAL_SETTINGS.s | etSetting("AT_Donor", "true")
REAL_SETTINGS.setSetting("COM_Donor", "true")
REAL_SETTINGS.setSetting("TRL_Donor", "true")
REAL_SETTINGS.setSetting("CAT_Donor", "true")
xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ("PseudoTV Live", "Donor Autoupdate Complete", 400... |
amitsaha/learning | python/search/find_median.py | Python | unlicense | 401 | 0.004988 | '''
Find the median element in an unsorted array
'''
import he | apq
def find_median(arr):
# O(n)
heapq.heapify(arr)
num_elements = len(arr)
if num_elements % 2 != 0:
return arr[(num_elements + 1)/2 - 1]
else:
return (arr[num_elements/2 - 1] + arr[num_elements/2 + 1 - 1])/2.0
assert find_median( | [1, -1, 2, 3, 4]) == 2
assert find_median([1, -1, 2, 3, 4, 5]) == 2.5
|
MrIliev/AIPY-Music-Player | AIPY.py | Python | apache-2.0 | 1,128 | 0.036348 | import sys
from PyQt4 import Qt
from PyQt4.phonon import Phonon
class AIPYbody():
# in the class body are all functionalities of the AIPY Music Player
# body will be one window from PyQT
def __init__ (self):
pass
def Display():
# used for showing the remaining time, or elapsed time of song, it is posible to ... | e visulations
pass
def PlayList():
# defines play list with files selected by user
pass
def PlayButton():
#button to start the music file, if there is not you will be able to choose one
pass
def PauseButton():
# button to pause the music file, can be together with play
pass
def StopButton():
# b... | xt song in playlist, if there is not starts same song again
pass
def PrevButton():
# button for previous song in playlist, if there is not starts the same song again
pass
def OnlineStreaming():
# button which opens new window to select source for online streaming
pass
def EQ():
# button which opens w... |
STiago/Python | Code/temperatures.py | Python | gpl-3.0 | 571 | 0.008757 | # Read inputs from Standard Input.
# Write outputs to Standard Output.
# Please, do not use fileinput module to read Standard Input.
import sys
try:
n = int(raw_input())
lis = raw_input().split()
except ValueError:
print "0 - Cannot process the data"
position = 0
less = 0
more = 0
s = map(int, lis)
... | .append(0)
s.sort()
# Position of 0
for i in range(0,n):
if s[i] == 0:
position = i
break
# Number close to 0
less = s[position-1]
more = s[position+1]
|
if abs(more) <= abs(less):
print more
else:
print less
|
dbarrosop/pySIR | pySIR/call.py | Python | apache-2.0 | 1,069 | 0.001871 | import requests
import json
import sir_exceptions
class Call:
def __init__(self, url, verify_ssl, method, params=None):
if method == 'GET':
r = requests.get(url, params=params, verify=verify_ssl)
elif method == 'POST | ':
r = requests.post(url, json=params, verify=verify_ssl)
elif method == 'PUT':
r = requests.put(url, json=params, verify=verify_ssl)
elif method == 'DELETE':
r = requests.delete(url | , verify=verify_ssl)
if r.status_code != 200:
raise sir_exceptions.WrongCallException(r.status_code, r.content)
elif r.headers['content-type'] != 'application/json':
raise sir_exceptions.WrongEndpointException('Wrong content-type: {}', format(r.headers['content-type']))
... |
GoogleCloudPlatform/covid-19-open-data | src/scripts/cloud_error_processing.py | Python | apache-2.0 | 3,450 | 0.003768 | import os
import requests
import sys
from google.cloud import firestore
from googleapiclient.discovery import build
from google.cloud import secretmanager
# Add our library utils to the path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from lib.constants import ISSUES_API_URL
from l... | group_id = error_group["group"]["groupId"]
if int(error_group["count"]) < 2:
# Don't add one-off errors to the db
continue
doc = errors_db.document(group_id)
if not doc.get().exists and error_group["group"]["resolutionStatus"] == "OPEN":
try:
... | github(error_group)}
]
error_group["group"]["resolutionStatus"] = "ACKNOWLEDGED"
except ConnectionError:
# Could not create an issue
# Don't add it to our known errors db, we can retry on the next scheduled job.
continue
... |
Bam4d/Roxxy | tools/hammer_test.py | Python | gpl-3.0 | 335 | 0.01791 | import requests
import json
import time
if __name__ == '__main__':
count = 0
#Non-threaded test
for i in range(0,1000):
res = requests.get('http://localhost:8055/?url=https://magic.import.io')
count += 1
print count
time.sleep | (0.1)
if count%1000 == 0:
| print count
|
GuillaumeSeren/linux | scripts/gdb/linux/cpus.py | Python | gpl-2.0 | 4,543 | 0 | #
# gdb helper commands and functions for Linux kernel debugging
#
# per-cpu tools
#
# Copyright (c) Siemens AG, 2011-2013
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
from linux import tasks, utils
MAX_CPUS = 4096
def get_cu... | gdb.events, 'new_objfile'):
| gdb.events.new_objfile.connect(cpu_mask_invalidate)
bits_per_entry = mask[0].type.sizeof * 8
num_entries = mask.type.sizeof * 8 / bits_per_entry
entry = -1
bits = 0
while True:
while bits == 0:
entry += 1
if entry == num_entries:
return
... |
deeplearning4j/deeplearning4j | jumpy/jumpy/spark/fast_impl.py | Python | apache-2.0 | 4,802 | 0.002707 | ################################################################################
# Copyright (c) 2015-2018 Skymind, Inc.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless... | ######################################################
import numpy as np
from ..java_classes import ArrayList
from ..java_classes import ArrayD | escriptor as getArrayDescriptor
from ..java_classes import DatasetDescriptor as getDatasetDescriptor
from ..java_classes import DataType
from ..java_classes import spark_utils as get_spark_utils
from ..java_classes import JDataset
from ..ndarray import array
from .utils import np2desc
from .utils import py2j_ds_desc
fr... |
lyst/shovel | src/shovel/config.py | Python | apache-2.0 | 138 | 0 | # -*- | coding: utf-8 -*-
class Config(object):
def __init__(self, bucket, root):
self.bucket = bucket
self.root = root | |
chainer/chainercv | chainercv/links/model/fpn/misc.py | Python | mit | 974 | 0 | from __future__ import division
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
return F.huber_loss(x, t, beta, reduce='no') / beta
# to avoid out of memory
def argsort(x):
xp = c... | eturn y
else:
return cuda.to_gpu(y)
def scale_img(img, min_size, max_size):
"""Process image."""
_, H, W = img.shape
scale = min_size / min(H, W)
if scale * max(H, W) > max_size:
scale = max_ | size / max(H, W)
H, W = int(H * scale), int(W * scale)
img = transforms.resize(img, (H, W))
return img, scale
|
steelion/python-tools | mao/toolbox/__init__.py | Python | mit | 27 | 0 | __aut | hor__ = 'Ofner Mari | o'
|
abtreece/ansible | lib/ansible/plugins/strategy/__init__.py | Python | mit | 44,580 | 0.003993 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 Foundation, either version 3 of the License, or
# (at your option) an... | ining(self, play):
return [host for host in self._inventory.get_hosts(play.hosts)
if host.name not in self._tqm._failed_hosts and host.name not in self._tqm._unreachable_hosts]
def get_failed_hosts(self, play):
return [host for host in self._inventory.get_hosts(play.hosts) if host.n... | vars, play):
'''
Base class method to add extra variables/information to the list of task
vars sent through the executor engine regarding the task queue manager state.
'''
vars['ansible_current_hosts'] = [h.name for h in self.get_hosts_remaining(play)]
vars['ansible_fail... |
asmacdo/pulp-automation | tests/consumer_agent_tests/test_09_consumer.py | Python | gpl-2.0 | 9,939 | 0.008452 | import unittest
from pulp_auto.consumer.consumer_class import (Consumer, Binding, Event, ConsumersApplicability)
from pulp_auto.task import Task
from pulp_auto.pulp import Request
from pulp_auto import path_join
from tests.pulp_test import (ConsumerAgentPulpTest, agent_test)
class TestConsumer(ConsumerAgentPulpTest... | "consumer_criteria": {"filters": {"id": {"$in": ["sunflower", "voyager"]}}}
}
)
self.assertPulp(code=202)
Task.wait_for_report(self.pulp, response)
# TODO: assert applicability tags in task response
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.