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 |
|---|---|---|---|---|---|---|---|---|
rickyschools/JARVIS | ml/learners.py | Python | mit | 1,120 | 0.001786 | from GIDEON.ml.ml_utilties import *
_run_types = ['production', 'diagnostics']
_load_types = [True, False]
class ActionModeler:
def __init__(self):
self._raw_features, self._target = load_action_data()
def run_diagnostics(self, save=True):
d = lambda x: ' ' if save else ' not '
print... | , request, use_saved=True):
request, _ = pre_processing(request)
# print(os.path.isfile(os.path.join(model_loc, model_name)))
if use_saved and os.path.isfile(os.path | .join(model_loc, model_name)):
model = read_saved_model()
else:
print('Running diagnostics before making prediction.')
model = self.run_diagnostics()
return model.predict(request)[0], max(model.predict_proba(request)[0])
|
uwcirg/true_nth_usa_portal | portal/migrations/versions/2ddfab3c6533_.py | Python | bsd-3-clause | 756 | 0.007937 | """empty message
Revision ID: 2ddfab3c6533
Revises: 2214f33d3a7b
Create Date: 2016-01-28 12:01:06.774836
"""
# revision iden | tifiers, used by Alembic.
revision = '2ddfab3c6533'
down_revision = '2214f33d3a7b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alem | bic - please adjust! ###
op.add_column('users', sa.Column(
'locale', sa.String(length=20), nullable=True))
op.add_column('users', sa.Column(
'timezone', sa.String(length=20), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please a... |
LLNL/spack | var/spack/repos/builtin/packages/dust/package.py | Python | lgpl-2.1 | 1,546 | 0.001294 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Dust(Package):
"""du + rust = dust. Like du but more intuitive."""
homepage = "https:... | sion'")
dust = Executable(join_path(self.spec["dust"].prefix.bin, "dust"))
output = dust(
"--version",
output=str.split,
)
print("stdout received fromm dust is '{}".format(output))
assert "Dust " in output
def test(self):
"""Run this | smoke test when requested explicitly"""
dustpath = join_path(self.spec["dust"].prefix.bin, "dust")
options = ["--version"]
purpose = "Check dust can execute (with option '--version')"
expected = ["Dust "]
self.run_test(
dustpath, options=options, expected=expected,... |
livoras/py-algorithm | searching/hash-chain.py | Python | mit | 1,550 | 0.002581 | #-*- coding: utf-8 -*-
class Hash():
def __init__(self):
self.size = 20
self.slots = []
| for i in xrange(0, 20):
self.slots.append([])
def __setitem__(self, key, value):
chain = self.slots[self.hash(key)]
for data in chain:
if data[0] == key:
data[1] = value
return True
chain.append([key, value])
def __getitem__(self... | ete(self, key):
slot = self.hash(key)
chain = self.slots[slot]
for i, data in enumerate(chain):
if data[0] == key:
del chain[i]
return True
raise ValueError("Key %s if not found." % key)
def hash(self, key):
return self.stoi(key) %... |
pjknkda/werkzeug | tests/contrib/__init__.py | Python | bsd-3-clause | 207 | 0 | # -*- codi | ng: utf-8 -*-
"""
tests.contrib
~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests the contrib modul | es.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
|
zhangf911/KlayGE | build_kfont.py | Python | gpl-2.0 | 435 | 0.02069 | #!/usr/bin/env python
#-*- coding: ascii -*-
from _ | _future__ import print_function
import sys
from blib_util import *
def build_kfont(build_info):
for compiler_info in build_info.compilers:
build_a_project("kfont", "kfont", build_info, compiler_info, True)
if __name__ == "__main__":
cfg = cfg_from_argv(sys.argv)
bi = build_info(cfg.compiler, cfg.archs,... | uild_kfont(bi)
|
huegli/automation | picrename/picrename/prnm/renops.py | Python | mit | 8,392 | 0.002741 | import os
import re
import logging
from picrename.prnm import fileops
class DateStrError(Exception):
pass
def exif_to_datetimestr(exif_data_string):
"""
Extracts the date from an EXIF tag and reformats it
"""
dateregex = re.compile(r"""
(?P<year>\d\d\d\d): # match the year
... |
newfullfname = os.path.join(
os.path.dirname(datetimestr_to_fullfname_dict[a_dtstr]),
newfname)
try:
logging.info("Renaming %r -> %r",
datetimestr_to_ful | lfname_dict[a_dtstr],
newfullfname)
os.rename(datetimestr_to_fullfname_dict[a_dtstr],
newfullfname)
except os.error as o |
minrk/oauthenticator | docs/source/example-oauthenticator.py | Python | bsd-3-clause | 3,918 | 0.00051 | """
Example OAuthenticator to use with My Service
"""
import json
from jupyterhub.auth import LocalAuthenticator
from oauthenticator.oauth2 import OAuthLoginHandler, OAuthenticator
from tornado.auth import OAuth2Mixin
from tornado.httputil import url_concat
from tornado.httpclient import HTTPRequest, AsyncHTTPClient... | lso be in the response to the token request,
# making this request unnecessary.
req = HTTPRequest(
"https://myservice.biz/api/user" | ,
method="GET",
headers={"Authorization": f"Bearer {access_token}"},
)
resp = await http_client.fetch(req)
resp_json = json.loads(resp.body.decode('utf8', 'replace'))
# check the documentation for what field contains a unique username
# it might not be th... |
MingoDynasty/FoscamSort | EmailController.py | Python | mit | 1,372 | 0 | import logging # Provides access to logging api.
import smtplib
class EmailController:
def __init__(self, username, password, server, port, sender_name):
self.logger = logging.getLogger(__name__)
self.username = username
self.password = password
self.server = server
self.p... | in(self.username, self.password)
body = '\r\n'.join(['To: %s' | % send_to,
'From: %s' % self.sender_name,
'Subject: %s' % subject,
'', text])
try:
self.logger.debug("Attempting to send....")
server.sendmail(self.username, [send_to], body)
self.logger.debu... |
kaksmet/servo | tests/wpt/web-platform-tests/tools/wptserve/wptserve/pipes.py | Python | mpl-2.0 | 13,913 | 0.000934 | from cgi import escape
import gzip as gzip_module
import re
import time
import types
import uuid
from cStringIO import StringIO
def resolve_content(response):
rv = "".join(item for item in response.iter_content())
| if type(rv) == unicode:
rv = rv.encode(response.encoding)
return rv
class Pipeline(object):
pipes = {}
def __i | nit__(self, pipe_string):
self.pipe_functions = self.parse(pipe_string)
def parse(self, pipe_string):
functions = []
for item in PipeTokenizer().tokenize(pipe_string):
if not item:
break
if item[0] == "function":
functions.append((self... |
molmod/zeobuilder | zeobuilder/gui/fields/__init__.py | Python | gpl-3.0 | 1,515 | 0.00264 | # -*- coding: utf-8 -*-
# Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Z... | Modeling, Vol. 48
# (7), 1530-1541, 2008
# DOI:10.1021/ci8000748
#
# Zeobuilder 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 shoul... | ses/>
#
#--
import read, edit, faulty, group, composed, optional
|
dylantelford/ccr-summer-internship | xmlBuckets/setup.py | Python | lgpl-3.0 | 395 | 0.005063 | #!/usr/bin/env python
from distutils.core import setup
setup(name='runBucket',
version='1.0.0',
license='LGPLv3',
author='Dylan Telford',
author_email='dylantelford@gmail.com | ',
url='https://github.com/ubccr/student-projects/tree/dtelford/dtelford/xmlScripts',
packages=['runBucket'],
scripts=['runBucket/runBucket.py'],
requires=['xml'])
| |
IZSVenezie/VetEpiGIS-Tool | plugin/poi_dialog.py | Python | gpl-2.0 | 6,037 | 0.003313 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'poi_dialog_base.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.se... | = QtWidgets.QLineEdit(Dialog)
self.lineEdit_longitude.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.Align | VCenter)
self.lineEdit_longitude.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit_longitude, 0, 1, 1, 1)
self.toolButton = QtWidgets.QToolButton(Dialog)
self.toolButton.setMinimumSize(QtCore.QSize(0, 59))
self.toolButton.setObjectName("toolButton")
self.g... |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/type_definition/test_rule_006.py | Python | gpl-3.0 | 1,173 | 0.004263 |
import os
import unittest
from vsg.rules import type_definition
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_006_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sT... | self.oFile)
self.assertEqual(oRule.vi | olations, [])
|
danielfrg/ec2hosts | ec2hosts/cli.py | Python | apache-2.0 | 1,208 | 0.001656 | from __future__ import print_function, absolute_import, division
import sys
import click
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
import ec2hosts
def main():
try:
cli(obj={})
except Exception as e:
import traceback
click.echo(traceback.format_exc(), err=True)
... | mand=True, context_settings=CONTEXT_SETTINGS)
@click. | version_option(prog_name='Anaconda Cluster', version=ec2hosts.__version__)
@click.pass_context
def cli(ctx):
ctx.obj = {}
if ctx.invoked_subcommand is None:
ctx.invoke(run)
@cli.command(short_help='Run')
@click.pass_context
def run(ctx):
click.echo("New /etc/hosts file:")
content = ec2hosts.ge... |
chriskiehl/Gooey | gooey/gui/components/widgets/slider.py | Python | mit | 1,260 | 0.001587 | import wx # type: ignore
| from gooey.gui import formatters
from | gooey.gui.components.widgets.bases import TextContainer
from gooey.python_bindings import types as t
class Slider(TextContainer):
"""
An integer input field
"""
widget_class = wx.Slider
def getWidget(self, *args, **options):
widget = self.widget_class(self,
... |
mostaphaRoudsari/Honeybee | src/Honeybee_Search EP Construction.py | Python | gpl-3.0 | 4,389 | 0.016405 | # Filter EnergyPlus Construction
#
# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Honeybee.
#
# Copyright (c) 2013-2020, Mostapha Sadeghipour Roudsari <mostapha@ladybug.tools>
# Honeybee is free software; you can redistribute it and/or modify
... | lt = main(_EPConst | rList, _standard, climateZone_, surfaceType_, keywords_)
if result!= -1:
EPSelectedConstr = result |
minghuascode/pyj | examples/flowpanel/FlowPanel.py | Python | apache-2.0 | 1,863 | 0.010735 | # -*- coding: iso-8859-1 -*-
import pyjd
#Ui components
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.FlowPanel import FlowPanel
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Label import Label
from pyjamas.ui.Image import Image
from pyjamas.ui.SimplePane | l import SimplePanel
from pyjamas import DOM
class FlowPanelDemo:
"""Demos the flow panel. Because of how the Flow | Panel works, all elements have to be inline elements.
Divs, tables, etc. can't be used, unless specified with CSS that they are inline or inline-block.
Because of how Vertical Panels work (with tables), we use CSS to display tables as inline-blocks.
IE, excluding IE8, doesn't support inline-bl... |
mir-dataset-loaders/mirdata | scripts/legacy/make_irmas_index.py | Python | bsd-3-clause | 6,590 | 0.002276 | import argparse
import glob
import hashlib
import json
import os
IRMAS_INDEX_PATH = '../mirdata/indexes/irmas_index.json'
def md5(file_path):
"""Get md5 hash of a file.
Parameters
----------
file_path: str
File path.
Returns
-------
md5_hash: str
md5 hash of data in file_... | (irmas_data_path, inst[0]))
annotation_checksum = md5(os.path.join(irmas_data_path, inst[1]))
irmas_index[index] = {
'audio': (inst[0], audio_checksum),
'annotation': (inst[1], annotation_checksum),
}
index += 1
with open(IRMAS_INDEX_PATH, 'w') as fhandle:
... | (irmas_index, fhandle, indent=2)
def make_irmas_test_index(irmas_data_path):
count = 1
irmas_dict = dict()
for root, dirs, files in os.walk(irmas_data_path):
for directory in dirs:
if 'Test' in directory:
for root_, dirs_, files_ in os.walk(
os.path.... |
gillett-hernandez/project-euler | Python/problem_15.py | Python | mit | 433 | 0.006928 | #!/usr/bin/env python3
# -* | - coding: utf-8 -*-
# @Author: Gillett Hernandez
# @Date: 201 | 6-07-14 17:06:40
# @Last Modified by: Gillett Hernandez
# @Last Modified time: 2017-08-10 12:39:06
from euler_funcs import timed
def count_routes(n):
result = 1
for i in range(1, n+1):
result = ((n+i) * result) // i
return result
@timed
def main():
print(count_routes(20))
if __name__ == ... |
sameerparekh/pants | tests/python/pants_test/backend/python/tasks/test_pytest_run.py | Python | apache-2.0 | 12,057 | 0.00423 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import glob
import o... |
report_basedir = os.path.join(self.build_root, 'dist', 'junit_option')
self.run_failing_tests(targets=[self.green, self.red], failed_targets=[self.red],
junit_xml_dir=report_basedir)
files = glob.glob(os.path.join(report_basedir, '*.xml'))
self.assertEqual(1, len(files), 'Ex... | )
junit_xml = files[0]
root = DOM.parse(junit_xml).documentElement
self.assertEqual(2, len(root.childNodes))
self.assertEqual(2, int(root.getAttribute('tests')))
self.assertEqual(1, int(root.getAttribute('failures')))
self.assertEqual(0, int(root.getAttribute('errors')))
self.assertEqual(0,... |
mkhuthir/learnPython | Book_learning-python-r1.1/ch5/performances.map.py | Python | mit | 392 | 0 | from time impo | rt time
mx = 2 * 10 ** 7
t = time()
absloop = []
for n in range(mx):
absloop.append(abs(n))
print('for loop: {:.4f} s'.format(time() - t))
t = time()
abslist = [abs(n) for n in range(mx)]
print('list comprehension: {:.4f} s'.format(time() - t))
t = time()
absmap | = list(map(abs, range(mx)))
print('map: {:.4f} s'.format(time() - t))
print(absloop == abslist == absmap)
|
annarev/tensorflow | tensorflow/python/kernel_tests/lrn_op_test.py | Python | apache-2.0 | 5,781 | 0.010552 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | shape, dtype=dtype)
lrn_op = nn.local_response_normalization(
inp,
name="lrn",
depth_radius=lrn_depth_radius,
bias=bias,
alpha=alpha,
beta=beta)
err = gradient_checker.compute_gradient_error(inp, shape, lrn_op, shape)
print("LRN Gradient error ... | self.assertLess(err, 1.0)
@test_util.run_deprecated_v1
def testGradients(self):
for _ in range(2):
self._RunAndVerifyGradients(dtypes.float32)
# Enable when LRN supports tf.float16 on GPU.
if not test.is_gpu_available():
self._RunAndVerifyGradients(dtypes.float16)
if __name__ ... |
itorres/junk-drawer | 2015/lp2pass.py | Python | unlicense | 2,627 | 0.000761 | #!/usr/bin/env python
import csv
import sys
import json
import hashlib
from subprocess import Popen, PIPE
from urlparse import urlparse
DEFAULT_GROUP = "lastpass-import"
class Record:
def __init__(self, d):
self.d = d
self.password = d['password']
if d['grouping'] in [None, "", "(none)... | ntry)
def writeToPass(self):
if len(self.items) == 1:
process = Popen(["pass", "insert", "-m", self.id], stdin=PIPE,
stdout=PIPE, stderr=None)
self.stdout = process.communicate(str(self))
self.result = process.returncode
else:
... | stdin=PIPE, stdout=PIPE, stderr=None)
self.stdout = process.communicate(str(v))
self.result = process.returncode
def __str__(self):
return self.text
class Records:
def __init__(self):
self.d = dict()
def add(self, r):
if r.... |
dirn/readthedocs.org | readthedocs/vcs_support/backends/git.py | Python | mit | 6,947 | 0.00072 | import re
import logging
import csv
import os
from StringIO import StringIO
from projects.exceptions import ProjectImportError
from vcs_support.backends.github import GithubContributionBackend
from vcs_support.base import BaseVCS, VCSVersion
log = logging.getLogger(__name__)
class Backend(BaseVCS):
supports_tag... | error (or no tags found)
if retcode != 0:
return []
return self.parse_tags(stdout)
def parse_tags(self, data):
"""
Parses output of show-ref --tags, eg:
3 | b32886c8d3cb815df3793b3937b2e91d0fb00f1 refs/tags/2.0.0
bd533a768ff661991a689d3758fcfe72f455435d refs/tags/2.0.1
c0288a17899b2c6818f74e3a90b77e2a1779f96a refs/tags/2.0.2
a63a2de628a3ce89034b7d1a5ca5e8159534eef0 refs/tags/2.1.0.beta2
c7fc3d16ed9dc0b19f0d27583ca661a64562d21... |
p2j/ip_tweet | iptweet.py | Python | mit | 2,893 | 0.001728 | import re
import os
import urllib.request
import tweepy
import json
import time
def tweet_ip():
IPTweet().do_update()
return
class IPTweet(object):
def __init__(self):
self.__location__ = os.path.realpath(os.path.join(
os.getcwd(), os.path.dirname(__file__)
))
def get... | ismyip.com/text') as url:
self.ip = url.read().decode('utf8').rstrip('\r\n')
return self
def get_old_ip(self | ):
try:
with open(os.path.join(self.__location__, 'ip.old')) as f:
self.old_ip = f.readline().rstrip('\r\n')
except:
self.old_ip = '0.0.0.0'
return self
def get_twitter_keys(self):
try:
with open(os.path.join(self.__location__, 'se... |
MegaWale/python-playb0x | scrapy/scrapyPlay/properties/properties/spiders/quotes.py | Python | mpl-2.0 | 641 | 0 | # -*- coding: utf-8 -*-
import scrapy
class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.topscrape.com/tag/humor/']
start_urls = ['http://quotes.topscrape.com/tag/humor/']
def parse(self, response):
for quote in response.css('div.quote'):
yield {
... | 'author': quote.xpath('span/small/text() | ').extract_first(),
}
next_page = response.css('li.next a::attr("href")').extract_first()
if next_page is not None:
yield response.follow(next_page, self.parse)
|
efajardo/osg-test | osgtest/tests/test_140_lcmaps.py | Python | apache-2.0 | 1,373 | 0.002185 | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
class TestLcMaps(osgunittest.OSGTestCase):
required_rpms = ['lcmaps', 'lcma | ps- | db-templates', 'vo-client', 'vo-client-lcmaps-voms']
def test_01_configure(self):
core.config['lcmaps.db'] = '/etc/lcmaps.db'
core.config['lcmaps.gsi-authz'] = '/etc/grid-security/gsi-authz.conf'
core.skip_ok_unless_installed(*self.required_rpms)
template = files.read('/usr/share/... |
bittercode/pyrrhic-ree | modules/onlineDocs.py | Python | gpl-2.0 | 530 | 0 | import webbrowser
import platform
def get_version():
version = platform.python_version()
if len(version) != 3: # This is to exclude minor versions. |
version = version[0:3]
return version
def open_doc(url):
webbrowser.open(url)
def open_library():
version = get_version()
url = "http://docs.python.org/ | {}/library/re.html".format(version)
open_doc(url)
def open_guide():
version = get_version()
url = "http://docs.python.org/{}/howto/regex.html".format(version)
open_doc(url)
|
yamt/neutron | quantum/tests/unit/metaplugin/test_metaplugin.py | Python | apache-2.0 | 13,773 | 0.000073 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | 'external_gateway_info': None}}
return data
def test_create_delete_network(self):
network1 = self._fake_network('fake1')
ret1 = self.plugin.create_network(self.context, network1)
self.assertEqual('fake1', ret1[FLAVOR_NETWORK])
network2 = self._fake_network('fake2')
... | |
bearstech/nuka | examples/docker_container.py | Python | gpl-3.0 | 258 | 0 | # -*- coding: utf-8 -*-
from nuka.hosts import DockerContainer
from nuka.tasks import shell
import nuka
host = DockerContainer(hostname='debian', image='bearstech/nuk | ai')
async def my_tasks(host):
await shell.shell('whoami')
|
nuka.run(my_tasks(host))
|
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/shortuuid/__init__.py | Python | agpl-3.0 | 128 | 0 | from shortuuid.main import (
encode,
decode,
uuid,
| random,
| get_alphabet,
set_alphabet,
ShortUUID,
)
|
djds23/pygotham-1 | pygotham/schedule/models.py | Python | bsd-3-clause | 7,610 | 0.000263 | """Schedule models.
Much of this module is derived from the work of Eldarion on the
`Symposion <https://github.com/pinax/symposion>`_ project.
Copyright (c) 2010-2014, Eldarion, Inc. and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted p... | ontent_override = db.Column(db.Text)
start = db.Column(db.Time, nullable=False)
end = db.Column(db.Time, nullable=False)
day_id = db.Column(db.Int | eger, db.ForeignKey('days.id'), nullable=False)
day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic'))
rooms = db.relationship(
'Room',
secondary=rooms_slots,
backref=db.backref('slots', lazy='dynamic'),
order_by=Room.order,
)
def __str__(self):
... |
haoqili/MozSecWorld | apps/msw/admin.py | Python | bsd-3-clause | 504 | 0.003968 | from msw.models import P | age, RichText, MembersPostUser, MembersPostText
from django.contrib import admin
# could add more complicated stuff here consult:
# tutorial: https://docs.djangoproject.com/en/dev/intro/tutorial02/#enter-the-admin-site
# tutorial finished admin.py: https://github.com/haoqili/Django-Tutorial-Directory/blob/master... | site.register(MembersPostUser)
admin.site.register(MembersPostText)
|
samuelwu90/PynamoDB | tests/test_consistent_hash_ring.py | Python | mit | 2,081 | 0.004805 | """
test_consistent_hash_ring.py
~~~~~~~~~~~~
Tests that PersistenceEngine's put, get, delete methods raise the correct error codes.
Run tests with:
clear; python -m unittest discover -v
"""
import unittest
import consistent_hash_ring
import util
import random
class T | estSequenceFunctions(unittest.TestCase):
def setUp(self):
self.consistent_hash_ring = consistent_hash_ring.ConsistentHashRing()
self.node_hash = util.get_hash('value')
def tearDow | n(self):
pass
def test_add_node_hash(self):
self.consistent_hash_ring.add_node_hash(self.node_hash)
self.assertTrue(self.node_hash in self.consistent_hash_ring._hash_ring)
def test_add_multiple_node_hashes(self):
for x in xrange(10):
node_hash = util.get_hash(str(ra... |
diogocs1/comps | web/addons/l10n_ma/__openerp__.py | Python | apache-2.0 | 2,154 | 0.004669 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010 kazacube (http://kazacube.com).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | on) any later version.
#
# This program is d | istributed 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 Public License
#... |
ntucllab/striatum | striatum/bandit/exp4p.py | Python | bsd-2-clause | 6,781 | 0 | """ EXP4.P: An extention to exponential-weight algorithm for exploration and
exploitation. This module contains a class that implements EXP4.P, a contextual
bandit algorithm with expert advice.
"""
import logging
import six
from six.moves import zip
import numpy as np
from striatum.bandit.bandit import BaseBandit
L... | on_id)
action_recommendation.append({
'action': action,
'estimated_reward': estimated_reward[action_id],
'uncertainty': uncertainty[action_id],
'score': score[action_id],
})
| self.n_total += 1
history_id = self._historystorage.add_history(
context, action_recommendation, reward=None)
return history_id, action_recommendation
def reward(self, history_id, rewards):
"""Reward the previous action with reward.
Parameters
----------... |
koenedaele/skosprovider | examples/dump_jsonld.py | Python | mit | 3,074 | 0.000976 | # -*- coding: utf-8 -*-
'''
This example demonstrates the skosprovider API with a simple
DictionaryProvider containing just three items.
'''
from pyld import jsonld
import json
from skosprovider.providers import DictionaryProvider
from skosprovider.uri import UriPatternGenerator
from skosprovider.skos import ConceptS... | {'type': 'prefLabel', 'language': 'nl', 'label': 'Bomen per soort'}
],
'type': 'collection',
'members': ['1', '2'],
'notes': [
{
'type': 'editorialNote',
'language': 'en',
'note': 'As seen in <em>How to Recognise Different Types of Trees from Quite a Long Way ... | logy'],
'dataset': {
'uri': 'http://id.trees.org/dataset'
}
},
[larch, chestnut, species],
uri_generator=UriPatternGenerator('http://id.trees.org/types/%s'),
concept_scheme=ConceptScheme('http://id.trees.org')
)
# Generate a doc for a cs
doc = jsonld_dumper(provider, CONTEXT... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.1/Lib/xml/dom/pulldom.py | Python | mit | 10,143 | 0.001577 | import xml.sax
import xml.sax.handler
import types
try:
_StringTypes = [types.StringType, types.UnicodeType]
except AttributeError:
_StringTypes = [types.StringType]
START_ELEMENT = "START_ELEMENT"
END_ELEMENT = "END_ELEMENT"
COMMENT = "COMMENT"
START_DOCUMENT = "START_DOCUMENT"
END_DOCUMENT = "END_DOCUMENT"
... | sult = self.elementStack[-1]
| del self.elementStack[-1]
return result
def setDocumentLocator(self, locator):
self._locator = locator
def startPrefixMapping(self, prefix, uri):
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix or ''
def endPrefixMapping(self, ... |
Roger/couchdb-python | couchdb/tests/mapping.py | Python | bsd-3-clause | 12,137 | 0.001813 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
from decimal import Decimal
import doctest
import unittest
from couchdb import design, mapping
from... | ld(mapping.DecimalField)
thing = Thing(numbers=[Decimal('1.0'), Decimal('2.0')])
| assert isinstance(thing.numbers, mapping.ListField.Proxy)
assert '1.0' not in thing.numbers
assert Decimal('1.0') in thing.numbers
def test_proxy_count(self):
class Thing(mapping.Document):
numbers = mapping.ListField(mapping.DecimalField)
thing = Thing(numbers=[Decim... |
iserko/jira2fogbugz | src/jira2fogbugz/__init__.py | Python | mit | 8,941 | 0.002461 | #!/usr/bin/env python
import argparse
import sys
import time
import traceback
from jira.client import JIRA
from jira.exceptions import JIRAError
from fogbugz import FogBugz
from fogbugz import FogBugzLogonError, FogBugzConnectionError
RECENTLY_ADDED_CASES = {}
FOGBUGZ_FIELDS = ('ixBug,ixPersonAssignedTo,ixPersonEdite... | ', 'Epic', 'Theme', 'Technical task'):
data['sCategory'] = 'Feature'
elif jis.fields.issuetype.name in ('Bug'):
data['sCategory'] = 'Bug'
else:
raise Exception("Unknown issue type: {0}".format(jis.fields.issuetype.name))
if getattr(jis.fields, 'parent', None):
parent = jis.f... | tmp = jira.search_issues('key={0}'.format(parent.key))
if len(tmp) != 1:
raise Exception("Was expecting to find 1 result for key={0}. Got {1}".format(parent.key, len(tmp)))
parent_issue = create_issue(tmp[0])
data['ixBugParent'] = parent_issue
if jis.fields.issuelinks:
... |
Nexenta/cinder | cinder/tests/unit/volume/drivers/test_tegile.py | Python | apache-2.0 | 18,078 | 0 | # Copyright (c) 2015 by Tegile Systems, 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
#
# Unle... | e(test.TestCase):
def setUp(self):
self.ctxt = context.get_admin_context()
self.configuration = test_config
super(TegileIntelliFlashVolumeDriverTestCase, self).setUp()
def test_create_volume(self):
tegile_driver = self.get_object(self.configuration)
with mock.patch.objec... | 'metadata': {'pool': 'testPool',
'project': test_config.tegile_default_project
}
}, tegile_driver.create_volume(test_volume))
def test_create_volume_fail(self):
tegile_driver = self.get_object(self.configuration)
with m... |
chuanchang/tp-libvirt | virttest/utils_misc.py | Python | gpl-2.0 | 81,782 | 0.000648 | """
Virtualization test utility functions.
:copyright: 2008-2009 Red Hat Inc.
"""
import time
import string
import random
import socket
import os
import stat
import signal
import re
import logging
import commands
import fcntl
import sys
import inspect
import tarfile
import shutil
import getpass
import ctypes
from aut... | end SIGTERM signal to a process with matched pattern.
:param pattern: normally only matched against the process name
"""
cmd = "pkill -f %s" % pattern
result = utils.run(cmd, ignore_status=True)
if result.exit_status:
logging.error("Failed to run '%s': %s", cmd, result)
else:
log... | s(pid):
return len(os.listdir('/proc/%s/fd' % pid))
def get_virt_test_open_fds():
return get_open_fds(os.getpid())
def process_or_children_is_defunct(ppid):
"""Verify if any processes from PPID is defunct.
Attempt to verify if parent process and any children from PPID is defunct
(zombie) or not... |
blorenz/indie-film-rentals | indiefilmrentals/products/migrations/0006_auto__add_field_baseindierentalproduct_brand.py | Python | bsd-3-clause | 6,372 | 0.006591 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'BaseIndieRentalProduct.brand'
db.add_column('products_baseindierentalproduct', 'brand',
... | 100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'products.baseindierentalproduct': {
'Meta': {'object_name': 'BaseIndieRentalProduct', '_ormbases': ['shop.Product']},
'brand': ('django.db.models.fields.related.ForeignKey', | [], {'to': "orm['products.Brand']"}),
'crossSell': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'crossSell_rel_+'", 'null': 'True', 'to': "orm['products.BaseIndieRentalProduct']"}),
'description': ('django.db.models.fields.TextField', [], {}),
... |
futurice/schedule | schedulesite/schedulesite/settings.py | Python | bsd-3-clause | 5,140 | 0.000973 | """
Django settings for schedulesite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ..... | SetUserMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.co | ntrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'middleware.CustomHeaderMiddleware',
)
AUTH_USER_MODEL = 'futuschedule.FutuUser'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.... |
mbrner/funfolding | setup.py | Python | mit | 1,277 | 0 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='funfolding',
version... | rs=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
| 'Programming Language :: Python :: 3.6',
],
keywords='unfolding',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=[
'numpy',
'scikit-learn>=0.18.1',
'emcee',
'pymc3',
'scipy',
'futures',
'matplotlib',
... |
gkabbe/Python-Kurs2015 | Lösungen/Woche1/password.py | Python | gpl-2.0 | 341 | 0.002933 | passwort = "geheim"
feh | lversuche = 0
while True:
user_input = raw_input("Passwort eingeben:\n")
if user_input == passwort:
print "Hello User!"
break
else:
fehlversuche += 1
print "Fehlversuche:", fehlversuche
if fehlversuche == 3:
| print "Zu viele Fehlversuche"
break
|
utkbansal/tardis | tardis/plasma/properties/nlte.py | Python | bsd-3-clause | 9,723 | 0.007199 | import logging
import os
import numpy as np
import pandas as pd
from tardis.plasma.properties.base import (PreviousIterationProperty,
ProcessingPlasmaProperty)
from tardis.plasma.properties import PhiSahaNebular, PhiSahaLTE
__all__ = ['PreviousElectronDensities', 'PreviousB... | e])
output_file.write(self.plasma_parent.v_inner[zone])
output_file.write(self.plasma_parent.v_outer[zone])
for zone, _ in enumerate(electron_densities):
with open('He_NLTE_Files/abundances_{}.txt'.format(zone), 'w') as \
output_file:
... | _number_density[zone].ix[
element].sum()
except:
number_density = 0.0
output_file.write(number_density)
helium_lines = lines[lines['atomic_number']==2]
helium_lines = helium_lines[helium_lines['ion_numbe... |
nmayorov/scipy | scipy/special/_precompute/wrightomega.py | Python | bsd-3-clause | 979 | 0 | import numpy as np
try:
import mpmath # type: ignore[import]
except ImportError:
pass
def mpmath_wrightomega(x):
return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
def wrightomega_series_error(x):
series = x
desired = mpmath_wrightomega(x)
return abs(series - desired) / desired
de... | s(exponential_approx - desired) / desired
def main():
desired_error = 2 * np.finfo(float).eps
print('Series Error')
for x in [1e5, 1e10, 1e15, 1e20]:
with mpmath.workdps(100):
error = wrightomega_series_error(x)
print(x, error, error < desired_error)
print('Exp error')
... | print(x, error, error < desired_error)
if __name__ == '__main__':
main()
|
frreiss/tensorflow-fred | tensorflow/python/autograph/converters/return_statements_test.py | Python | apache-2.0 | 5,879 | 0.012587 | # Copy | right 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 la... | 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.
# ==============================================================================
"""Tests for return_statements module."""
from __futu... |
akaszynski/vtkInterface | examples/01-filter/distance-between-surfaces.py | Python | mit | 3,157 | 0.001901 | """
Distance Between Two Surfaces
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compute the average thickness between two surfaces.
For example, you might have two surfaces that represent the boundaries of
lithological layers in a subsurface geological model and you want to know the
average thickness of a unit between those boundari... | )
p.add_mesh(h1, color=True, opacity=0.75, smooth_shading=True)
p.show()
###############################################################################
# Nearest Neighbor Distance
# +++++++++++++++++++++++++
#
# You could also use a KDTree to compare the distance between each point of the
# upper surface and the nea... | ill be
# noticeably faster than a ray trace, especially for large surfaces.
from scipy.spatial import KDTree
tree = KDTree(h1.points)
d, idx = tree.query(h0.points )
h0["distances"] = d
np.mean(d)
###############################################################################
p = pv.Plotter()
p.add_mesh(h0, scalars="... |
gogrean/SurfFit | pyxel/prof.py | Python | gpl-3.0 | 13,240 | 0.002115 | import numpy as np
import matplotlib.pyplot as plt
from .utils import rotate_point, bin_pix2arcmin, get_bkg_exp
from .messages import ErrorMessages
from .image import Image
class Region(object):
def get_bin_vals(self, counts_img, bkg_img,
exp_img, pixels_in_bin, only_net_cts=False):
"""Calculate ... | bkg_cts += bkg_img_data[i][j, k]
exp_raw += exp_val
exp_bkg += exp_val_bkg / bkgnorm
net_cts += counts_img_data[i][j, k] - bkg_img_data[i][j, k] * bkg_corr_i
if only_net_cts:
return net_cts
raw_rate = raw_cts / exp_raw
bkg_r... | rr_net_rate = np.sqrt(raw_cts / exp_raw**2 + bkg_cts / exp_bkg**2)
return raw_cts, net_cts, bkg_cts, \
raw_rate, err_raw_rate, net_rate, err_net_rate, bkg_rate, err_bkg_rate
def merge_bins(self, counts_img, bkg_img, exp_img,
min_counts, islog=True):
bkg_img, exp_im... |
frol/Fling-receiver | apps/fling_receiver/views.py | Python | mit | 2,528 | 0.007516 | from coffin.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect
from .forms import FlingReceiverAddForm, FlingReceiverEditForm
from .models import FlingReceiver
def root(request, template_name='root.html'):
r... | quest, form_class=FlingReceiverAddForm,
template_name='fling_receiver/fling_receiver_add.html'):
form = form_class(request.POST or None, initial={'user': request.user})
if form.is_valid():
form.save()
return redirect('fling_receiver_list')
return TemplateResponse(request, template_na... | l'):
fling_receiver = get_object_or_404(FlingReceiver, id=fling_receiver_id, user=request.user)
form = form_class(request.POST or None, instance=fling_receiver)
if form.is_valid():
form.save()
return redirect('fling_receiver_list')
return TemplateResponse(request, template_name,
... |
w495/python-video-shot-detector | shot_detector/utils/__init__.py | Python | bsd-3-clause | 348 | 0 | # -*- coding: utf8 -*-
"""
Some utils
"""
from __future__ import absolute_import, division, print_function
from .config_arg_par | ser import ConfigArgParser
from .lazy_helper import LazyHelper
from .lazy_helper_wrapper import LazyHelperWrapper
from .log_meta import LogMeta
from .log_settings import LogSetting
f | rom .repr_dict import ReprDict
|
pyaiot/pyaiot | pyaiot/tests/test_messaging.py | Python | bsd-3-clause | 2,476 | 0 | """pyaiot messaging test module."""
import json
from pytest import mark
from pyaiot.common.messaging import Message
@mark.parametrize('message', [1234, "test", "àéèïôû"])
def test_serialize(message):
serialized = Message.serialize(message)
assert serialized == json.dumps(message, ensure_ascii=False)
def ... | ialized == Message.serialize({'type': 'reset', 'uid': '1234'})
def test_discover_node():
serialized = Message.discover_node | ()
assert serialized == Message.serialize({'request': 'discover'})
@mark.parametrize('value', [1234, "test", "àéèïôû"])
def test_update_node(value):
serialized = Message.update_node('1234', 'test', 'value')
assert serialized == Message.serialize(
{'type': 'update', 'uid': '1234', 'endpoint': 'te... |
wtbarnes/aia_response | make_figures.py | Python | mit | 2,177 | 0.034451 | #name:make_figures.py
#author:Will Barnes
#Description: make some figures useful to notes on AIA response functions
import numpy as np
import matplotlib.pyplot as plt
import seaborn.apionly as sns
def display_aia_response_control_flow():
"""Show the control flow of the IDL programs used to compute AIA response fu... |
def plot_aia_response_functions(raw_response_file,fix_response_file):
"""Plot AIA temperature response functions as computed by SSW"""
#Load data
raw_tresp,fix_tresp = np.loadtxt(raw_response_file),np.loadtxt(fix_response_file)
#set labels
aia_labs = [r'$94\,\,\AA$',r'$131\,\,\AA$',r'$171\,\,\AA$... | ax[0].plot(10**raw_tresp[:,0],raw_tresp[:,i],linewidth=2,linestyle='-',color=sns.color_palette('deep')[i-1],label=aia_labs[i-1])
ax[0].plot(10**fix_tresp[:,0],fix_tresp[:,i],linewidth=2,linestyle='--',color=sns.color_palette('deep')[i-1])
#normalized
ax[1].plot(raw_tresp[:,0],raw_tresp[:,i]/np.... |
syci/partner-contact | base_location/models/res_city_zip.py | Python | agpl-3.0 | 1,353 | 0 | # Copyright 2016 Nicolas Bessi, Camptocamp SA
# Copyright 2018 Aitor Bouzas <aitor.bouzas@adaptivecity.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResCityZip(models.Model):
"""City/locations completion object"""
_name = "res.city.zip"
_... | city_id)",
"You already have a zip with that code in the same city. "
"The zip code must be unique within it's city",
)
]
@api.depends("name", "city_id")
def _compute_new_display_name(self):
for rec in self:
name = [rec.name, rec.city_id.name]
... | if rec.city_id.country_id:
name.append(rec.city_id.country_id.name)
rec.display_name = ", ".join(name)
|
nuxeh/morph | morphlib/localrepocache_tests.py | Python | gpl-2.0 | 6,502 | 0 | # Copyright (C) 2012-2015 Codethink Limited
#
# 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; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but ... | escaped)
d | ef test_noremote_error_message_contains_repo_name(self):
e = morphlib.localrepocache.NoRemote(self.repourl, [])
self.assertTrue(self.repourl in str(e))
def test_avoids_caching_local_repo(self):
self.lrc.fs.makedir('/local/repo', recursive=True)
self.lrc.cache_repo('file:///local/rep... |
hoangt/core | core/tools/generator/wizard/config.py | Python | agpl-3.0 | 2,087 | 0.008146 | from PyQt4 import QtCore, QtGui
import os
class ConfigPage(QtGui.QWizardPage):
def __init__(self, templates, parent=None):
super(ConfigPage, self).__init__(parent)
#self.setTitle("Configuration")
#self.setSubTitle("Alter configuration and build your own platform.")
#self.setPixmap(... | i.QWidget()
self.hsplit.insertWidget(0, self.panel)
self.model = self.templates.getModel(self.panel)
self.view.setModel(self.model)
self.view.expandAll()
| self.view.setColumnWidth(0, 220)
self.view.setColumnWidth(1, 20)
self.setLayout(self.layout)
#self.vsplit.moveSplitter(280,1)
#self.hsplit.moveSplitter(120,1)
|
chrsrds/scikit-learn | examples/impute/plot_missing_values.py | Python | bsd-3-clause | 5,503 | 0.001454 | """
====================================================
Imputing missing values before building an estimator
====================================================
Missing values can be replaced by the mean, the median or the most frequent
value using the basic :class:`sklearn.impute.SimpleImputer`.
The median is a mor... | g', 'b', 'orange']
# plot diabetes results
plt.figure(figsize=(12, 6))
ax1 = plt.subplot(121)
for j in xval:
ax1.barh(j, mses_diabetes[j], xerr=stds_diabetes[j],
color=colors[j], alpha=0.6, align='center')
ax1.set_title('Imputation Techniques with Diabetes Data')
ax1.set_xlim(left=np.min(mses_ | diabetes) * 0.9,
right=np.max(mses_diabetes) * 1.1)
ax1.set_yticks(xval)
ax1.set_xlabel('MSE')
ax1.invert_yaxis()
ax1.set_yticklabels(x_labels)
# plot boston results
ax2 = plt.subplot(122)
for j in xval:
ax2.barh(j, mses_boston[j], xerr=stds_boston[j],
color=colors[j], alpha=0.6, align='c... |
twtrubiks/pillow-examples | resizePicture/resize.py | Python | mit | 2,818 | 0.021127 | #coding=utf8
import os, sys
from PIL import Image
from PIL import ImageFile
import glob
output_dir = "resized_images"
def main():
# 找出路徑下全部的圖片檔案
types = ('*.png', '*.jpg', '*.jpeg' ,'*.bmp' ,'*.gif') # the tuple of file types
all_image_files = []
for files in types:
all_image_files.extend(gl... | 100))
height = int((height * float(ratio)/100))
| # Image.resize(size, resample=0)
# size – The requested size in pixels, as a 2-tuple: (width, height). width and height type int
img = img.resize( (width ,height) ,Image.ANTIALIAS)
image_filename = output_dir + "/" + image_file
print "Save to " + image_filename
img.save(ima... |
ardi69/pyload-0.4.10 | pyload/plugin/crypter/MegaRapidCz.py | Python | gpl-3.0 | 779 | 0.017972 | # -*- coding: utf-8 -*-
from pyload.plugin.internal.SimpleCrypter import SimpleCrypter
class MegaRapidCz(SimpleCrypter):
__name = "MegaRapidCz"
__type = "crypter"
__version = "0.02"
__pattern = r'http://(?:www\.)?(share|mega)rapid\.cz/slozka/\d+/\w+'
__config = [("use_premium" , "bo... | on = """Share-Rapid.com folder | decrypter plugin"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
LINK_PATTERN = r'<td class="soubor".*?><a href="(.+?)">'
|
Spferical/matrix-chatbot | main.py | Python | mit | 17,094 | 0.000059 | #!/usr/bin/env python3
import time
from matrix_client.client import MatrixClient
from matrix_client.api import MatrixRequestError
from requests.exceptions import ConnectionError, Timeout
import argparse
import random
from configparser import ConfigParser
import re
import traceback
import urllib.parse
import logging
imp... | e room the given event took place in."""
return self.client.rooms[event['room_id']]
def handle_command(self, event, command, args):
"""Handles the given command, possibly sending a reply to it."""
command = command.lower()
if command == '!rate':
| if args:
num = re.match(r'[0-9]*(\.[0-9]+)?(%|)', args[0]).group()
if not num:
self.reply(event, "Error: Could not parse number.")
return
if num[-1] == '%':
rate = float(num[:-1]) / 100
... |
val-github/lammps-dev | tools/python/neb_combine.py | Python | gpl-2.0 | 2,172 | 0.020718 | #!/usr/local/bin/python
# make new dump file by combining snapshots from multiple NEB replica dumps
# Syntax: neb_combine.py -switch arg(s) -switch arg(s) ...
# -o outfile = new dump file
# each snapshot has NEB atoms from all replicas
# -r dump1 dump2 ... = replica dump files of NEB atoms
#... | e(t[0])
nback = back.snaps[0].nselect
idvec = range(ntotal+1,ntotal+nback+1)
back.setv("id",idvec)
else: nback = 0
ntotal += nback
# write out each snaps | hot
# natoms = ntotal, by overwriting nselect
# add background atoms if requested
times = d[0].time()
for time in times:
d[0].tselect.one(time)
i = d[0].findtime(time)
hold = d[0].snaps[i].nselect
d[0].snaps[i].nselect = ntotal
d[0].write(outfile,1,1)
d[0].snaps[i].nselect = hold
for one in d[1:]:
on... |
crmccreary/openerp_server | openerp/tools/test_reports.py | Python | agpl-3.0 | 13,310 | 0.005259 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | ult values of the
wizard form.
:param wiz_buttons: a list of button names, or button icon strings, which
should be preferred to press during the wizard.
Eg. | 'OK' or 'gtk-print'
:param our_module: the name of the calling module (string), like 'account'
"""
if not our_module and isinstance(action_id, basestring):
if '.' in action_id:
our_module = action_id.split('.', 1)[0]
if context is None:
context = {}
else:
co... |
liberation/django-admin-tools | admin_tools/dashboard/modules.py | Python | mit | 24,954 | 0.000641 | """
Module where admin tools dashboard modules classes are defined.
"""
from django.utils.text import capfirst
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.utils.itercompat i | mport is_iterable
from admin_tools.utils import AppListElementMixin, uniquify
class DashboardModule(object):
"""
Base class for all dashboard modules.
Dashboard modules have the following properties:
``e | nabled``
Boolean that determines whether the module should be enabled in
the dashboard by default or not. Default value: ``True``.
``draggable``
Boolean that determines whether the module can be draggable or not.
Draggable modules can be re-arranged by users. Default value: ``True``... |
Abdoctor/behave | behave/formatter/plain.py | Python | bsd-2-clause | 4,689 | 0.000213 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from behave.formatter.base import Formatter
from behave.model_describe import ModelPrinter
from behave.textutil import make_indentation
# -----------------------------------------------------------------------------
# CLASS: PlainFormatter
# ------------... | (doc-strings)
* table
* tags (maybe)
"""
name = "plain"
description = "Very basic formatter with maximum compatibility"
SHOW_MULTI_LINE = True
SHOW_TAGS = False
SHOW_A | LIGNED_KEYWORDS = False
DEFAULT_INDENT_SIZE = 2
def __init__(self, stream_opener, config, **kwargs):
super(PlainFormatter, self).__init__(stream_opener, config)
self.steps = []
self.show_timings = config.show_timings
self.show_multiline = config.show_multiline and self.SHOW_MULT... |
alxgu/ansible | lib/ansible/modules/network/fortios/fortios_firewall_DoS_policy.py | Python | gpl-3.0 | 14,026 | 0.001497 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... | n:
- Comment.
ds | taddr:
description:
- Destination address name from available addresses.
suboptions:
name:
description:
- Address name. Source firewall.address.name firewall.addrgrp.name.
... |
tal-nino/edwin | edwinServer/common/database_all.py | Python | apache-2.0 | 267 | 0 | # -*- cod | ing: utf-8 -*-
'''
'''
from __future__ import absolute_import
from __future__ import with_statement
from . import database_meta
from . import database_tera
def closeAllConnections():
database_meta.close | Connection()
database_tera.closeConnection()
|
alshedivat/tensorflow | tensorflow/python/ops/check_ops.py | Python | apache-2.0 | 47,658 | 0.005267 | # 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... | ive',
v1=['debugging.assert_negative', 'assert_negative'])
@deprecation.deprecated_endpoints('assert_negative')
def assert_negative(x, data=None, summarize=None, message=None, name=None):
"""Assert the condition `x < 0` holds element-wise.
Example of adding a dependency to an operation:
```python
with tf.... | e means, for every element `x[i]` of `x`, we have `x[i] < 0`.
If `x` is empty this is trivially satisfied.
Args:
x: Numeric `Tensor`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each ten... |
smurfix/parsimonious | parsimonious/nodes.py | Python | mit | 13,036 | 0.00069 | """Nodes that make up parse trees
Parsing spits out a tree of these, which you can then tell to walk itself and
spit out a useful value. Or you can walk it yourself; the structural attributes
are public.
"""
# TODO: If this is slow, think about using cElementTree or something.
from inspect import isfunction
from sys ... | nto something useful
Performs a depth-first traversal of an AST. Subclass this, add methods for
each expr | you care about, instantiate, and call
``visit(top_node_of_parse_tree)``. It'll return the useful stuff. This API
is very similar to that of ``ast.NodeVisitor``.
These could easily all be static methods, but that would add at least as
much weirdness at the call site as the ``()`` for instantiation. And ... |
capstone-rust/capstone-rs | capstone-sys/capstone/bindings/python/capstone/mos65xx_const.py | Python | mit | 3,179 | 0 | # For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [mos65xx_const.py]
MOS65XX_REG_INVALID = 0
MOS65XX_REG_ACC = 1
MOS65XX_REG_X = 2
MOS65XX_REG_Y = 3
MOS65XX_REG_P = 4
MOS65XX_REG_SP = 5
MOS65XX_REG_DP = 6
MOS65XX_REG_B = 7
MOS65XX_REG_K = 8
MOS65XX_REG_ENDING = 9
MOS65XX_AM_NONE = 0
MOS65XX_AM_IMP = 1
MOS65XX_A... | LONG = 14
MOS65XX_AM_ZP_IND_LONG_Y = 15
MOS65XX_AM_ABS = 16
MOS65XX_AM_ABS_X = 17
MOS65XX_AM_ABS_Y = 18
MOS65XX_AM_AB | S_IND = 19
MOS65XX_AM_ABS_X_IND = 20
MOS65XX_AM_ABS_IND_LONG = 21
MOS65XX_AM_ABS_LONG = 22
MOS65XX_AM_ABS_LONG_X = 23
MOS65XX_AM_SR = 24
MOS65XX_AM_SR_IND_Y = 25
MOS65XX_INS_INVALID = 0
MOS65XX_INS_ADC = 1
MOS65XX_INS_AND = 2
MOS65XX_INS_ASL = 3
MOS65XX_INS_BBR = 4
MOS65XX_INS_BBS = 5
MOS65XX_INS_BCC = 6
MOS65XX_INS_B... |
leppa/home-assistant | tests/helpers/test_dispatcher.py | Python | apache-2.0 | 4,196 | 0.000238 | """Test dispatcher helpers."""
import asyncio
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
dispatcher_connect,
dispatcher_send,
)
from tests.common import get_test_home_assistant
class TestHelpersDispatcher:
"""Tests for discovery h... | er_send(self.hass, "test", "bla")
self.hass.block_till_done()
assert calls == [3, "bla"]
def test_simple_function_unsub(self):
"""Test simple function (executor) and unsub."""
calls1 = []
calls2 = []
def test_funct1(data):
"""Test function."""
... | "
calls2.append(data)
dispatcher_connect(self.hass, "test1", test_funct1)
unsub = dispatcher_connect(self.hass, "test2", test_funct2)
dispatcher_send(self.hass, "test1", 3)
dispatcher_send(self.hass, "test2", 4)
self.hass.block_till_done()
assert calls1 == [... |
steveherrin/PhDThesis | Thesis/scripts/make_bb_spectrum_plot.py | Python | mit | 5,583 | 0.003582 | import ROOT
from math import pi, sqrt, pow, exp
import scipy.integrate
import numpy
from array import array
alpha = 7.2973e-3
m_e = 0.51099892
Z_Xe = 54
Q = 2.4578
def F(Z, KE):
E = KE + m_e
W = E/m_e
Z0 = Z + 2
if W <= 1:
W = 1 + 1e-4
if W > 2.2:
a = -8.46e-2 + 2.48e-2*Z0 + 2.... | "")
l_majoron.AddEntry(bb0nX_graphs[3], "0#nu#beta#beta#chi^{0}(#chi^{0}) (n=3)", "l")
l_majoron.AddEntry(None, "", "")
l_majo | ron.AddEntry(bb0nX_graphs[5], "0#nu#beta#beta#chi^{0}#chi^{0} (n=7)", "l")
l_majoron.Draw()
dummy = raw_input("Press Enter...")
|
YuepengGuo/sina_weibo_crawler | crawler/toolkit/weibo.py | Python | apache-2.0 | 11,860 | 0.002698 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.1.4'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'
'''
Python client SDK for sina weibo API using OAuth 2.
'''
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import gzip, time, json, hmac, base64, has... | _read_body(e)) |
except:
r = None
if hasattr(r, 'error_code'):
raise APIError(r.error_code, r.get('error', ''), r.get('request', ''))
raise e
class HttpObject(object):
def __init__(self, client, method):
self.client = client
self.method = method
def __getattr__... |
GroundPound/ManFuzzer | manparser/__init__.py | Python | apache-2.0 | 1,492 | 0.021448 | '''
Created on Dec 23, 2012
@author: Peter
This module contains a few functions for extracting the parameters out of a man page.
'''
import subprocess
import logging
from arguments.valuedarguments import ValuedArguments
TIMEOUT = 3
logger = logging.getLogger('man-fuzzer')
def mineflags(executable):
'''Return... | ble) + " --help",timeout)
def _mine | _Man_flags(executable,timeout):
return _extract_arguments("man " + str(executable),timeout) |
willybh11/python | advProg/turtleStuff/helloturtleworld.py | Python | gpl-3.0 | 846 | 0.055556 | import turtle
import time
window = turtle.Screen()
def test():
allturtles = []
for i in range(4):
t1 = turtle.Turtle()
t2 = turtl | e.Turtle()
t3 = turtle.Turtle()
t4 = turtle.Turtle()
t1.speed(0)
t2.speed(0)
t3.speed(0)
t4.speed(0)
t1.penup()
t2.penup()
t3.penup()
t4.penup()
t1.setx(50*i)
t1.sety(50*i)
t2.setx(50*i)
t2.sety(-50*i)
t3.setx(-50*i)
t3.sety(50*i)
t4.setx(-50*i)
t4.sety(-50*i)
t1... | ()
t4.ht()
allturtles.append([t1,t2,t3,t4])
start = time.clock()
for degrees in range(360):
for line in allturtles:
for t in line:
for repeat in range(2):
t.fd(200)
t.lt(90)
t.lt(1)
print "That took %f seconds." %(time.clock()-start)
test()
window.exitonclick()
|
Abraca/debian | waflib/Tools/suncc.py | Python | gpl-2.0 | 1,378 | 0.064586 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os
from waflib import Utils
from waflib.Tools import ccroot,ar
from waflib.Configure import conf
@conf
def find_scc(conf):
v=conf.env
cc=None
if v['CC']:cc=v['CC']
... | and_log(cc+['-flags'])
except Exception:
conf.fatal('%r is not a Sun com | piler'%cc)
v['CC']=cc
v['CC_NAME']='sun'
@conf
def scc_common_flags(conf):
v=conf.env
v['CC_SRC_F']=[]
v['CC_TGT_F']=['-c','-o']
if not v['LINK_CC']:v['LINK_CC']=v['CC']
v['CCLNK_SRC_F']=''
v['CCLNK_TGT_F']=['-o']
v['CPPPATH_ST']='-I%s'
v['DEFINES_ST']='-D%s'
v['LIB_ST']='-l%s'
v['LIBPATH_ST']='-L%s'
v['ST... |
nextgis/nextgisweb | nextgisweb/layer/util.py | Python | gpl-3.0 | 85 | 0 | from . | .i18n import trstring_factory
COMP_ID = 'layer'
_ = trstring_factory(COMP_ID)
| |
kulawczukmarcin/mypox | mininet_scripts/simple_net.py | Python | apache-2.0 | 1,695 | 0.00059 | __author__ = 'Ehsan'
from mininet.node import CPULimitedHost
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel, info
from mininet.node import RemoteController
from mininet.cli import CLI
"""
Instructions to run the topo:
1. Go to directory where this fil is.
2. ru... | c = RemoteController('c', '192.168. | 56.1', 6633)
net = Mininet(topo=SimplePktSwitch(), host=CPULimitedHost, controller=None)
net.addController(c)
net.start()
CLI(net)
net.stop()
# if the script is run directly (sudo custom/optical.py):
if __name__ == '__main__':
setLogLevel('info')
run()
|
jdber1/opendrop | opendrop/app/common/image_processing/plugins/define_line/component.py | Python | gpl-3.0 | 7,694 | 0.00065 | # Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com)
# OpenDrop is released under the GNU GPL License. You are free to
# modify and distribute the code, but always under the same license
#
# If you use this software in your research, please cite the following
# journal articles:
#
# J. D. Berry, M. J. ... | al Public License along
# with this software. If not, see <https://www.gnu.org/licenses/>.
from typing import Any, Tuple
from gi.rep | ository import Gtk, Gdk
from opendrop.app import keyboard
from opendrop.app.common.image_processing.image_processor import ImageProcessorPluginViewContext
from opendrop.mvp import ComponentSymbol, View, Presenter
from opendrop.utility.bindable.gextension import GObjectPropertyBindable
from opendrop.geometry import Vec... |
thatguyandy27/python-sandbox | learning-python/Ch3/dates_finished.py | Python | mit | 1,126 | 0.039964 | #
# Example file for working with date information
# (For Python 3.x, be sure to use the ExampleSnippets3.txt file)
from datetime import date
from datetime import time
from datetime import datetime
def main():
## DATE OBJECTS
# Get today's date from the simple today() method from the date class
today = date.tod... | (0=Monday, 6=Sunday)
print "Today's Weekday #: ", today.weekday()
## DATETIME OBJECTS
# Get today's date from the datetime class
today = datetime.now()
print "The | current date and time is ", today
# Get the current time
t = datetime.time(datetime.now())
print "The current time is ", t
# weekday returns 0 (monday) through 6 (sunday)
wd = date.weekday(today)
# Days start at 0 for Monday
days = ["monday","tuesday","wednesday","thursday","friday","saturday","... |
museumsvictoria/nodel-recipes | (retired)/pjlinkqueue/script.py | Python | mit | 1,588 | 0.027708 | # Copyright (c) 2014 Museum Victoria
# This software is released under the MIT license (see license.txt for details)
from Queue import *
import threading
import atexit
remote_action_PowerOn = RemoteAction()
remote_action_PowerOff = RemoteAction()
remote_action_SetInput = RemoteAction()
def local_action_activate(x = ... | rg)
self.event.wait(job['delay'])
queue.task_done()
except Exception, e:
print e
print "Failed to call command " + job['function']
else:
self.event.wait(1)
def stop(self):
self.event.set()
queue = Queue()
th = | TimerClass()
@atexit.register
def cleanup():
print 'shutdown'
th.stop()
def main():
th.start()
print 'Nodel script started.' |
project-fondue/python-yql | yql/logger.py | Python | bsd-3-clause | 1,435 | 0 | """Logging for Python YQL."""
import os
import logging
import logging.handlers
LOG_DIRECTORY_DEFAULT = os.path.join(os.path.dirname(__file__), "../logs")
LOG_DIRECTORY = os.environ.get("YQL_LOG_DIR", LOG_DIRECTORY_DEFAULT)
LOG_LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warni... | get_logger():
"""Set-upt the logger if enabled or fallback to NullHandler."""
if os.environ.get("YQL_LOGGING", False):
if not os.path.exists(LOG_DIRECTORY):
os.mkdir(LOG_DIRECTORY)
log_handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxB... | backupCount=5)
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log_handler.setFormatter(formatter)
else:
log_handler = NullHandler()
yql_logger.addHandler(log_handler)
return yql_logger
|
beepee14/scikit-learn | sklearn/metrics/regression.py | Python | bsd-3-clause | 16,953 | 0.000059 | """Metrics to assess performance on regression task
Functions named as ``*_score`` return a scalar value to maximize: the higher
the better
Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize:
the lower the better
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Ma... |
return y_type, y_true, y_pred, multioutput
def mean_absolute_error(y_true, y_pred,
sample_weight=None,
multioutput='uniform_average'):
"""Mean absolute error regression loss
Read more in the :ref:`User Guide <mean_absolute_error>`.
Parameters
---... |
y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs)
Estimated target values.
sample_weight : array-like of shape = (n_samples), optional
Sample weights.
multioutput : string in ['raw_values', 'uniform_average']
or array-like of shape (n_outputs)
Defines ag... |
dddomodossola/remi | remi/__init__.py | Python | apache-2.0 | 698 | 0 | from .gui import (
Widget,
Button,
TextInput,
SpinBox,
Label,
GenericDialog,
InputDialog,
ListView,
ListItem,
DropDown,
DropDownItem,
Image,
Table,
TableRow,
TableItem,
TableTitle,
Input,
Slider,
ColorPicker,
Date,
GenericObject,
Fi... | Dialog,
Menu,
MenuItem,
FileUploader,
FileDownloader,
VideoPlayer,
)
from .server import App, Server, start
from pkg_resources import get_distribution, DistributionNotFound
try:
__versi | on__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
|
persandstrom/home-assistant | tests/components/alarm_control_panel/test_manual_mqtt.py | Python | apache-2.0 | 56,123 | 0 | """The tests for the manual_mqtt Alarm Control Panel component."""
from datetime import timedelta
import unittest
from unittest.mock import patch
from homeassistant.setup import setup_component
from homeassistant.const import (
STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY,
STATE_ALARM_A... | topic': 'alarm/state',
}}))
entity_id = 'alarm_control_panel.test'
self.hass.start()
self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_home(self.hass, 'a... | ay_with_pending(self):
"""Test arm home method."""
self.assertTrue(setup_component(
self.hass, alarm_control_panel.DOMAIN,
{'alarm_control_panel': {
'platform': 'manual_mqtt',
'name': 'test',
'code': CODE,
'pending_t... |
vshlapakov/kafka-python | kafka/consumer/multiprocess.py | Python | apache-2.0 | 10,236 | 0.001661 | from __future__ import absolute_import
import logging
import time
from collections import namedtuple
from multiprocessing import Process, Manager as MPManager
try:
from Queue import Empty, Full
except ImportError: # python 2
from queue import Empty, Full
from .base import (
AUTO_COMMIT_MSG_COUNT, AUTO_... | notifications given by the controller process
NOTE: Ideally, this should have been a method inside the Consumer
class. However, multiprocessing module has issues in windows. The
functionality breaks unless this function is kept outside of a class
"" | "
# Make the child processes open separate socket connections
client.reinit()
# We will start consumers without auto-commit. Auto-commit will be
# done by the master controller process.
consumer = SimpleConsumer(client, group, topic,
auto_commit=False,
... |
zqhuang/COOP | mapio/pyscripts/check_QU.py | Python | gpl-3.0 | 1,311 | 0.012204 | import time
import os
import sys
cclist = ['commander', 'nilc', 'sevem', 'smica']
nulist = ['0', '1']
hlist = ['hot0', 'hot1', 'hot2']
clist = ['cold0', 'cold1', 'cold2']
nslist = ['F', 'N', 'S']
readonly = 'T'
nmaps = 1000
print "=============== F =============="
for nu in nulist:
print " -------------------------... | + ' ' + nu + ' ' + str(nmaps) + ' self hot0 T ' + ns + ' T '+ readonly)
os.system(r'./SST ' + cc + ' 1024 QU ' + ' ' + nu + ' ' + str(nmaps) + ' self cold0 T ' + ns + ' T '+ readonly) | |
jeremiah-c-leary/vhdl-style-guide | vsg/rules/subtype/rule_002.py | Python | gpl-3.0 | 1,387 | 0.000721 |
from vsg import parser
from vsg import token
from vsg.rules import consistent_token_case
lTokens = []
lTokens.append(toke | n.subtype_declaration.identifier)
lIgnore = []
lIgnore.append(token.interface_signal_declaration.identifier)
lIgnore.append(token.interface_unknown_declaration.identifier)
lIgnore.append(token.interface_constant_declaration.identifier)
lIgnore.append(token.interface_variable_declaration.identifier)
lIgnore.append(toke... | sistent_token_case):
'''
This rule checks for consistent capitalization of subtype names.
**Violation**
.. code-block:: vhdl
subtype read_size is range 0 to 9;
subtype write_size is range 0 to 9;
signal read : READ_SIZE;
signal write : write_size;
constant read_s... |
gnowxilef/plexpy | plexpy/webserve.py | Python | gpl-3.0 | 52,488 | 0.002705 | # This file is part of PlexPy.
#
# PlexPy 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.
#
# PlexPy 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
# GN... | www.gnu.org/licenses/>.
from plexpy import logger, notifiers, plextv, pmsconnect, common, log_reader, datafactory, graphs, users
from plexpy.helpers import checked, radio
from mako.lookup import TemplateLookup
from mako import exceptions
import plexpy
import threading
import cherrypy
import hashlib
import random
imp... |
MyRobotLab/pyrobotlab | home/hairygael/InMoov2.full3.byGael.Langevin.1.py | Python | apache-2.0 | 138,420 | 0.055592 | #file : InMoov2.full3.byGael.Langevin.1.py
# this script is provided as a basic guide
# most parts can be run by uncommenting them
# InMoov now can be started in modular pieces
import random
import threading
import itertools
leftPort = "COM20"
rightPort = "COM7"
i01 = Runtime.createAndStart("i01", "InMoov")
#inmoov... | #################################
helvar = 1
weathervar = 1
# play rock | paper scissors
inmoov = 0
human = 0
###############################################################
# after a start you may call detach to detach all
# currently attached servos
#i01.detach()
#i01.attach()
# auto detaches any attached servos after 120 seconds of inactivity
#i01.autoPowerDownOnInactivity(100)
#i01.... |
phapdv/project_euler | pe56.py | Python | mit | 616 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from base import Problem
class Solution(Problem):
def solve(self, input_):
numberLargest = 0
for a in range(1, 100):
if a % 10 != 0:
for b in range(1, 100):
num_pow = a**b
number_su... | = number_sum
print('Solve problem {}'.format(self.number))
print(numberLargest)
if __name__ == '__main__':
solution = Solution(56)
solution.solve | (100)
|
kotoromo/Numeric_Methods | Bisection/util.py | Python | gpl-3.0 | 1,437 | 0.005567 | from decimal import *
class util:
def getInterval(self, function):
"""
function: lambda function
Method that obtains the integer intervals where the function
changes its sign from negative to positive.
If it finds the function's root within its intervals, i... | e signs with b.
returns: boolean
"""
| #if a is a negative number and so is b
return ( (a < 0) is not (b < 0))
|
indrz/indrz | indrz/poi_manager/forms.py | Python | gpl-3.0 | 769 | 0.003901 | from django import forms
from poi_manager.models import Poi, PoiCategory
from mptt.forms import TreeNodeChoiceField
class PoiCategoryForm(forms.ModelForm):
cat_name = forms.CharField(max_length=128, help_text="Please enter the category name.")
parent = TreeNodeChoiceField(queryset=PoiCategory.objects.all(), r... | ="Please enter the title of the page.")
floor_num = forms.IntegerField(initial=0, required=False)
category = TreeNodeChoiceField(queryset=PoiCategory.objects.all())
class Meta:
model = Poi
fields = ('name', 'floor_num', 'category' | ,)
|
ngageoint/scale | scale/storage/migrations/0008_auto_20170609_1443.py | Python | apache-2.0 | 1,859 | 0.001614 | # -*- coding: utf-8 -*-
# Generated by Dja | ngo 1.11.1 on 2017-06-09 14:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('batch', '0002_auto_20170412 | _1225'),
('recipe', '0018_recipefile_recipe_input'),
('storage', '0007_auto_20170412_1225'),
]
operations = [
migrations.AddField(
model_name='scalefile',
name='batch',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion... |
andreaso/ansible | lib/ansible/modules/network/nxos/nxos_static_route.py | Python | gpl-3.0 | 10,343 | 0.002804 | #!/usr/bin/python
#
# 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 version.
#
# Ansible is distribut... | e
choices: ['present','absent']
'''
EXAMPLES = '''
- nxos_static_route:
prefix: "192.168.20.64/24"
next_hop: "3.3.3.3"
route_name: testing
pref: 100
username: "{{ un }}"
password: "{{ pwd }}"
host: "{{ inventory_hostname }}"
'''
RETURN = '''
proposed:
description: k/v pairs of ... | {"next_hop": "3.3.3.3", "pref": "100",
"prefix": "192.168.20.64/24", "route_name": "testing",
"vrf": "default"}
existing:
description: k/v pairs of existing configuration
returned: verbose mode
type: dict
sample: {}
end_state:
description: k/v pairs of configuration after mo... |
alexandrovteam/pyImagingMSpec | pyImagingMSpec/test/imutils_test.py | Python | apache-2.0 | 3,746 | 0.001068 | import unittest
import numpy as np
from ..imutils import nan_to_zero, quantile_threshold, interpolate
class ImutilsTest(unittest.TestCase):
def test_nan_to_zero_with_ge_zero(self):
ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
fo... | (np.arange(0), np.arange(0, dtype=np.bool_), 101)
)
| kws = ('im', 'notnull_mask', 'q_val',)
for args in test_cases:
kwargs = {kw: val for kw, val in zip(kws, args)}
self.assertRaises(ValueError, quantile_threshold, **kwargs)
def test_quantile_threshold_trivial(self):
test_cases = (
((np.arange(10), np.ones(1... |
ProjectSky/FrackinUniverse-sChinese-Project | script/tools/patch_tool.py | Python | mit | 6,836 | 0.009206 | import json
import os
import re
from codecs import open as open_n_decode
from json_tools import field_by_path, list_field_paths, prepare
# 网上抄的函数,用来合成json,结果还算可靠尼玛呢坑死我了
def add_value(dict_obj, path, value):
obj = dict_obj
for i, v in enumerate(path):
if i + 1 == len(path):
if not isinstan... | = 0
json_text = json.loads(jsons)
op_list = list()
i_list = list()
result = list()
for i, value in enumerate(json_text):
op_result = value['op']
op_list.append(op_result)
i_list.append(i)
op_dict = list(zip(i_list, op_list))
for value in op_dict:
if list(op_di... | e' or list(op_dict[index])[1] == 'test':
pass
else:
result.append(list(op_dict[index])[0])
index = index+1
return result
# 为某些patch文件写的解析法?大概吧,效率很低
def detect_patch(jsons):
string = prepare(jsons)
result = json.loads(string)
new_list=list()
for i in result:
... |
mvdbeek/tools-iuc | data_managers/data_manager_fetch_ncbi_taxonomy/data_manager/data_manager.py | Python | mit | 4,462 | 0.002465 | import argparse
import datetime
import json
import os
import shutil
import tarfile
import zipfile
from urllib.request import Request, urlopen
def url_download(url, workdir):
file_path = os.path.join(workdir, 'download.dat')
if not os.path.exists(workdir):
os.makedirs(workdir)
src = None
dst = ... | r json.')
parser | .add_argument('--out', dest='output', action='store', help='JSON filename')
parser.add_argument('--name', dest='name', action='store', default=str(datetime.date.today()), help='Data table entry unique ID')
parser.add_argument('--url', dest='url', action='store', default='ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.