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 |
|---|---|---|---|---|---|---|---|---|
likelyzhao/mxnet | example/kaggle-ndsb1/training_curves.py | Python | apache-2.0 | 1,093 | 0.010064 | ## based on https://github.com/dmlc/mxnet/issues/1302
## Parses the model fit log file and generates a train/val vs epoch plot
import matplotlib.pyplot as plt
import numpy as np
import re
import argparse
parser = argparse.ArgumentParser(description='Parses log file and generates train/val curves')
parser.add_argument | ('--log-file', type=str,default="log_tr_va",
help='the path of log file')
args = parser.parse_args()
TR_RE = re.compile('.*?]\sTrain-accuracy=([\d\.]+)')
VA_RE = re.compile('.*?]\sValidation-accuracy=([\d\.]+)')
log = open(args.log_file).read()
log_tr = [float(x) for x in TR_RE.findall(log)]
log... | ', color="r",
label="Train accuracy")
plt.plot(idx, log_va, 'o', linestyle='-', color="b",
label="Validation accuracy")
plt.legend(loc="best")
plt.xticks(np.arange(min(idx), max(idx)+1, 5))
plt.yticks(np.arange(0, 1, 0.2))
plt.ylim([0,1])
plt.show()
|
lastship/plugin.video.lastship | resources/lib/sources/de/moviedream.py | Python | gpl-3.0 | 5,572 | 0.005205 | # -*- coding: UTF-8 -*-
"""
Lastship Add-on (C) 2019
Credits to Lastship, Placenta and Covenant; our thanks go to their creators
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, e... | lic Licen | se for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# Addon Name: Lastship
# Addon id: plugin.video.lastship
# Addon Provider: Lastship
import re
import urllib
import urlparse
import hashlib, base64
i... |
wgrose/leanto | google/appengine/api/datastore.py | Python | apache-2.0 | 52,965 | 0.006117 | #!/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... | etRequest()
req.key_list().extend([key._Key__reference for key in keys])
_MaybeSetupTransaction(req, keys)
resp = datastore_pb.GetResponse()
try:
apiproxy_stub_map.MakeSyncCall('datastore_v3', 'Get', req | , resp)
except apiproxy_errors.ApplicationError, err:
raise _ToDatastoreError(err)
entities = []
for group in resp.entity_list():
if group.has_entity():
entities.append(Entity._FromPb(group.entity()))
else:
entities.append(None)
if multiple:
return entities
else:
if entities[... |
alvations/USAAR-SemEval-2015 | task02-USAAR-SHEFFIELD/modely.py | Python | mit | 684 | 0.010234 | #!/usr/bin/env python -*- coding: utf-8 -*-
import math
import cPickle as pickle
import numpy as np
from sklearn.svm import SVR
from sklearn.linear_model import BayesianRidge
x = np.loadtxt('x.asiya.train')[:,np.newaxis]
y = np.loadtxt('y.asiya.train')
x_test = np.loadtxt('x.asiya.test')[:,np.newaxis]
br = pickle... | output)
#fout = open('modely.10.output', | 'w')
for line in zip(*runs):
avg =sum(line)/len(line)
if avg > 5:
avg = 5.0
elif avg < 0:
avg = 0.0
print str(float(avg))[:6]
#fout.write(str(float(avg))[:6]+'\n')
|
vojtatom/planets | sun.py | Python | gpl-3.0 | 3,499 | 0.041155 | from random import random, randint
from PIL import Image, ImageDraw, ImageFont
import perlin
def draw_background(setup) :
canvas = setup['canvas']
image = Image.new('RGBA', canvas, tuple(setup['color']['back']))
background = Image.new('RGBA', canvas, (0,0,0,0))
draw = ImageDraw.Draw(background)
stars = [[ int(p... | delta = [ (x - center[0]) / (samples * density), (y - center[1]) / (samples * density) ]
color = list_of_pixels[x + y * width]
illumination = 1
for m in range(samples) :
tc = [ tc[0] - delta[0], tc[1] - delta[1]]
add_color = tuple( illumina | tion * x for x in list_of_pixels[int(tc[0]) + int(tc[1]) * width] )
illumination *= decay
color = tuple( x + y for x, y in zip(color, add_color))
new_image.append(tuple(int(x) for x in color))
image = Image.new(sun_image.mode, sun_image.size)
image.putdata(new_image)
return image
def draw_sun(imag... |
markjones112358/homeDisplay | interface.py | Python | mit | 3,307 | 0.02661 | from flask import Flask, request, send_from_directory, redirect, Response
import pprint
import json
import modules.weather
import time
import os
app = Flask(__name__)
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
@app.route('/css/<path:path>')
de... | ication/json')
# return send_from_directory('http', 'weather.json')
else:
print("Cached weather expired, returning fresh download")
return Response(json.dumps(download_weather()), mimetype='application/json')
else:
print("No cache exists, returning fresh download")
return Response(json.dumps(download_w... | rint("Returning shopping.json from directory")
return send_from_directory('http', 'shopping.json')
else:
with open('http/shopping.json', 'w') as f:
# json.dumps([], f)
f.write("[]")
print("Returning empty shopping.json file")
return Response([], mimetype='application/json')
def load_shopping():
print("... |
iain-peddie/well-behaved-python | tests/WellBehavedPythonTests/Discovery/ModuleExaminerTests.py | Python | gpl-3.0 | 3,114 | 0.006744 | #!/usr/bin/env python3
# Copyright 2013 Iain Peddie inr314159@hotmail.com
#
# This file is part of WellBehavedPython
#
# WellBehavedPython 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 v... |
from WellBehavedPython.Discovery.ModuleExaminer import ModuleExaminer
class Mo | duleExaminerTests(TestCase):
def test_examiner_can_find__only_class_in_simple_module(self):
# Where
examiner = ModuleExaminer('WellBehavedPythonTests.Samples.SampleModule');
# When
classes = examiner.listAllClasses()
# The classes have been imported
# Then
... |
calaldees/libs | python3/calaldees/dictset.py | Python | gpl-3.0 | 2,385 | 0.005451 |
def subdict(d, keys):
return {k: v for k, v in d.items() if k in keys}
# consider https://docs.python.org/3/library/functools.html#functools.total_ordering
# just __eq__ and __lt__
#@total_ordering
class DictSetOperationsMixin():
"""
I was disappointed with pythons builtin support for set operations with ... | return {**a, **b} # TODO return DictSet?
def __iadd__(self, other):
self.update(other)
return self
def __le__(self, other):
"""
>>> aa = DictSet({'a': 1, 'b': 2, 'c': 3})
>>> bb = DictSet({'c': 3, 'd': 4, 'e': 5})
>>> cc = DictSet({'a': 1})
>>> a... | True
>>> aa <= aa
True
"""
return DictSetOperationsMixin.__ge__(other, self)
def __lt__(self, other):
return DictSetOperationsMixin.__le__(self, other) and (len(self) < len(other))
def __ge__(self, other):
"""
>>> DictSetOperationsMixin.__ge__(
...... |
joeryan/hardway | ex9.py | Python | mit | 337 | 0 | days = "Mon Tue W | ed Thur Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something foine on here.
With the three double quotes.
W | e'll be able to type as much as we want.
Even 4 lines if we want, or 5 or 6.
"""
|
simpkins/amass | src/amass/metadata/merge/cli_chooser.py | Python | gpl-3.0 | 2,152 | 0 | #!/usr/bin/python -tt
#
# Copyright (c) 2011, Adam Simpkins
#
import sys
from .chooser import ChooserBase
class CliChooser(ChooserBase):
def __init__(self, album, threshold):
ChooserBase.__init__(self, album)
self.confidenceThreshold = threshold
def write(self, msg):
if isinstance(ms... | lf.album.getFirstTrack().fields[field_name]
self.writeField('--', field)
self.writeln('* Track Fields:')
for track in self.album.itertracks():
for field in track.fields.itervalues():
if not field.candidates:
continue
if fi... | e
self.writeField(track.number, field)
# FIXME: Prompt the user for which fields should be edited
|
ask/celery | celery/contrib/rdb.py | Python | bsd-3-clause | 4,702 | 0.000638 | # -*- coding: utf-8 -*-
"""
celery.contrib.rdb
==================
Remote debugger for Celery tasks running in multiprocessing pool workers.
Inspired by http://snippets.dzone.com/posts/show/7248
**Usage**
.. code-block:: python
from celery.contrib import rdb
from celery.task import task
@task
def ad... | else:
raise Exception(
| "%s: Could not find available port. Please set using "
"environment variable CELERY_RDB_PORT" % (self.me, ))
def say(self, m):
self.out.write(m + "\n")
def _close_session(self):
self.stdin, self.stdout = sys.stdin, sys.stdout = self._prev_handles
self._handle... |
masci/toodo | toodo/appengine_config.py | Python | unlicense | 85 | 0 | import sys
imp | ort os
sys.path.append(os.path.join(os.path.dirname( | __file__), 'lib'))
|
rveciana/BasemapTutorial | code_examples/utilities/makegrid.py | Python | cc0-1.0 | 675 | 0.017778 | from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure(figsize=(9, 3))
map = Basemap(width=12000000,height=8000000,
resolution='l',pr | ojection='stere',
lat_ts=50,lat_0=50,lon_0=-107.)
lons, lats, x, y = map.makegrid(30, 30, returnxy=True)
ax = fig.add_subplot(121)
ax.set_title('The regular grid')
map.scatter(x, y, marker='o')
map.drawcoastlines()
ax = fig.add_subplot(122)
ax.set_title('Projection changed')
map = Basemap(width=1200000... | .show() |
bhupennewalkar1337/erpnext | erpnext/schools/doctype/student/student_dashboard.py | Python | gpl-3.0 | 341 | 0.043988 | from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on the attendance of this Student'),
'fieldname': 'student',
'transactions': [
{
| 'items': ['Student Log', 'Student Group', 'Student Attendance']
}, |
{
'items': ['Program Enrollment', 'Fees', 'Assessment']
}
]
} |
greven/vagrant-django | project_name/urls.py | Python | bsd-3-clause | 993 | 0 | """myproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a UR | L to urlpatterns: url(r'^$', views. | home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import ur... |
xlqian/navitia | source/tyr/setup.py | Python | agpl-3.0 | 1,983 | 0.001009 | #!/usr/bin/env python
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part | of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive l | ocomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distri... |
atreyv/sympy | sympy/polys/ring_series.py | Python | bsd-3-clause | 54,558 | 0.001173 | from sympy.polys. | domains import QQ, EX
from sympy.polys.rings import PolyElement, ring, sring
from sympy.polys.polyerrors import DomainError
from sympy.polys.monomials import (monomial_min, monomial_mul, monomial_div,
monomial_ldiv)
from mpmath.libmp.libintmath import ifac
from sympy.core import PoleE... | s, tan, atan, exp, atanh, tanh, log, ceiling
from mpmath.libmp.libintmath import giant_steps
import math
def _invert_monoms(p1):
"""
Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in x.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ... |
s-hertel/ansible | test/support/integration/plugins/modules/docker_swarm.py | Python | gpl-3.0 | 24,565 | 0.001913 | #!/usr/bin/python
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['previe... | red on the managers.
- Docker default value is C(no).
- M(docker_swarm_info) can be used to retrieve the unlock key.
type: bool
rotate_worker_token:
description: Rotate the worker join token.
type: bool
default: no
rotate_manager_token:
description: Rotate the manager join token.
... | s.io/en/stable/) >= 1.10.0 (use L(docker-py,https://pypi.org/project/docker-py/) for Python 2.6)"
- Docker API >= 1.25
author:
- Thierry Bouvet (@tbouvet)
- Piotr Wojciechowski (@WojciechowskiPiotr)
'''
EXAMPLES = '''
- name: Init a new swarm with default parameters
docker_swarm:
state: present
- name: U... |
qilicun/python | python2/PyMOTW-1.132/PyMOTW/datetime/datetime_datetime_math.py | Python | gpl-3.0 | 572 | 0.003497 | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Calculations with datetime values.
"""
__version__ | = "$Id$"
#en | d_pymotw_header
import datetime
today = datetime.datetime.today()
print 'Today :', today
yesterday = today - datetime.timedelta(days=1)
print 'Yesterday:', yesterday
tomorrow = today + datetime.timedelta(days=1)
print 'Tomorrow :', tomorrow
print 'tomorrow - yesterday:', tomorrow - yesterday
print 'yesterday - ... |
bistack/pyStorageBenchmarkTools | test_raid.py | Python | gpl-2.0 | 1,856 | 0.004849 | #!/usr/bin/python
# pdev
# pdev cbd
# pdev asd cbd
# | pdev asd sd cbd
from hba_util import HBA
from raid_util import Raid_Util
from subdev import *
def test_create_remove_raid(rai | d_util, bdevs):
sub_dev_list = []
for bdev in bdevs:
path = '/dev/' + bdev
sub_dev_list.append(path)
raid_util.set_sub_dev_list(sub_dev_list)
raid_util.zero_raid_sub_dev()
raid_util.create_raid()
raid_util.show_raid_info()
raid_util.wait_sync()
raid_util.fail_one()
r... |
rlskoeser/sunburnt | sunburnt/json.py | Python | mit | 1,190 | 0.004202 | from __future__ import absolute_import
import json, math
from .schema import SolrResponse, SolrResult
class SunburntJSONEncoder(json.JSONEncoder):
def encode(self, o):
if isinstance(o, SolrResponse):
| return self.encode(list(o))
return super(SunburntJSONEncoder, self).encode(o)
def default(self, obj):
if hasattr(obj, "strftime"):
try:
microsecond = obj.microsecond
except AttributeError:
microsecond = int(1000000* | math.modf(obj.second)[0])
return u"%s.%sZ" % (obj.strftime("%Y-%m-%dT%H:%M:%S"), microsecond)
return super(SunburntJSONEncoder, self).default(obj)
def dump(obj, fp, *args, **kwargs):
if isinstance(obj, SolrResponse):
obj = list(obj)
elif isinstance(obj, SolrResult):
obj = ob... |
agry/NGECore2 | scripts/mobiles/tatooine/water_thief.py | Python | lgpl-3.0 | 1,333 | 0.025506 | import sys
from services.spawn | import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datat | ables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('water_thief')
mobileTemplate.setLevel(5)
mobileTemplate.setDifficulty(Difficulty.NORM... |
eBay/cronus-agent | agent/agent/lib/agent_thread/threadmgr.py | Python | apache-2.0 | 11,844 | 0.007683 | #pylint: disable=R0904,W0105
'''
Copyright 2014 eBay Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicabl... | .getLogger( | __name__)
class NullThreadMgr():
""" thread manager that does nothing
"""
def __init__(self):
""" constructor"""
pass
def addThread(self, thread):
""" Do nothing """
pass
def stop(self):
""" Do nothing """
pass
def hasActive(self):
""" ... |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/logging/config.py | Python | mit | 13,800 | 0.003333 | # Copyright 2001-2007 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this perm... | s
def _install_loggers(cp, handlers, disable_existing_loggers):
"""Create and install loggers"""
# configure the root first
llist = cp.get("loggers", "keys")
llist = string.split(llist, ",")
llist = map(lambda x: string.strip(x), llist)
llist.remove("root")
sectname = "logger_r... | es[level])
for h in root.handlers[:]:
root.removeHandler(h)
hlist = cp.get(sectname, "handlers")
if len(hlist):
hlist = string.split(hlist, ",")
hlist = _strip_spaces(hlist)
for hand in hlist:
log.addHandler(handlers[hand])
#and now the others...
... |
natasasdj/OpenWPM | test/expected.py | Python | gpl-3.0 | 15,523 | 0.000709 | """ Contains lists of expected data and or rows for tests """
from utilities import BASE_TEST_URL, BASE_TEST_URL_DOMAIN, BASE_TEST_URL_NOPATH
# Navigator and Screen properties
properties = {
"window.navigator.appCodeName",
"window.navigator.appName",
"window.navigator.appVersion",
"window.navigator.bui... | 0/test_pages/shared/test_script_2.js',
u'http://localtest.me:8000/test_pages/http_test_page.html',
0, None, None, 0, 0,
u'http://localtest.me:8000',
u'http://localtest.me:8000/test_pages/http_test_page_2.html', 2),
(u'http://localtest.me:8000/test_pages/shared/test_script.js',
... | ocaltest.me:8000/test_pages/http_test_page.html',
0, None, None, 0, 0,
u'http://localtest.me:8000',
u'http://localtest.me:8000/test_pages/http_test_page.html', 2),
(u'http://localtest.me:8000/test_pages/shared/test_image.png',
u'http://localtest.me:8000/test_pages/http_test_page.html... |
saltstack/salt | tests/pytests/unit/modules/test_win_servermanager.py | Python | apache-2.0 | 2,675 | 0 | import pytest
import salt.modules.win_servermanager as win_servermanager
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {win_servermanager: {"__grains__": {"osversion": "6.2"}}}
def test_install():
"""
Test win_servermanager.install
"""
moc... | ), patch.dict(win_servermanager.__salt__, {"system.reboot": mock_reboot}):
result = win_servermanager.install("XPS-Viewer", restart=True)
mock_reboot.assert_called_once()
assert result == expecte | d
|
ademariag/kapitan | kapitan/lint.py | Python | apache-2.0 | 8,531 | 0.003048 | #!/usr/bin/env python3
# Copyright 2019 The Kapitan Authors
# SPDX-FileCopyrightText: 2020 The Kapitan Authors <kapitan-admins@googlegroups.com>
#
# SPDX-License-Identifier: Apache-2.0
"lint module"
import logging
import os
import sys
from pprint import pformat
from kapitan.errors import KapitanError
from kapitan.u... | logger.debug("Checking if all secrets are declared in " + compiled_path)
for path in list_all_paths(compiled_path):
if os.path.isfile(path):
with open(path, "r") as compiled_file:
file_contents = compiled_file.read()
for secret_path in list(secrets_paths):
... | if secret_path in file_contents:
secrets_paths.discard(secret_path)
checks_sum = len(secrets_paths)
if checks_sum > 0:
logger.info(
"No usage found for the following {} secrets files:\n{}\n".format(
len(secrets_paths), pformat(secrets_paths)
... |
QLGu/django-oscar | src/oscar/apps/customer/forms.py | Python | bsd-3-clause | 15,465 | 0 | import string
import random
from django import forms
from django.conf import settings
from django.contrib.auth import forms as auth_forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.sites.models import get_current_site
from django.core.exceptions import ValidationError
from django.util... | reset_url = self.get_reset_url(site, request, user, use_https | )
ctx = {
'user': user,
'site': site,
'reset_url': reset_url}
messages = CommunicationEventType.objects.get_and_render(
code=self.communication_type_code, context=ctx)
Dispatcher().dispatch_user_messages(user, messages)
... |
jwplayer/rssalertbot | rssalertbot/locking/dynamo.py | Python | mit | 2,370 | 0.011392 | import logging
import pendulum
from pynamodb.attributes import (UnicodeAttribute, UTCDateTimeAttribute)
from pynamodb.exceptions import DoesNotExist
from pynamodb.models import Model
from . import BaseLocker, Lock, LockAccessDenied
log = logging.getLogger(__name__)
class DynamoLock(Model):
class Meta:
... | wner_name != owner_name:
log.debug(f"Lock {key} denied")
raise LockAccessDenied()
# delete the old lock
old.delete()
except DoesNotExist:
pass
# create the new lock
rec = DynamoLock(
key = ke | y,
expires = pendulum.now('UTC').add(seconds = lease_time),
owner_name = owner_name,
)
rec.save()
log.debug(f"Lock {rec.key} acquired, expires {rec.expires}")
def release():
self.release_lock(key, owner_name)
# return lock
return... |
svetlyak40wt/svetlyak40wt.recipe.symlinks | setup.py | Python | bsd-3-clause | 1,194 | 0.028476 | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(
os.path.dirname(__file__), filename)).read()
entry_points = """
[zc.buildout]
default = svetlyak40wt.recipe.symlinks:Symlinks
[zc.buildout.uninstall]
default = svetlyak40wt.recipe.symlinks:uninstal... | ME.md'),
classifiers = [
'License :: OSI Approved :: BSD License',
'Framework :: Buildout',
'Programming Language :: Python',
],
keywords = 'buildout recipe',
author = 'Alexander Artemenko',
author_email = 'svetlyak.40wt@gmail.com',
url = 'http://github.com/svetlyak40wt/s... | 'svetlyak40wt.recipe'],
include_package_data = True,
install_requires = [
'zc.buildout',
'zc.recipe.egg',
'setuptools',
],
zip_safe = False,
entry_points = entry_points,
)
|
ceph/autotest | client/bin/fsdev_disks.py | Python | gpl-2.0 | 19,722 | 0.003499 | import sys, os, re, string
from autotest_lib.client.bin import utils, fsinfo, fsdev_mgr, partition
from autotest_lib.client.common_lib import error
fd_mgr = fsdev_mgr.FsdevManager()
# For unmounting / formatting file systems we may have to use a device name
# that is different from the real device name that we have ... | disk1_only=False, disk_list=None):
"""
Prepare drive(s) to contain the file system type / options given in the
description line 'fs_desc'. When 'disk_list' is not None, we prepare all
the drives in that list; otherwise we pick the first available data drive
( | which is usually hdc3) and p |
tectronics/pyresample | pyresample/_spatial_mp.py | Python | gpl-3.0 | 10,244 | 0.009664 | #pyresample, Resampling of remote sensing image data in python
#
#Copyright (C) 2010, 2013 Esben S. Nielsen, Martin Raspaud
#
#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 t... | copy in shared memory rather than the origial data.
self.leafsize = leafsize
self._nprocs = nprocs
self._chunk = chunk
self._schedule = schedule |
def query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf):
'''
Same as cKDTree.query except parallelized with multiple
processes and shared memory.
'''
# allocate shared memory for x and result
nx = x.shape[0]
shmem_x = mp.Raw... |
gakarak/FCN_MSCOCO_Food_Segmentation | MSCOCO_Processing/ext_code/run04_model_inference.py | Python | apache-2.0 | 2,889 | 0.012807 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import time
import shutil
import os
import matplotlib.pyplot as plt
import skimage.io as skio
import numpy as np
import keras
from keras.utils import np_utils
from keras.utils.vis_utils import plot_model
def readDataMasked(pidx):
with open(pidx, 'r') as... | 2)
q1 = valY[ii][:,:,1].copy()>0.5
q2 = | retY[ii][:, :, 1].copy()>0.5
plt.imshow(np.dstack([q1,q2,q1]))
plt.title('Loss: %0.3f, Acc: %0.3f' % (arrAcc[ii,0], arrAcc[ii,1]))
plt.show()
print ('-----')
|
mlabru/ptracks | model/newton/cine/prc_aproximacao.py | Python | gpl-3.0 | 13,517 | 0.002239 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
--------------------------------------------------------------------------------------------------
prc_aproximacao
procedimento de aproximação de acordo com o aeródromo e pista estabelecidos
This program is free software: you can redistribute it and/or modify
it under... | l_log = logging.getLogger("prc_aproximacao")
l_log.setLevel(logging.ERROR)
l_log.error(u"<E04: fase zero. apx/breakpoint inexistente. aeronave:[{}/{}].".format(f_atv.i_trf_id, f_atv.s_trf_ind))
# abort procedure
abnd.abort_prc(f_atv)
# return
re... | n
# obtém dados do breakpoint
obrk.obtem_brk(f_atv, l_brk, f_cine_data)
# fase de direcionamento aos breakpoints do procedimento ?
elif ldefs.E_FASE_DIRPONTO == f_atv.en_atv_fase:
# interceptou o breakpoint ?
if dp.prc_dir_ponto(f_atv, f_cine_data.f_coord_x_brk, f_cine_data.f_c... |
chaosmaker/pyload | module/plugins/crypter/FilebeerInfoFolder.py | Python | gpl-3.0 | 413 | 0.002421 | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadCrypter import DeadCrypter
class FilebeerInfoFolder(DeadCrypter):
__name__ = "FilebeerInfoFolder"
__type__ = "crypter"
__pattern__ = r"http://(?:www\.)?filebeer\.info/(\d+~f).*"
__version__ = "0.02"
__description__ = """Filebeer.info Folder... | jmail.cz")
| |
iAmMrinal0/django_moviealert | moviealert/urls.py | Python | mit | 1,192 | 0 | """moviealert URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... | , name="home"),
url(r'^tasklist', task_list, name="tasklist"),
url(r'^get_city/', get_city),
# url(r'^accounts/logout/$',
# 'djan | go.contrib.auth.views.logout',
# {'next_page': '/'}
# ),
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
|
swift-lang/swift-e-lab | parsl/providers/cobalt/cobalt.py | Python | apache-2.0 | 8,583 | 0.003495 | import logging
import os
import time
from parsl.providers.error import ScaleOutFailed
from parsl.channels import LocalChannel
from parsl.launchers import AprunLauncher
from parsl.providers.cobalt.template import template_string
from parsl.providers.cluster_provider import ClusterProvider
from parsl.utils import Repres... | heduler_options = scheduler_options
self.worker_init = worker_init
def _status(self):
""" Internal: Do not call. Returns the status list for a list of job_ids
Args:
self
Returns:
[status...] : Status list of all jobs
"""
jobs_missing = ... | e_wait("qstat -u $USER")
# Execute_wait failed. Do no update.
if retcode != 0:
return
for line in stdout.split('\n'):
if line.startswith('='):
continue
parts = line.upper().split()
if parts and parts[0] != 'JOBID':
... |
thisisshi/cloud-custodian | tools/c7n_gcp/c7n_gcp/actions/notify.py | Python | apache-2.0 | 3,245 | 0.000308 | # Copyright The Cloud Custod | ian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.actions import BaseNotify
from c7n import utils
from c7n.resolver import ValuesFrom
from c7n_gcp.provider import resources as gcp_resources
class Notify(BaseNotify):
"""
:example:
.. code-block:: yaml
policies:
- name: ba... | - type: notify
to:
- email@address
# which template for the email should we use
template: policy-template
transport:
type: pubsub
topic: projects/yourproject/topics/yourtopic
"""
... |
iris-edu-int/kombu | kombu/tests/test_serialization.py | Python | bsd-3-clause | 11,687 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
from base64 import b64decode
from kombu.exceptions import ContentDisallowed, EncodeError, DecodeError
from kombu.five import text_t, bytes_t
from kombu.serialization import (
regist... | gistry.assert_has_calls([
call.enable('pickle'), call.enable('yaml'),
call.enable('msgpac | k'),
])
registry.enable.side_effect = KeyError()
enable_insecure_serializers()
with patch('kombu.serialization.registry') as registry:
enable_insecure_serializers(['msgpack'])
registry.assert_has_calls([call.enable('msgpack')])
def test_disable_i... |
sigmunau/nav | python/nav/ipdevpoll/neighbor.py | Python | gpl-2.0 | 13,422 | 0.000596 | #
# Copyright (C) 2012 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | identified netbox.
The ifName, ifDescr, ifAlias, and optionally, baseport attributes are
searched for name.
:returns: A shadows.Interface object representing the interface, or None
if no corresponding interface was found.
"""
if not (self.netbox and name):... | self._logger.warning("cannot search database for malformed "
"neighboring port name %r", name)
return
queries = [Q(ifdescr=name), Q(ifname=name), Q(ifalias=name)]
if name.isdigit():
queries.append(Q(baseport=int(name)))
netbox = Q(n... |
libvirt/libvirt-test-API | libvirttestapi/repos/migration/migrate_parallel.py | Python | gpl-2.0 | 5,426 | 0.000921 | # Copyright (C) 2010-2012 Red Hat, Inc.
# This work is licensed under the GNU GPLv2 or later.
import threading
import time
import libvirt
import json
from libvirt import libvirtError
from libvirttestapi.repos.domain import domain_common
from libvirttestapi.utils import utils
from libvirttestapi.utils import process
r... | ot active")
if dstdom.info()[0] != libvirt.VIR_DOMAIN_RUNNING:
test_result = False
logger.error("Dst VM wrong state %s, should be running", dstdom.info()[0])
except libvirtError as e:
test_result = False
logger.error("API error message: %s, error code is %s"
... | message(), e.get_error_code()))
logger.error("Migration Failed")
finally:
env_clean(srcc, dstc, guestname, logger)
if not test_result:
return 1
else:
logger.info("Migration PASS")
return 0
|
costadorione/purestream | channels/mondolunatico.py | Python | gpl-3.0 | 9,580 | 0.003133 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# streamondemand.- XBMC Plugin
# Canal para mondolunatico
# http://blog.tvalacarta.info/plugin-xbmc/streamondemand.
# ------------------------------------------------------------
import os
import re
import urllib
import urlparse
fro... | apedplot))
return itemlist
def search(item, texto):
logger.info("[mondolunatico.py] " + item.url + " search " + texto)
item.url = host + "/?s=" + texto
try:
return peliculas(item)
# Se captura la excepción, para no interrumpir al buscador global si un canal falla
except:
impor... | olunatico peliculas")
itemlist = []
# Descarga la pagina
data = scrapertools.cache_page(item.url, headers=headers)
# Extrae las entradas (carpetas)
patron = '<div class="boxentry">\s*<a href="([^"]+)"[^>]+>\s*<img src="([^"]+)" alt="([^"]+)"[^>]+>'
matches = re.compile(patron, re.DOTALL).find... |
jumpstarter-io/keystone | keystone/contrib/revoke/core.py | Python | apache-2.0 | 9,306 | 0 | # 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
# distributed under t... | tion,
payload):
self.revoke(
model.RevokeEvent(project_id=payload['resource_info']))
def _domain_callback(self, service, resource_type, operation,
payload):
self.revoke(
model.RevokeEvent(domain_id=payload['resource_info']))... | .revoke(
model.RevokeEvent(trust_id=payload['resource_info']))
def _consumer_callback(self, service, resource_type, operation,
payload):
self.revoke(
model.RevokeEvent(consumer_id=payload['resource_info']))
def _access_token_callback(self, service, re... |
tensorflow/tfx | tfx/utils/model_paths/tf_serving_flavor_test.py | Python | apache-2.0 | 2,745 | 0.003279 | # Copyright 2020 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... | assertEqual(
tfs_flavor.parse_model_path('gs://bucket-name/foo/bar/my-model/123'),
('gs://bucket-name/foo/bar', 'my-model', 123))
def testParseModelPath_Fail(self):
with self.assertRaises(ValueError):
| tfs_flavor.parse_model_path('too-short')
with self.assertRaises(ValueError):
tfs_flavor.parse_model_path('/foo/bar/my-model/not-an-int-version')
with self.assertRaises(ValueError):
tfs_flavor.parse_model_path('/foo/bar/other-model/123',
expected_model_name='... |
datanel/navitia | source/sql/models/navitia.py | Python | agpl-3.0 | 24,406 | 0.006269 | # -*- coding: utf-8 -*-
## File autogenerated by SQLAutoCode
## see http://code.google.com/p/sqlautocode/
from sqlalchemy import *
from sqlalchemy.dialects.postgresql import *
from geoalchemy2 import Geography
from models import metadata
object_type = Table('object_type', metadata,*[
Column('id', INTEGER(), prima... | rimary_ke | y=False, nullable=False),],
schema='navitia')
parameters = Table('parameters', metadata,*[
Column('beginning_date', DATE(), primary_key=False),
Column('end_date', DATE(), primary_key=False),
Column('timezone', TEXT(), primary_key=False),
Column('shape', Geography(geometry_type='MULTIPOLYGON', srid... |
thopiekar/Uranium | UM/Preferences.py | Python | lgpl-3.0 | 8,239 | 0.00619 | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
import configparser
from UM.Signal import Signal, signalemitter
from UM.Logger import Logger
from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType #To register the MIME type of the preference file.
from UM.SaveFile... | Preferences File",
suffixes = ["cfg"],
preferred_suffix = "cfg"
)
)
## Preferences are application based settings that are saved for future use.
# | Typical preferences would be window size, standard machine, etc.
@signalemitter
class Preferences:
Version = 5
def __init__(self):
super().__init__()
self._file = None
self._parser = None
self._preferences = {}
def addPreference(self, key, default_value):
prefere... |
wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/IPython/qt/manager.py | Python | mit | 1,594 | 0 | """ Defines a KernelClient that provides signals and slots.
"""
from IPython.external.qt import QtCore
# Local imports
from IPython.utils.traitlets import Bool, DottedObjectName
from IPython.kernel import KernelManager
from IPython.kernel.restarter import KernelRestarter
from .kernel_mixins import QtKernelManagerMi... | elf):
if self.autorestart and self.has_kernel:
if self._restarter is None:
self._restarter = QtKernelRestarter(
kernel_manager=self,
par | ent=self,
log=self.log,
)
self._restarter.add_callback(self._handle_kernel_restarted)
self._restarter.start()
def stop_restarter(self):
if self.autorestart:
if self._restarter is not None:
self._restarter.stop()
... |
Kleptobismol/scikit-bio | skbio/sequence/tests/test_sequence.py | Python | bsd-3-clause | 56,349 | 0.000089 | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... | -------------------------
from __future__ import absolute_import, division, print_function
from future.standard_library import hooks
with hooks():
from itertools import zip_longest
from re import compile as re_compile
from collections import Counter, defaultdict
from unittest import TestCase, main
import numpy a... | y.testing as npt
from skbio import (
BiologicalSequence, NucleotideSequence, DNASequence, RNASequence,
ProteinSequence)
from skbio.sequence import BiologicalSequenceError
class BiologicalSequenceTests(TestCase):
def setUp(self):
self.b1 = BiologicalSequence('GATTACA', quality=range(7))
s... |
trezor/micropython | tests/misc/sys_settrace_subdir/trace_generic.py | Python | mit | 1,552 | 0.009021 | print("Now comes the language constructions tests.")
# function
def test_func():
def test_sub_func():
print("test_function")
test_sub_func()
# closure
def test_closure(msg):
def make_closure():
print(msg)
return make_closure
# exception
def test_exception():
try:
raise ... | trace_importme.saysomething()
# class
class TLClass():
def method():
pass
pass
def test_class():
class TestClass:
__anynum = -9
def method(self):
print("test_class_method")
self.__anynum += 1
def prprty_getter(self):
return self... | def prprty_setter(self, what):
self.__anynum = what
prprty = property(prprty_getter, prprty_setter)
cls = TestClass()
cls.method()
print("test_class_property", cls.prprty)
cls.prprty = 12
print("test_class_property", cls.prprty)
def run_tests():
test_func()
test_clo... |
zmap/ztag | ztag/annotations/FtpOverlandStorage.py | Python | apache-2.0 | 1,698 | 0.004122 | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag.annotation import Type
from ztag.annotation import Manufacturer
from ztag import protocols
import ztag.test
class FtpOverlandStorage(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
... | ith("220 ProFTPD"):
meta.local_metadata.product = "ProFTPD"
version = self.version_re.search(banner).group(1)
meta.local_metadata.version = version
rev = self.version_re.search(banner).group(2)
meta.local_metadata.revision = rev
... | urn meta
""" Tests
"220 ProFTPD 1.2.9 Server (Snap Appliance FTP Server) [SNAP2252876.spec.local]\r\n"
"220 ProFTPD 1.2.9 Server (Snap Appliance FTP Server) [HAFServer.uconn.edu]\r\n"
"""
|
codebox/algorithms | strassens_matrix_multiplication.py | Python | mit | 1,704 | 0.008803 | '''
-------------------------------
Strassens Matrix Multiplication
-------------------------------
Performs matrix multiplication in sub-cubic time, performing only 7 recursive calls
rather than the 8 required by standard multiplication.
The function assumes 2 square matrices that have height/width that is a power o... | def split_matrix(m):
n = len(m) / 2
ma = map(lambda x : x[:n], m[:n])
mb = map(lambda x : x[n:], m[:n])
mc = map(lambda x : x[:n], m[n:])
md = map(lambda x : x[n:], m[n:])
return ma, mb, mc, md
def add_rows(r):
return map(sum, zip(r[0], r[1]))
def add... | p(negate_row, m)
def multiply(m1, m2):
if len(m1) == 1:
return [[m1[0][0] * m2[0][0]]]
ma, mb, mc, md = split_matrix(m1)
me, mf, mg, mh = split_matrix(m2)
p1 = multiply(ma, add(mf, negate(mh)))
p2 = multiply(add(ma, mb), mh)
p3 = multiply(add(mc, md), m... |
Sohojoe/damon | damon1/validation.py | Python | apache-2.0 | 12,391 | 0.020418 | '''
This file is made with purpose to contain all validation related things. For now
, it has the custom methods to validate arguments. At later stage it may have
even more.
'''
import damon1 as dmn
#from helper import *
#
#import damon1.tools as tools
'''
This validates the self argument of ltm method of D... | od of Damon_R class..
'''
def validate_r_grm_control(self,arg_val):
#firstly check type.
if not isinstance(arg_val,dict):
raise dmn.helper.DamonException("Type | of control must be a dictionary.")
#now lets check if the control dictionary is in right format
if (all(list(e in ['iter.qN','GHk','method','verbose','digits.abbrv']
for e in arg_val.keys())) is False):
raise dmn.helper.DamonException("control argument is not in correct format. "+
... |
regadas/presstatic | presstatic/builder.py | Python | mit | 3,269 | 0.00153 | # -*- coding: utf-8 -*-
import os
import shutil
from jinja2 import Environment, FileSystemLoader
from webassets import Environment as AssetsEnvironment
from webassets.ext.jinja2 import AssetsExtension
from webassets.loaders import YAMLLoader
class TemplateBuilder(object):
def __init__(self, path, output,
... | fig.yml'):
self.path = path
self.output = output
self.output_path = os.path.join(path, output)
self.env = Environment(loader=FileSystemLoader(path),
extensions=[AssetsExtension])
try:
config_path = os.path.join(self.path, asset_config)
... | nt()
except IOError:
self.assets_env = AssetsEnvironment()
if 'directory' not in self.assets_env.config:
self.assets_env.directory = self.output_path
if 'url' not in self.assets_env.config:
self.assets_env.url = static_url
self.assets_env.load_path ... |
Jcing95/iop-hd | contrib/seeds/generate-seeds.py | Python | mit | 4,326 | 0.009246 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... | omment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not first:
g.write(',\n')
first = False
(host,port) = parse_spec(line, defaultport)
hoststr = ','.join(('0x%02x' % b)... | g.write(' {{%s}, %i}' % (hoststr, port))
g.write('\n};\n')
def main():
if len(sys.argv)<2:
#print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef IOP_CHAINPARAMSSEEDS_H\n')
g.write('#define IOP_CHA... |
cp16net/python-troveclient | troveclient/v1/databases.py | Python | apache-2.0 | 2,840 | 0 | from troveclient import base
from troveclient.common import check_for_exceptions
from troveclient.common import limit_url
from troveclient.common import Paginated
import urlparse
class Database(base.Resource):
"""
According to Wikipedia, "A database is a system intended to organize,
store, and retrieve
... | e(url)
check_for_exceptions(resp, body)
def _list(self, url, response_key, limit=None, marker=None):
resp, body = self. | api.client.get(limit_url(url, limit, marker))
check_for_exceptions(resp, body)
if not body:
raise Exception("Call to " + url +
" did not return a body.")
links = body.get('links', [])
next_links = [link['href'] for link in links if link['rel'] == '... |
DestructHub/bcs-contest | 2016/Main/L/Python/solution_1_wrong.py | Python | mit | 471 | 0.082803 | def calc():
h, l = input().split(' ')
mapa = []
for i_row in range(int(h)):
mapa.append(input().split(' '))
maior_num = 0
for row in mapa:
for col in row:
n = int(col)
if (n > maior_num):
maior_num = n
qtd = [0 for i in range(maior_num + 1)]
for row in mapa:
for col in row:
n ... | i
| print(menor)
calc()
|
desarrollosimagos/svidb | administrativo/listasTematicas/admin.py | Python | gpl-3.0 | 12,168 | 0.02786 | #!/usr/bin/python -u
# -*- coding: utf-8 -*-
from listasTematicas.models import *
from especies.models import *
from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect,HttpResponse
from django.shortcuts import render, ren... | if db_field.name == "userupdate":
kwargs["queryset"] = User.objects.filter(id=request.user.id)
return super(SpaprovechablesAdmin, self).formfield_for_foreignkey(db_ | field, request, **kwargs)
class Media:
js = ('/js/tiny_mce/tiny_mce.js', '/js/textareas.js')
admin.site.register(Spaprovechables,SpaprovechablesAdmin)
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
class Spaprovec... |
jim-bo/silp2 | creation/align.py | Python | mit | 10,726 | 0.003916 | '''
alignment utility functions
'''
import os
import sys
import subprocess
import logging
import mmap
import gzip
import multiprocessing
from operator import itemgetter
import numpy as np
## public functions ##
def pair_alignment(paths, args):
""" creates the alignment """
# validate parameters.
assert ... | _names(file_name=sort2_npy, data=names2)
del names2
subprocess.call(["rm", "-f", names2_npy])
| # create sizes.
sizes = dict()
with open(size_file, "rb") as fin:
lines = fin.readlines()
for line in lines:
sz, name = line.strip().split()
sz = int(sz)
sizes[name] = sz
# create the annotation arrays.
annotes = dict()
for ref in sizes:
annotes[ref] = n... |
dtroyer/python-openstacksdk | openstack/cloud/openstackcloud.py | Python | apache-2.0 | 31,888 | 0 | # 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
# distributed under the... | servers = conn2.list_servers()
:param kwargs: keyword arguments can contain anything that would
| normally go in an auth dict. They will override the same
settings from the parent cloud as appropriate. Entries
that do not want to be overridden can be ommitted.
"""
if self.config._openstack_config:
config = self.config._... |
drougge/wwwwellpapp | image.py | Python | mit | 1,071 | 0.026144 | #!/usr/bin/env python
from os.path import exists
from os import stat
from time import strftime, gmtime, time
from bottle import get, abort, response
from common import init
from wellpapp import RawWrapper, raw_exts
def fmttime(t):
return strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(t))
def serve(fn, ext):
if not ... | ponse.set_header("Content-Length", str(z))
response.set_header("Expires", fmttime(time() + 60*60*24 * 10))
response.set_header("Date", fmttime(time()))
return fh
@get("/image/<z>/<m:re:[0-9a-z]{32}>")
def thumb(m, z):
client = init()
if z in ("normal", "large") | :
return serve(client.pngthumb_path(m, z), "png")
else:
return serve(client.thumb_path(m, z), "jpeg")
@get("/image/<m:re:[0-9a-z]{32}>.<ext:re:[a-z]{3,4}>")
def r_image(m, ext):
client = init()
return serve(client.image_path(m), ext)
|
sassoftware/sas_kernel | sas_kernel/data/__init__.py | Python | apache-2.0 | 82 | 0.02439 | im | port os
_dataRoot = os.path.abspath(os.path.dirname(__file__))
print (_d | ataRoot) |
bellowsj/aiopogo | aiopogo/pogoprotos/data/battle/battle_action_type_pb2.py | Python | mit | 3,507 | 0.003422 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/data/battle/battle_action_type.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from go... | _type=None,
options=None,
serialized_start=76,
serialized_end=328,
)
_sym_db.RegisterEnumDescriptor(_BATTLEACTIONTYPE)
BattleActionType = enum_type_wrapper.EnumTypeWrapper(_BATTLEACTIONTYPE)
ACTION_UNSET = 0
ACTION_ATTACK = 1
ACTION_DODGE = 2
ACTION_SPECIAL_ATTACK = 3
ACTION_SWAP_POKEMON = 4
ACTION_FAINT = 5
ACT... | um_types_by_name['BattleActionType'] = _BATTLEACTIONTYPE
# @@protoc_insertion_point(module_scope)
|
square/pants | tests/python/pants_test/fs/test_expand_path.py | Python | apache-2.0 | 1,446 | 0.011065 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib impor... | /bob', expand_path('~/bob'))
def test_env_var_expansion(self):
with self.root() as root:
with environment_as(A='B', C='D'):
self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E'))
@contextmanager
def root(self):
with temporary_dir() as root:
# Avoid OSX issues where ... | os.path.realpath(root)
with pushd(real_root):
yield real_root
|
jdemel/gnuradio | gr-fec/python/fec/qa_fecapi_dummy.py | Python | gpl-3.0 | 8,043 | 0.006465 | #!/usr/bin/env python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import absolute_import
import numpy as np
from gnuradio import gr, gr_unittest, blocks
from gnuradio import fec
from gnuradio.fec import extende... | )
tb.connect(src, packer, snk0)
enc_unpacked = fec.dummy_encoder_make(frame_size, False, False)
ext_enc_unp = extended_encoder(enc_unpacked, thread | ing='none', puncpat='11')
tb.connect(src, ext_enc_unp, snk1)
enc_pack = fec.dummy_encoder_make(frame_size // 8, True, False)
ext_enc_pack = extended_encoder(enc_pack, threading='none', puncpat='11')
tb.connect(src, ext_enc_pack, snk2)
enc_packed_bits = fec.dummy_encoder_make(fr... |
li-xirong/image2label | fiksvm/fiksvm.py | Python | mit | 5,842 | 0.007874 | #!/usr/bin/env python
from ctypes import *
from ctypes.util import find_library
import sys
import os
import platform
LIB_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')
if sys.platform.startswith('linux'):
filename = os.path.join(LIB_PATH, 'linux', 'libfiksvm.so.1')
libfiksvm = CDLL(f... | NTER(POINTER(fiksvm_approx_model))])
fillprototype(libfiksvm.fiksvm_save_model, c_int, [c_char_p, POINTER(fiksvm_approx_model)])
fillprototype(libfiksvm.fiksvm_load_model, POINTER(fiksvm_approx_model), [c_char_p])
fillprototype(libfiksvm.fiksvm_get_probA, c_double, [POINTER(fiksv | m_approx_model)])
fillprototype(libfiksvm.fiksvm_get_probB, c_double, [POINTER(fiksvm_approx_model)])
fillprototype(libfiksvm.fiksvm_set_probAB, None, [POINTER(fiksvm_approx_model), c_double, c_double])
fillprototype(libfiksvm.add_new_hikmodel, c_int, [POINTER(fiksvm_approx_model), POINTER(svm_model), c_double, c_doub... |
luzfcb/django-auth-policy | django_auth_policy/user_admin.py | Python | bsd-3-clause | 6,016 | 0.000665 | import logging
from django import forms
from django import template
from django import http
from django.conf.urls import patterns, url
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.utils import timezone
fr... | request=request,
password=password)
return template.response.TemplateResponse(request,
'admin/django_auth_policy/set_temporary_password.html',
{'passwords': passwords})
return template.response... | save_model(self, request, obj, form, change):
obj.save()
UserChange.objects.create(user=obj, by_user=request.user)
|
michaelfardu/thinkconfluent | confluent_server/confluent/messages.py | Python | apache-2.0 | 21,993 | 0.000546 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 IBM Corporation
# Copyright 2015 Lenovo
#
# 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/LI... | nreachable(self.error)
class ConfluentTargetNotFound(ConfluentNodeError):
def __init__(self, node, errorstr='not found'):
self.node = node
self.error = errorstr
def strip_node(self, node):
raise exc.NotFoundException(self.error)
class ConfluentTargetInvalidCredentials(Con | fluentNodeError):
def __init__(self, node):
self.node = node
self.error = 'bad credentials'
def strip_node(self, node):
raise exc.TargetEndpointBadCredentials
class DeletedResource(ConfluentMessage):
def __init__(self, resource):
self.kvpairs = {}
class ConfluentChoiceMe... |
ciudadanointeligente/write-it | nuntium/tests/messages_per_person_view_test.py | Python | gpl-3.0 | 4,401 | 0 | # coding=utf-8
from global_test_case import GlobalTestCase as TestCase
from subdomains.utils import reverse
from instance.models import WriteItInstance
from ..models import Message
from popit.models import Person
class MessagesPerPersonViewTestCase(TestCase):
def setUp(self):
super(MessagesPerPersonViewTe... | ertNotIn(private_message, response.context['message_list'])
def test_show_only_messages_that_are_related_to_the_writeitinstance(self):
the_other_instance = WriteItInstance.objects.get(id=2)
message = Message.objects.create(
content='Content 1',
author_name='Felipe',
... | blic=True,
confirmated=True,
persons=[self.pedro],
)
url = reverse(
'thread_to',
subdomain=self.writeitinstance.slug,
kwargs={
'pk': self.pedro.id,
},
)
response = self.client.get(url)
... |
ashutosh-mishra/youtube-dl | youtube_dl/extractor/arte.py | Python | unlicense | 10,732 | 0.003541 | # encoding: utf-8
import re
import json
import xml.etree.ElementTree
from .common import InfoExtractor
from ..utils import (
ExtractorError,
find_xpath_attr,
unified_strdate,
determine_ext,
get_element_by_id,
compat_str,
)
# There are different sources of video in arte.tv, the extraction proce... | lang == 'de':
l = 'A'
regexes = [r'VO?%s' % l, r'VO?.-ST%s' % l]
return any(re.match(r, f['versionCode']) for r in regexes)
# Some formats may not be in the same language as the url
formats = filter(_match_lang, all_formats)
formats = list(formats) # in py... | formats:
# Some videos are only available in the 'Originalversion'
# they aren't tagged as being in French or German
if all(f['versionCode'] == 'VO' for f in all_formats):
formats = all_formats
else:
raise ExtractorError(u'The formats list ... |
lukeiwanski/tensorflow | tensorflow/contrib/learn/python/learn/__init__.py | Python | apache-2.0 | 2,715 | 0.000737 | # 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... | ic_spec import MetricSpec
from tensorflow.contrib.learn.python.learn.monitors import NanLossDuringTrainingEr | ror
from tensorflow.contrib.learn.python.learn.trainable import Trainable
from tensorflow.contrib.learn.python.learn.utils import *
# pylint: enable=wildcard-import
|
sigmavirus24/pip | tests/unit/test_pep425tags.py | Python | mit | 5,894 | 0 | import sys
from mock import patch
from pip import pep425tags
class TestPEP425Tags(object):
def mock_get_config_var(self, **kwd):
"""
Patch sysconfig.get_config_var for arbitrary keys.
"""
import pip.pep425tags
get_config_var = pip.pep425tags.sysconfig.get_config_var
... | ual_abi_d_flag(sel | f):
"""
Test that the `d` flag is set on a PyDebug, non-Pymalloc ABI tag.
"""
self.abi_tag_unicode('d', {'Py_DEBUG': True, 'WITH_PYMALLOC': False})
def test_manual_abi_m_flag(self):
"""
Test that the `m` flag is set on a non-PyDebug, Pymalloc ABI tag.
"""
... |
joshuar500/mcratesv1 | mcratesv1_project/blog_rankings/urls.py | Python | apache-2.0 | 115 | 0 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'$', views.index, name="index" | ),
]
| |
shakamunyi/neutron-dvr | neutron/agent/securitygroups_rpc.py | Python | apache-2.0 | 12,495 | 0.00032 | # Copyright 2012, Nachi Ueno, NTT MCL, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | ect):
"""A mix-in that enable SecurityGroup support in plugin rpc."""
def security_group_rules_for_devices(self, context, devices):
LOG.debug(_("Get security group rules "
"for devices via rpc %r"), devices)
return self.call(conte | xt,
self.make_msg('security_group_rules_for_devices',
devices=devices),
version=SG_RPC_VERSION,
topic=self.topic)
class SecurityGroupAgentRpcCallbackMixin(object):
"""A mix-in that enable SecurityGrou... |
apache/incubator-singa | examples/gan/lsgan.py | Python | apache-2.0 | 6,650 | 0.000451 | #
# 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... | print_log(' The {} iteration, G_LOSS: {}, D_LOSS: {}'.format(
iteration, g_loss, d_loss))
def save_image( | self, iteration):
demo_row = 5
demo_col = 5
if not hasattr(self, "demo_noise"):
self.demo_noise = tensor.Tensor(
(demo_col * demo_row, self.noise_size), dev, tensor.float32)
self.demo_noise.uniform(-1, 1)
gen_imgs = self.model.forward_gen(self.demo_noi... |
Thingee/cinder | cinder/volume/manager.py | Python | apache-2.0 | 59,306 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | olume import rpcapi as volume_rpcapi
f | rom cinder.volume import utils as volume_utils
from cinder.volume import volume_types
from cinder.zonemanager.fc_zone_manager import ZoneManager
from eventlet.greenpool import GreenPool
LOG = logging.getLogger(__name__)
QUOTAS = quota.QUOTAS
volume_manager_opts = [
cfg.StrOpt('volume_driver',
def... |
baloo/shinken | shinken/modules/livestatus_broker/livestatus_constraints.py | Python | agpl-3.0 | 1,143 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.co | m
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by... | ersion.
#
# Shinken 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 Publ... |
globocom/database-as-a-service | dbaas/maintenance/migrations/0038_auto__add_filermigrate.py | Python | bsd-3-clause | 59,365 | 0.007766 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FilerMigrate'
db.create_table(u'maintenance_filermigrate'... | db.models.fields.DateTime | Field', [], {'auto_now': 'True', 'blank': 'True'})
},
u'account.team': {
'Meta': {'ordering': "[u'name']", 'object_name': 'Team'},
'contacts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTim... |
zuotingbing/spark | python/pyspark/resource/taskrequests.py | Python | apache-2.0 | 3,865 | 0.002846 | #
# 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 us... | elf._java_task_resource_requests.resource(v.resourceName, v.amount)
else:
self._java_task_resource_requests = None
self._task_resources = {}
def cpus(self, amount):
if self._java_task_resource_requests is not None:
self._java_task_resourc | e_requests.cpus(amount)
else:
self._task_resources[self._CPUS] = TaskResourceRequest(self._CPUS, amount)
return self
def resource(self, resourceName, amount):
if self._java_task_resource_requests is not None:
self._java_task_resource_requests.resource(resourceName, f... |
robjcaskey/evennia-merlin | merlin/models.py | Python | bsd-3-clause | 2,098 | 0.003337 | from django.db import models
"""
Misc. utility methods. Keep these to a minimum.
"""
def myrddin_date_format(dtime):
"""
Myrddin used the format, 'Mon Jan 01', for showing dates. Output
the given datetime object in this for | mat.
:param datetime.datetime dtime: The datetime object to print out.
:rtype: str
:returns: A Myrddin-style date string for last post date.
"""
return dtime.strftime('%a %b %d')
""" |
Models and managers.
"""
class BBGroupManager(models.Manager):
"""
Convenience table-level methods for BB groups. Logic for filtering based
on subscriptions should stay here, along with any other commonly used
filtering.
"""
def get_groups_for_player(self, player):
"""
:param P... |
ktarrant/options_csv | journal/trades/migrations/0001_initial.py | Python | mit | 1,392 | 0.00431 | # Generated by Django 2.1 on 2018-08-28 05:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Leg',
fields=[
('id', models.AutoField(auto_c... | mbol', models.CharField(max_length=16)),
('exec_date', models.DateTimeField(verbose_name='date executed')),
('buy_or_sell', models.CharField(choices=[('buy', 'Buy'), ('sell', 'Sell')], default='buy', max_length=4)),
('open_or_close', models.CharField(choices=[('open', 'Op... | ('stock', 'Stock'), ('fut', 'Futures')], default='call', max_length=5)),
('quantity', models.PositiveIntegerField()),
('execution_price', models.FloatField()),
('execution_fees', models.FloatField(default=0)),
('expiration_date', models.DateTimeField(null=... |
mixmastamyk/yamlweb | setup.py | Python | gpl-3.0 | 1,537 | 0.035133 | #~ # -*- coding: utf-8 -*-
#~ from os.path import join
from distutils.core import setup
from yamlweb import __version__, __progname as name
# re | adme is needed at register/upload time, not install time
try:
with open('readme.rst') as f:
| long_description = f.read()
except IOError:
long_description = ''
setup(
name = name,
version = __version__,
description = 'Converts YAML to HTML and CSS.',
author = 'Mike Miller',
author_email = 'mixmastamyk@github.com',
url ... |
tonimichel/django-choicer | choicer/test/__init__.py | Python | mit | 335 | 0.002985 | from __future__ import absolute_import, print_function, | unicode_literals
import unittest
from choicer.test import core_tests
def suite():
return unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(core_tests.ChoicerTests),
])
def run_all():
return unittest.TextTestRunner(verbosity | =2).run(suite())
|
shuaizi/leetcode | leetcode-python/num508.py | Python | apache-2.0 | 1,644 | 0.001825 | __author__ = 'shua | i'
# Definition for a binary tree node.
class TreeNode(object):
d | ef __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret_dict = {}
def tree_sum(node):
if not node:
... |
endlessm/chromium-browser | third_party/depot_tools/fetch_configs/devtools-frontend.py | Python | bsd-3-clause | 1,092 | 0.010989 | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import config_util # pylint: disable=import-error
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=no... | ads': True,
}
return {
'type': 'gclient_git',
'gclient_git_spec': spec,
}
@staticmethod
def expected_root(_props):
return 'devtools-frontend'
def main(argv=None):
return DevToolsF | rontend().handle_args(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
caphrim007/ansible | lib/ansible/modules/cloud/google/gcp_compute_ssl_policy_facts.py | Python | gpl-3.0 | 7,795 | 0.003464 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | # Imports
############################################################### | #################
from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest
import json
################################################################################
# Main
################################################################################
def main():
module = G... |
centrofermi/e3pipe | tasks/e3dbbackfill.py | Python | gpl-3.0 | 2,466 | 0.006894 | #!/usr/bin/env python
# *********************************************************************
# * Copyright (C) 2014 Luca Baldini (luca.baldini@pi.infn.it) *
# * *
# * For the license terms see the file LICENSE, distributed *
# * along ... | . | *
# *********************************************************************
#
# 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 opti... |
grundgruen/zipline | tests/pipeline/test_pipeline_algo.py | Python | apache-2.0 | 19,700 | 0.000051 | """
Tests for Algorithms using the Pipeline API.
"""
from unittest import TestCase
from os.path import (
dirname,
join,
realpath,
)
from nose_parameterized import parameterized
from numpy import (
array,
arange,
full_like,
float64,
nan,
uint32,
)
from numpy.testing import assert_alm... | def expected_close(self, date, asset):
if date < self.split_date:
lookup = self.closes
else:
lookup = self.adj_closes
return lookup.loc[date, asset]
def exists(self, date, asset):
return asset.start_date <= date <= asset.end_date
def test_attach_pipel... | attach_pipeline after initialize raises correctly.
"""
def initialize(context):
pass
def late_attach(context, data):
attach_pipeline(Pipeline(), 'test')
raise AssertionError("Shouldn't make it past attach_pipeline!")
algo = TradingAlgorithm(
... |
materia-coin/materia | share/rpcuser/rpcuser.py | Python | mit | 1,110 | 0.006306 | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.a... | ername as an argument.\n')
sys.exit(0)
username = sys.argv[1]
#This uses os.urandom() underneath
cryptogen = SystemRandom()
#Create 16 byte hex salt
salt_sequence = [cryptogen.randrange(256) for i in range(16)]
hexseq = list(map(hex, salt_sequence))
salt = "".join([x[2:] for x in hexseq])
#Create 32 byte b64 pa... | s.urandom(32))
digestmod = hashlib.sha256
if sys.version_info.major >= 3:
password = password.decode('utf-8')
digestmod = 'SHA256'
m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), digestmod)
result = m.hexdigest()
print("String to be appended to materia.conf:")
print("rpcauth="+username... |
NicoRahm/CGvsPhoto | CGvsPhoto/__init__.py | Python | mit | 193 | 0.005181 | from .im | age_loader import Database_loader
from .image_loader import Test_loader
from .model import M | odel
from .baseline_histograms import train_classifier
from .construct_DB import construct_DB |
openstack/tempest | tempest/api/volume/admin/test_backends_capabilities.py | Python | apache-2.0 | 2,618 | 0 | # Copyright 2016 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... | ls):
super(BackendsCapabilitiesAdminTestsJSON, cls).resource_setup()
# Get host list, formation: host@backend-name
cls.hosts = [
pool['name'] for pool in
cls.admin_scheduler_stats_client.list_pools()['pools']
]
@decorators.idempotent_id('3750af44-5ea2-4cd4-bc... | ')
def test_get_capabilities_backend(self):
"""Test getting backend capabilities"""
# Check response schema
self.admin_capabilities_client.show_backend_capabilities(self.hosts[0])
@decorators.idempotent_id('a9035743-d46a-47c5-9cb7-3c80ea16dea0')
def test_compare_volume_stats_values(... |
adamewing/GRIPper | lib/configtest.py | Python | mit | 1,660 | 0.005422 | #!/usr/bin/env | python
"""
Copyright (C) 2012 by Adam Ewing (adam.ewing@gmail.com)
Released under the MIT license, see LICENSE.txt
configtest.py checks required configuration options and files
"""
import ConfigParser
import sys
import os
def checkfile(file):
try:
open(file)
return True
except:
| return False
def check(cfgfile):
if not checkfile(cfgfile):
raise ValueError("Could not open config file: " + cfgfile)
valoptions = ('readLength',
'insertSize',
'minMapQ',
'minPeakSize',
'maxReadLen',
... |
fenixon/tiponpython | models/observacion.py | Python | gpl-3.0 | 1,177 | 0.024639 | """
tiponpython Simulacion de ensayos de acuiferos
Copyright 2012 Andres Pias, Mathias Chubrega, Alvaro Correa, Sebastian Daloia, Jesus Guibert
This file is part of tiponpython.
tiponpython 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
any later version.
tiponpython is distributed in the hop | e that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with tiponpython. If not, see http://www.gnu.... |
yifeng-li/deep_learning | main_SdA.py | Python | bsd-3-clause | 3,073 | 0.025057 | """
An example of running stacked denoising autoencoders.
Yifeng Li
CMMT, UBC, Vancouver
Sep. 23, 2014
Contact: yifeng.li.cn@gmail.com
"""
import os
import numpy
import SdA
import classification as cl
from gc import collect as gc_collect
numpy.warnings.filterwarnings('ignore') # Theano causes some warnings
path="... |
# test
test_set_y_pred=SdA.test_model(classifier, test_set_x_org, batch_size=200)
# evaluate classification performance
| perf,conf_mat=cl.perform(test_set_y_org,test_set_y_pred,numpy.unique(train_set_y_org))
print perf
print conf_mat
gc_collect()
|
chargebee/chargebee-python | chargebee/models/plan.py | Python | mit | 2,784 | 0.020833 | import json
from chargebee.model import Model
from chargebee import request
from chargebee import APIError
class Plan(Model):
class Tier(Model):
fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"]
pass
class ApplicableAddon(Mo... | ode", "period", \
"period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \
"free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \
"redirect_url", "enabled_in_hosted_pages", | "enabled_in_portal", "addon_applicability", "tax_code", \
"hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \
"sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \
"accounting_category4", "is_shippable", ... |
sulantha2006/Conversion | Python/RUSRandomForest/__init__.py | Python | mit | 24 | 0 | __author__ = 'Sulan | tha' | |
VirusTotal/content | Packs/CyberArkPAS/Integrations/CyberArkPAS/CyberArkPAS_test.py | Python | mit | 9,611 | 0.004578 | import pytest
from CyberArkPAS import Client, add_user_command, get_users_command, \
update_user_command, add_safe_command, update_safe_command, get_list_safes_command, get_safe_by_name_command, \
add_safe_member_command, update_safe_member_command, list_safe_members_command, add_account_command, \
update_... | , UPDATE_ACCOUNT_RAW_RESPONSE, UPDATE_ACCOUNT_CONTEXT),
(get_account_details_command, GET_ACCOUNT_ARGS, GET_ACCOUNT_RAW_RESPONSE, GET_ACCOUNT_CONTEXT),
(get_list_accounts_command, GET_LIST_ACCOUNT_ARGS, GET_LIST_ACCOUNT_RAW_RESPONSE, GET_LIST_ACCOUNT_CONTEXT),
(get_list_account_activity_command, GET_LIST_AC... | ITIES_RAW_RESPONSE,
GET_LIST_ACCOUNT_ACTIVITIES_CONTEXT),
])
def test_cyberark_pas_commands(command, args, http_response, context, mocker):
"""Unit test
Given
- demisto args
- raw response of the http request
When
- mock the http request result
Then
- create the context
- valida... |
jokuf/hack-blog | users/models.py | Python | mit | 1,710 | 0.000585 | from __future__ import unicode_literals
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from .managers import UserManager
cla... | help_text=_('Designates whether the user can log into this admin site.'),
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = | _('user')
verbose_name_plural = _('users')
def get_full_name(self):
'''
Returns the first_name plus the last_name, with a space in between.
'''
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
''... |
rmaceissoft/django-photologue | photologue/sitemaps.py | Python | bsd-3-clause | 1,809 | 0.005528 | """
The `Sitemaps protocol <http://en.wikipedia.org/wiki/Sitemaps>`_ allows a webmaster
to inform search engines about URLs on a website that are available for crawling.
Django comes with a high-level framework that makes generating sitemap XML files easy.
Install the sitemap application as per the `instructions in th... | h a lightbox).
class GallerySitemap(Sitemap):
def items(self):
# The following code is very basic and will probably cause problems with
# large querysets.
return Gallery.objects.on_site().is_public()
def lastmod(self, obj):
return obj.date_added
class PhotoSitemap(Sitemap):... | n Photo.objects.on_site().is_public()
def lastmod(self, obj):
return obj.date_added
|
partofthething/home-assistant | tests/components/xiaomi/test_device_tracker.py | Python | apache-2.0 | 8,787 | 0.000455 | """The tests for the Xiaomi router device tracker platform."""
import logging
from unittest.mock import MagicMock, call, patch
import requests
from homeassistant.components.device_tracker import DOMAIN
import homeassistant.components.xiaomi.device_tracker as xiaomi
from homeassistant.components.xiaomi.device_tracker ... | gger(__name__)
INVALID_USERNAME = "bob"
TOKEN_TIMEOUT_USERNAME = "tok"
URL_AUTHORIZE = "http://192.168.0.1/cgi-bin/luci/api/xqsystem/login"
URL_LIST_END = "api/misystem/devicelist"
FIRST_CALL = True
def mocked_requests(*args, **kwargs):
"""Mock requests.get invocations."""
class MockResponse:
"""Cl... |
def __init__(self, json_data, status_code):
"""Initialize the mock response class."""
self.json_data = json_data
self.status_code = status_code
def json(self):
"""Return the json of the response."""
return self.json_data
@property
... |
simark/simulavr | regress/test_opcodes/test_LDS.py | Python | gpl-2.0 | 2,639 | 0.018568 | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... | se, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a ... | loor, Boston, MA 02110-1301 USA.
#
###############################################################################
#
# $Id: test_LDS.py,v 1.1 2004/07/31 00:59:11 rivetwa Exp $
#
"""Test the LDS opcode.
"""
import base_test
from registers import Reg
class LDS_TestFail(base_test.TestFail): pass
class base_LDS(base_te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.