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 |
|---|---|---|---|---|---|---|---|---|
Ragowit/hearthbreaker | hearthbreaker/tags/action.py | Python | mit | 20,965 | 0.000668 | import copy
from hearthbreaker.tags.base import Status, Action, Aura, Condition, AuraUntil, CardQuery, \
CARD_SOURCE, Effect, Buff, BuffUntil, Amount, Picker, Selector
from hearthbreaker.tags.condition import IsSecret
from hearthbreaker.tags.selector import AllPicker, ConstantSelector
class Give(Action):
def ... | 'name': 'summon',
'card': self.card,
'count': self.count
}
return {
'name': 'summon',
'card': self.card
}
def __from_json__(self, card, count=1):
self.card = CardQuery.from_json(**card)
self.count = count
... | # Used only for Jaraxxus currently
def __init__(self, card):
if isinstance(card, CardQuery):
self.card = card
else:
self.card = CardQuery(card.ref_name)
def act(self, actor, target, other=None):
card = self.card.get_card(target, target.player, actor)
... |
peiwei/zulip | analytics/views.py | Python | apache-2.0 | 26,077 | 0.001611 | from __future__ import absolute_import
from __future__ import division
from typing import Any, Dict, List, Tuple
from django.db import connection
from django.template import RequestContext, loader
from django.core import urlresolvers
from django.http import HttpResponseNotFound
from jinja2 import Markup as mark_safe
... | t)
AND
ua.query in (
'/jso | n/send_message',
'send_message_backend',
'/api/v1/send_message',
'/json/update_pointer',
'/json/users/me/pointer'
)
GROUP by realm.id, up.email
... |
cemsbr/yala | tests_data/fake_code.py | Python | mit | 845 | 0.001183 | import os
import abc
untyped_list = []
def high_complexity (arg):
"""High cyclomatic complexity."""
if arg == 0:
print(0)
elif arg == 1:
print(1)
elif arg == 2:
print(2)
elif arg == 3:
print(3)
elif arg == 4:
print(4)
elif arg == 5:
print(5)... | int(6)
elif arg == 7:
print(7)
elif arg == 8:
print(8)
elif arg == 9:
print(9)
elif arg == 10:
print(10)
elif arg == 11:
print(11)
elif arg == 12:
print(12)
elif arg == 13:
print(13)
elif arg == 14:
print(14)
elif arg ==... | if arg == 19:
print(19)
|
goffersoft/common-utils-python | experimental/com/goffersoft/utils/address.py | Python | gpl-2.0 | 5,816 | 0 | #! /usr/bin/python
"""This Module Contains Address Base Class
This is a base class whose
methods will be overridden by
derived classes customized to
different address formats
This module contains the following funcstions and classes
1) _get_field_separator - internal function to return the defaul... | return self.__addr
@addr.setter
def addr(self, addr):
""" addr setter method """
if(addr != self.__addr):
self.__addr = addr
self.__addrparts = None
@property
def addrparts(self):
""" addrparts getter method """
self.__update_addrparts()
... | parts):
""" addrparts setter method """
if(addrparts != self.__addrparts):
self.__addrparts = addrparts
self.__addr = None
def tostr(self):
""" return addr as a string """
return self.addr
def tobytes(self):
""" return addr as bytes """
i... |
tiagocoutinho/bliss | bliss/comm/embl/MDEvents.py | Python | lgpl-3.0 | 9,538 | 0.018977 | # -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
# Copyright (c) 2016 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.
import sys
import time
import string
import threading
from ExporterClient import *
SERVER_ADDRESS = "localhost"
SERVER_PORT=9001
... | _CRYO_BACK, #boolean
PROPERTY_INTERLOCK_ENABLED, #boolean
PROPERTY_ | FRONT_LIGHT_LEVEL, #double
PROPERTY_BACK_LIGHT_LEVEL #double
]
##############################################################################################################
#Auxiliary
############################################################################################... |
anryko/ansible | test/units/executor/module_common/test_recursive_finder.py | Python | gpl-3.0 | 11,999 | 0.005417 | # (c) 2017, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... | FinderContainers = namedtuple('FinderContainers', ['py_module_names', 'py_module_cache', 'zf'])
py_module_names = set((('ansible', '__init__'), ('ansible', 'module_utils', '__init__')))
# py_module_cache = {('__init__',): b''}
py_module_cache = {}
zipoutput = BytesIO()
zf = zipfile.ZipFile(zipou... | mode='w', compression=zipfile.ZIP_STORED)
# zf.writestr('ansible/__init__.py', b'')
return FinderContainers(py_module_names, py_module_cache, zf)
class TestRecursiveFinder(object):
def test_no_module_utils(self, finder_containers):
name = 'ping'
data = b'#!/usr/bin/python\nreturn \'{\"cha... |
ojarva/home-info-display | homedisplay/control_milight/urls.py | Python | bsd-3-clause | 663 | 0.001508 | from django.conf.urls import url
from . import views
urlpatterns = [ # pylint:disable=invalid-name
url(r'^status$', views.Control.as_view()),
url(r'^status/(?P<group>([0-9]))$', views.Control.as_view()),
url(r'^control/(?P<command>([a-z_-]+))/(?P<group>([0-9]))$',
views.Control.as_view()),
url... | (r'^timed/(?P<command>([a-z-_]+))/( | ?P<action>([a-z-_]+))$',
views.TimedProgram.as_view()),
]
|
rjeschmi/vsc-base | test/exceptions.py | Python | lgpl-2.1 | 8,315 | 0.00433 | # -*- coding: utf-8 -*-
#
# Copyright 2015-2017 Ghent University
#
# This file is part of vsc-base,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# the Flem... | cluded if LOC_INFO_TOP_PKG_NAMES is defined
TestException.LOC_INFO_TOP_PKG_NAMES = ['vsc']
logToFile(tmplog, enable=True)
self.assertErrorRegex(LoggedException, 'BOOM', raise_testexception, 'BOOM')
logToFile(tmpl | og, enable=False)
log_re = re.compile(r"^%s :: BOOM \(at (?:.*?/)?vsc/install/testing.py:[0-9]+ in assertErrorRegex\)$" % rootlogname)
logtxt = open(tmplog, 'r').read()
self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt))
f = open(tmplog, 'w')
f.wri... |
HazardSJ/HazardBot | enwiki/afd_relisted_null_editor.py | Python | mit | 1,048 | 0.001908 | import pywikibot
pywikibot.config.family = "wikipedia"
pywikibot.config.mylang = "en"
site = pywikibot.Site()
site.login()
class AFDRelistedNullEditor(object):
"""Makes a null edit to AfDs transcluded in the logs on [[Category:Re | listed AfD debates]]"""
def __init__(self):
self.afd_prefix = "Wikipedia:Articles for deletion/"
self.category = pywi | kibot.Category(site, "Category:Relisted AfD debates")
def process_log(self, log):
for page in log.itertemplates():
if page.title().startswith(self.afd_prefix):
try:
if self.category.title() in page.get():
page.touch()
e... |
canhhs91/greenpointtrees | src/oscar/apps/search/features.py | Python | mit | 395 | 0.002532 | from django.conf import settings
def is_solr_supported():
try:
re | turn 'Solr' in settings.HAYSTACK_CONNECTIONS['default']['ENGINE']
except (KeyError, AttributeError):
return False
def is_elasticsearch_s | upported():
try:
return 'Elasticsearch' in settings.HAYSTACK_CONNECTIONS['default']['ENGINE']
except (KeyError, AttributeError):
return False
|
OpenCobolIDE/OpenCobolIDE | open_cobol_ide/view/forms/dlg_preferences_ui.py | Python | gpl-3.0 | 72,494 | 0.003504 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/colin/Projects/OpenCobolIDE/forms/dlg_preferences.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from pyqode.qt import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
de... | self.groupBox_3)
self.label_13.setObjectName("label_13")
self.formLayout.setWidget(3, QtWidgets.QFo | rmLayout.LabelRole, self.label_13)
self.checkBoxShowErrors = QtWidgets.QCheckBox(self.groupBox_3)
self.checkBoxShowErrors.setText("")
self.checkBoxShowErrors.setObjectName("checkBoxShowErrors")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.checkBoxShowErrors)
... |
johnbachman/indra | indra/sources/dgi/__init__.py | Python | bsd-2-clause | 536 | 0 | # -*- coding: utf-8 -*-
"""A processor for the `Drug Gene Interaction DB <http://www.dgidb.org>`_.
* `Integration of the Drug–Gene Interaction Database (DGIdb 4.0) with open
crowdsource efforts <https://doi.org/10.1093/nar/gkaa1084>`_. Freshour,
*et al*. Nucleic Acids Research. 2020 Nov 25.
Interactions data fro... | can be obtained at the
following URL | s:
* https://www.dgidb.org/data/monthly_tsvs/2021-Jan/interactions.tsv
"""
from .api import get_version_df, process_df, process_version # noqa:F401
|
barsi/odoo-rtl | web_rtl/__manifest__.py | Python | agpl-3.0 | 1,405 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo RTL support
# Copyright (C) 2016 Moham | med Barsi.
#
# This program is free software: you can redistribute it and/or modify
# it under the ter | ms 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERC... |
likelyzhao/mxnet | example/speech-demo/io_func/feat_readers/common.py | Python | apache-2.0 | 1,508 | 0.033156 | import numpy
import os
class ByteOrder:
LittleEndian, BigEndian = range(2)
class FeatureException(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
def ReadLabel(filename):
labels = numpy.loadtxt(filename, ndmin=1)
return labels.astype(numpy.int32)
class BaseRea... | e, labelFile)
elif fileformat.lower() == 'kaldi':
import reader_kaldi
return reader_kaldi.kaldiReader(featureFile, labelFile)
else:
msg = "Error: Specified format | '{}' is not supported".format(fileformat)
raise Exception(msg) |
samupl/simpleERP | simpleERP/admin.py | Python | mit | 416 | 0 | from django.uti | ls.translation import ugettext_lazy as _
def configure_admin_site(admin_site):
# Text to put at the end of each page's <title>.
admin_site.site_title = _('SimpleERP Admin site')
# Text to put in each page's <h1>.
admin_site.site_header = _('SimpleERP Administration')
# Text to put at the top of ... | tration')
|
leophys/libreant | webant/test/test_api_archivant.py | Python | agpl-3.0 | 243 | 0 | from webant.test import WebantTestCase
from nose.tool | s import eq_
class TestApiArchivant(WebantTestCase):
API_PREFIX = '/api/v1'
def test_get_volumes(self):
eq_(self.wtc.get(self.API_PREFIX + '/ | volumes/').status_code, 200)
|
miracle2k/feedplatform | setup.py | Python | bsd-2-clause | 1,070 | 0.018692 | #!/usr/bin/env python
import os
from distutils.core import setup
def find_packages(root):
# so we don't depend on setuptools; from the Storm ORM setup.py
packages = []
for directory, subdirectories, files in os.walk(root):
if '__init__.py' in files:
packages.append(directory.replace(os... | stem :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Indexi | ng/Search',
],
packages = find_packages('feedplatform'),
)
|
gmr/hockeyapp | hockeyapp/version.py | Python | bsd-3-clause | 4,696 | 0.002981 | """
Implements objects for calling Version APIs
"""
__author__ = 'Don Thorp'
__email__ = 'don@donthorp.net'
__since__ = '2012-03-23'
import sys
from . import api
class AppVersions(api.APIRequest):
def __init__(self, api_key, app_id):
"""Create the AppVersions request object for developers.
:p... | return params
@property
def path(self):
"""Returns the request path
| :returns: str
"""
return api.BASE_URI + 'apps/%s/app_versions' % self._app_id
@property
def dsym(self):
return self._dsym
@dsym.setter
def dsym(self, f):
self._dsym = f
@property
def notes(self):
return self._notes
@notes.setter
def notes(se... |
mc706/django-angular-scaffold | angular_scaffold/management/commands/createlimiter.py | Python | mit | 520 | 0.003846 | from django.core.management.base import BaseCommand
from django.conf import settings
from angular_scaffold.management.commands.helpers._generate_limiter import generate_limiter
class Command(BaseCommand):
help = 'Adds the rootScope Rate limiter for your services'
def handle(self, *args, **options):
... | te('Generating rate limiter run file')
if hasattr(settings, 'BASE_DIR'):
path = setting | s.BASE_DIR
else:
path = '.'
generate_limiter(path) |
opethe1st/SameGame | src/tests/test_model/test_scorer.py | Python | gpl-3.0 | 1,074 | 0.003724 | from unittest import TestCase
from same.model.scorer import Scorer
class ScoreTestCase(TestCase):
def setUp(self):
self.scorer = Scorer()
class TestGetCurrentScore(ScoreTestCase):
def test_get_current_score(self):
score = 5
| self.scorer.current_score = score
self.assertEqual(self.scorer.get_current_score(), score)
class TestUpdateCurrentScore(ScoreTestCase):
def test_update_current_score(self):
score = 5
self.scorer.current_score = score
self.scorer.update_current_score(score=13)
self.... | = [(0, 0), (0, 1), (0, 2)]
returned_score = self.scorer.calculate_score(ball_positions=ball_positions)
self.assertEqual(returned_score, 9)
def test_calculate_score_zero(self):
ball_positions = []
returned_score = self.scorer.calculate_score(ball_positions=ball_positions)
sel... |
Akoten/Microsoft-Translator-Python-API | __init__.py | Python | bsd-3-clause | 8,249 | 0.000485 | # -*- coding: utf-8 -*-
"""
__init__
A translator using the micrsoft translation engine documented here:
http://msdn.microsoft.com/en-us/library/ff512419.aspx
:copyright: © 2011 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
__all__ = ['Transla... | to_lang,
'contentType': content_type,
'category': category,
}
if from_lang is not None:
params['from'] = from_lang
return self.call(
"http://api.microsofttranslator.com/V2/Ajax.svc/Translate",
params)
def translate_array(self, text... | ons):
"""Translates an array of text strings from one language to another.
:param texts: A list containing texts for translation.
:param to_lang: A string representing the language code to
translate the text into.
:param from_lang: A string representing the language code of ... |
RulersOfAsgard/ALAMO-worker | alamo_worker/alerter/tests/test_notification_http.py | Python | apache-2.0 | 4,938 | 0 | # -*- coding: utf-8 -*-
from copy import deepcopy
from datetime import datetime, timedelta
from types import ModuleType
from unittest import TestCase
from unittest.mock import patch
from alamo_worker.conf import settings
from alamo_worker.alerter.notifications.http import HttpNotificationClient
from alamo_worker.alert... | ficationClient()
run_async(
notification.send(self.check, self.check.triggers[0], 'resolve')
)
self.assertEqual(mock_sleep.call_count, notification._retries)
def test_omits_empty_http_response_body(self):
check_data = deepcopy(CHECK_TEST_DATA)
check_data['trigger... | CheckInstance(check_data)
notification = HttpNotificationClient()
event = notification.build_data(
check, check.triggers[0], 'trigger'
)
self.assertNotIn('http_response_body', event['payload'])
|
smalls12/django_helpcenter | helpcenter/testing_utils.py | Python | mit | 2,482 | 0 | from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from helpcenter import models
# Default Values
ARTICLE_BODY = 'Test article body.'
ARTICLE_TITLE = 'Test Article'
CATEGORY_TITLE = 'Test Category'
def create_article(title=ARTICLE_TITLE, body=ARTICLE_BODY,
... | username=self.username, password=self.password)
def tearDown(self, *args, **kwargs):
""" Logout the current client """
self.client.logout()
super(AuthTestMixin, self).tearDown(* | args, **kwargs)
|
vmgmedia/pacemaker | cts/CTSaudits.py | Python | gpl-2.0 | 29,678 | 0.006806 | '''CTS: Cluster Testing System: Audit module
'''
__copyright__ = '''
Copyright (C) 2000, 2001,2005 Alan Robertson <alanr@unix.sh>
Licensed under the GNU GPL.
'''
#
# 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 ... | t = 1
self.CM.ns.WaitForAllNodesToComeUp(self.CM.Env["nodes"])
for node in self.CM.Env["nodes"]:
(rc, lsout) = self.CM.rsh(node, "ls -al /var/lib/heartbeat/cores/* | grep core.[0-9]", None)
for line in lsout:
line = line.strip()
if line not in se... | ing: Pacemaker core file on %s: %s" % (node, line))
(rc, lsout) = self.CM.rsh(node, "ls -al /var/lib/corosync | grep core.[0-9]", None)
for line in lsout:
line = line.strip()
if line not in self.known:
result = 0
|
williamgibb/rhizopathy | tests/test_rhizopathy.py | Python | mit | 65 | 0 |
from | rhizopathy.cli import main
d | ef test_main():
main([])
|
shadow/shadow-ctl | src/config.py | Python | gpl-3.0 | 1,598 | 0.010638 | '''
Default configs.
'''
import os, curses
from ConfigParser import SafeConfigParser
from tools import *
from enum import *
# sections for each config file
Sections = Enum("general", "setup", "cli")
CONFIG_BASE = "~/.shadow"
CONFIG_PATH = os.path.expanduser(CONFIG_BASE + "/shadow-cli.conf")
CONFIG = None
DEFAULT_CONF... | tion(section)
| for option in d.options(section):
default = d.get(section, option)
if not c.has_option(section, option): c.set(section, option, default)
return c
def getDefaultConfig():
global DEFAULT_CONFIG
# return the default configurations
# TODO - caller could modify and overwrite t... |
piotrdz/colobot-lint | Tests/run_tests.py | Python | bsd-3-clause | 1,290 | 0.010078 | #!/usr/bin/env python3
import argparse
import subprocess
import os
import sys
import list_tests
import fnmatch
parser = argparse.ArgumentParser(add_help = False)
parser.add_argument('--colobot-lint-exec', dest='colobot_lint_executable', required=True)
parser.add_argument('--debug', dest='debug_flag', action='store_tru... | ining_args = parser.parse_known_args()
python_interp = sys.executable
this_dir = os.path.dirname(os.path.realpath(__file__))
if options.filter:
filtered_tests = []
for test in list_tests.list_tests():
if fnmatch.fnmatch(test, options.filter):
filtered_tests.append(test)
if len(filtere... | 0:
remaining_args = ['discover', '-s', this_dir, '-t', this_dir, '-p', '*_test.py']
code = subprocess.call([python_interp, '-m', 'unittest'] + remaining_args,
cwd = this_dir,
env = { 'COLOBOT_LINT': os.path.realpath(options.colobot_lint_executable),
... |
nicolashainaux/mathmaker | mathmaker/lib/document/content/calculation/order_of_operations.py | Python | gpl-3.0 | 68,910 | 0.000482 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | mplied 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 Mathmaker; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 0... |
import random
from decimal import Decimal
from mathmakerlib.calculus import is_integer, move_fracdigits_to
from mathmakerlib.calculus import remove_fracdigits_from, fix_fracdigits
from mathmakerlib.calculus import Number
from mathmaker.lib import shared
from mathmaker.lib.constants.latex import COLORED_QUESTION_MAR... |
pombredanne/milk | milk/supervised/svm.py | Python | mit | 15,907 | 0.007984 | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2015, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from .classifier import normaliselabels, ctransforms_model
from .base import superv... | sed.svm_raw.train: kernel not set!'
assert self.algorithm in ('libsvm','smo'), 'milk.supervised.svm_raw: unknown algorithm (%s)' % self.algorithm
assert not (np.isinf(self.C) or np.isnan(self.C)), 'milk.supervised.svm_ra | w: setting C to NaN or Inf causes problems.'
features = np.asanyarray(features)
if normalisedlabels:
Y = labels.copy()
else:
Y,_ = normaliselabels(labels)
assert Y.max() == 1, 'milk.supervised.svm_raw can only handle binary problems'
Y *= 2
Y -= 1
... |
nikolaystanishev/hut | huts/settings.py | Python | mit | 4,118 | 0.001214 | """
Django settings for huts project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
im... | Middleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = 'huts.urls'
TEMPLATES = [
... | lates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.... |
joker946/nova | nova/objects/virtual_interface.py | Python | apache-2.0 | 3,823 | 0.000523 | # Copyright (C) 2014, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | @base.remotable_classmethod
def get_by_id(cls, context, vif_id):
db_vif = db.virtual_interface_get(context, vif_id)
if db_vif:
return cls._from_db_object(context, | cls(), db_vif)
@base.remotable_classmethod
def get_by_uuid(cls, context, vif_uuid):
db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_address(cls, context, addre... |
jrg365/gpytorch | gpytorch/priors/lkj_prior.py | Python | mit | 7,346 | 0.001906 | #!/usr/bin/env python3
import math
from numbers import Number
import torch
from torch.distributions import constraints
from torch.nn import Module as TModule
from ..utils.cholesky import psd_safe_cholesky
from .prior import Prior
class LKJPrior(Prior):
r"""LKJ prior over n x n (positive definite) correlation m... | nd a user-specified prior over marginal standard deviations to return a
prior over the full covariance matrix.
Usage: LKJCovariancePrior(n, eta, sd_prior), where
n is a positive integer, the size of the covariance matrix,
eta is a positive shape parameter for the | LKJPrior over correlations, and
sd_prior is a scalar Prior over nonnegative numbers, which is used for
each of the n marginal standard deviations on the covariance matrix.
"""
def __init__(self, n, eta, sd_prior, validate_args=False):
if not isinstance(sd_prior, Prior):
rai... |
davelab6/fontqa | FontLab/Macros/System/Modules/fontQA_Vmetric.py | Python | gpl-3.0 | 7,526 | 0.013022 | #------------------------------------------------------------------------------
#
# This file is part of the fontQA framework
# Copyright (C) 2005 published by FSI Fonts und Software GmbH
# written by Andreas (Eigi) Eigendorf
#
# This programming framework is free soft | ware; you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This programming framework is distributed in the hope that it will be
# useful, but WITHOUT ... | ANTY; 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 this programming framework; if not, write to the
# Free Software Foundation, Inc.... |
erasmospunk/electrumx | lib/server_base.py | Python | mit | 4,398 | 0 | # Copyright (c) 2017, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
import asyncio
import logging
import os
import signal
import sys
import time
from functools import partial
class ServerBase(object):
'''Base class serve... | SUPPRESS_MESSAGES = [
'Fatal read error on socket transport',
'Fatal write error on socket transport',
]
PYTHON_MIN_VERSION = (3, 6)
def __init__(self, env):
'''Save the environment, perform basic sanity checks, and | set the
event loop policy.
'''
self.logger = logging.getLogger(self.__class__.__name__)
self.env = env
# Sanity checks
if sys.version_info < self.PYTHON_MIN_VERSION:
mvs = '.'.join(str(part) for part in self.PYTHON_MIN_VERSION)
raise RuntimeError(... |
IntelPython/BlackScholes_bench | bs_erf_numba_guvec_par.py | Python | mit | 1,146 | 0.016579 | # Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import base_bs_erf
import numba as nb
from math import log, sqrt, exp, erf
def black_scholes_numba_opt(price, strike, t, mr, sig_sig_two, vol, call, put):
P = float( price [0] )
S = strike [0]
T = t [0]
a = ... | nopython=True, target="parallel", fastmath=False)(black_scholes_numba_opt)
@nb.jit
def black_scholes(nopt, price, strike, t, rate, vol, call, put):
sig_sig_two = vol*vol*2
mr = -rate
black_scholes_numba_opt_ | vec(price, strike, t, mr, sig_sig_two, vol, call, put)
base_bs_erf.run("Numba@guvec-par", black_scholes, pass_args=True)
|
plotly/plotly.py | packages/python/plotly/plotly/validators/choropleth/_legendgroup.py | Python | mit | 412 | 0.002427 | import _plotly_utils.basevalidators
class LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="legendgroup", parent_name="choropleth", **kwargs):
| super(Legendgroup | Validator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs
)
|
consultit/Ely | ely/direct/data_structures_and_algorithms/ch02/range.py | Python | lgpl-3.0 | 2,023 | 0.001977 | # Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of... | start, stop = 0, start # should be treated as if range(0,n)
# calculate the effective length once
self._length = max(0, (stop - start + step - 1) // step)
# need knowledge of start and step (but not stop) to support __getitem__
self._start = start
self._ste... | self._length
def __getitem__(self, k):
"""Return entry at index k (using standard interpretation if negative)."""
if k < 0:
k += len(self) # attempt to convert negative index
if not 0 <= k < self._length:
raise IndexError('index out of range')
... |
KirillTim/crashsimilarity | tests/test_cache.py | Python | mpl-2.0 | 2,929 | 0.001366 | import os
import unittest
from crashsimilarity.cache import TracesCache, DownloaderCache
from tests.test_utils import StackTraceProcessorTest
class CacheTest(unittest.TestCase):
default_cache_file_name = 'default.pickle'
other_file_name = 'other.pickle'
# don't want to use pyfake or mock os.system calls... | er_file_name):
os.remove(self.other_file_name)
def tearDown(self):
self.setUp()
class TestTracesCache(CacheTest):
default_cache_file_nam | e = 'traces_cache.pickle'
def test_traces_cache_build_from_raw_traces(self):
"""we need to be sure that `build_from_raw_traces` is just a proxy call for StackTraceProcessor.process(...)"""
cache = TracesCache.build_from_raw_traces(StackTraceProcessorTest.raw_traces)
self.assertEqual(cache.t... |
popazerty/dvbapp2-gui | lib/python/Plugins/Extensions/IniHbbTV/bookmark.py | Python | gpl-2.0 | 8,456 | 0.033822 | class BookmarkData:
def __init__(self, _id, _title, _url, _parent, _type):
self.mId = _id
self.mTitle = _title
self.mUrl = _url
self.mParent = _parent
self.mType = _type
def dump(self, _intent=' '):
print "%s-> %d, %s, %s, %d, %d" % (_intent, self.mId, self.mTitle, self.mUrl, self.mParent, self.mType... | _parent, _type,))
self.mConfig.add_section(s)
self.setNumber(s, 'id', i)
self.setString(s, 'title', _title)
self.setString(s, 'url', _url)
self.setNumber(s, 'parent', _parent)
self.setNumber(s, 'type', _type)
self.setNumber('__SYS__', 'bookmark_current_idx', i)
self._save()
return True
def deleteB... | lf.message("delete bookmark : %d", (_id,))
self.delSection('b-%d' % (_id,))
self._save()
def updateBookmark(self, _bookmark):
self.populate()
s = "b-%d" % (_bookmark.mId)
self.message("update bookmark : %s, %s, %d, %d", (_bookmark.mTitle, _bookmark.mUrl, _bookmark.mParent, _bookmark.mType,))
self.setStrin... |
nataddrho/DigiCue-USB | Python3/src/venv/Lib/site-packages/pip/_internal/utils/virtualenv.py | Python | mit | 3,653 | 0 | import logging
import os
import re
import site
import sys
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import List, Optional
logger = logging.getLogger(__name__)
_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(
r"include-system-site-packages\s*=\s*(?P<value>tr... | ", sys.pr | efix)
def _running_under_regular_virtualenv():
# type: () -> bool
"""Checks if sys.real_prefix is set.
This handles virtual environments created with pypa's virtualenv.
"""
# pypa/virtualenv case
return hasattr(sys, 'real_prefix')
def running_under_virtualenv():
# type: () -> bool
"... |
BadSingleton/pyside2 | tests/QtWidgets/qtoolbox_test.py | Python | lgpl-2.1 | 839 | 0.001192 |
import unittest
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import QToolBox, QWidget
from helper import UsesQApplication
class OwnershipControl(UsesQApplication):
def setUp(self):
super(OwnershipControl, self).setUp()
self.toolbox = QToolBox()
def tearDown(self):
del sel... | # Was losing ownership of the widget.
index = self.toolbox.addItem(QWidget(), 'item')
item = self.toolbox.widget(index)
self.assert_(isinstance(item, QWidget))
| def testAddItemWithIcon(self):
index = self.toolbox.addItem(QWidget(), QIcon(), 'item')
item = self.toolbox.widget(index)
self.assert_(isinstance(item, QWidget))
if __name__ == '__main__':
unittest.main()
|
Tijl/ANASIME | simulator.py | Python | gpl-3.0 | 4,935 | 0.02999 | '''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT... | ile if we are starting over
if not processed:
print 'creating new %s file..'%filename
open(filename,'w').write(header)
return processed
def testalgorithms(prefix,base,target,names,algorithms,outfilename):
results = []
optimal = 0
arb = []
found = False
for an,a in zip(n... | results.append(prefix+[an]+[ar.get(x,'-') for x in ('time','memory','inputsize','score')])
for x in results:
if x[-1]=='-': x.append('-')
else: x.append(optimal-int(x[-1]))
open(outfilename,'a').write('\n'+'\n'.join([' '.join(map(str,x)) for x in results]))
def writeemptyresult(prefix,n... |
SurveyMonkey/wukong | wukong/query.py | Python | mit | 18,304 | 0.000055 | import wukong.errors as solr_errors
import copy
import re
import six
INFINITE_ROWS = 999999999
class SolrNode(object):
"""
The base class to model a tree node in the query logic to SOLR
"""
def __init__(self, *args, **kwargs):
self.items = self.build_items(args, kwargs)
@property
def... | += "-%s:\"%s\"" % (key, value)
else:
query_string += "-%s:%s" % (key, value)
# IN
elif operator == 'in':
| if not isinstance(value, list):
raise solr_errors.SolrError(
"Operator:in only takes list type"
)
new_value = []
for i in value:
if i is not None:
if isinstance(i, six.string_types):
... |
trolldbois/ctypeslib | setup.py | Python | mit | 1,432 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="ctypeslib2",
version="2.3.2",
description="ctypeslib2 - FFI toolkit, relies on clang",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
author="Loic Jaquemet",
a... | 'data/headers.tpl',
'data/pointer_type.tpl',
'data/string_cast.tpl',
| 'data/structure_type.tpl',
]},
entry_points={
'console_scripts': [
'clang2py = ctypeslib.clang2py:main',
]},
test_suite="test.alltests",
install_requires=[
'clang>=11',
]
)
|
bmccann/examples | dcgan/main.py | Python | bsd-3-clause | 9,656 | 0.004557 | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchv... | type=int, default=25, help='number of epochs to train for')
parser.add_argument('--lr', type=float, default=0.0002, help='learning rate, default=0.0002')
parser.add_argument('- | -beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')
parser.add_argument('--cuda' , action='store_true', help='enables cuda')
parser.add_argument('--ngpu' , type=int, default=1, help='number of GPUs to use')
parser.add_argument('--netG', default='', help="path to netG (to continue training)")
parser.... |
yarbroughw/JMDE | JMDE/scripts/graph.py | Python | mit | 4,491 | 0.001113 | from __future__ import print_function
import json
import matplotlib.pyplot as plt
import numpy as np
with open("../data/results/scores.json", 'r') as f:
scores = json.load(f)
with open("../data/results/dis | tances.json", 'r') as f:
distances = json.load(f)
with open("../data/results/times.json", 'r') as f:
times = json.load(f)
print(scores)
print(distances)
print(times)
def scorelines():
''' line plot of learned classifier's scores (x = ns, y = accuracy) '''
ns = [10, 100, 1000, 10000]
fig, ax = plt... | ,
label='Basic')
ax.plot(ns, scores["tree"], marker='s', linestyle='-', color='b',
label='Tree')
ax.plot(ns, scores["trained"], marker='^', linestyle='-', color='g',
label='Learned Thresholds')
ax.set_xlabel('Size of Training Set')
ax.set_ylabel('Average Accuracy over... |
quattor/aquilon | lib/aquilon/worker/commands/del_filesystem.py | Python | apache-2.0 | 1,059 | 0 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | on.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.commands.del_resource import CommandDelResource
class CommandDelFilesystem(CommandDelResource):
required_parameters = ["files | ystem"]
resource_class = Filesystem
resource_name = "filesystem"
|
yangming85/lettuce | tests/integration/test_bamboo.py | Python | gpl-3.0 | 2,162 | 0 | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org>
#
# 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 Foundatio... | tatus, out = run_scenario('leaves', 'count', 2)
assert_equals(status, 0, out)
status, out = run_scenario('leaves | ', 'count', 3)
assert_not_equals(status, 0)
assert "Length of outbox is 1" in out
@FileSystem.in_directory(current_directory, 'django', 'bamboo')
def test_mail_content():
'Mail content is checked through Lettuce steps'
status, out = run_scenario('leaves', 'content', 1)
assert_equals(status, 0, ou... |
pimutils/khal | khal/settings/utils.py | Python | mit | 8,737 | 0.000572 | # Copyright (c) 2013-2021 khal contributors
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publi... | le
:type option: str
:returns: firstday, firstfullweek
:rtype: str/bool
"""
option = option.lower()
if option == 'firstday':
return 'firstday'
elif option == 'firstfullweek':
return 'firstfullweek'
else:
raise VdtV | alueError(
f"Invalid value '{option}' for option 'monthdisplay', must be one "
"of 'firstday' or 'firstfullweek'"
)
def expand_path(path):
"""expands `~` as well as variable names"""
return expanduser(expandvars(path))
def expand_db_path(path):
"""expands `~` as well as v... |
acdha/django-google-analytics | google_analytics/tests/__init__.py | Python | mit | 32 | 0 | from tes | t_templatetags | import *
|
euklyd/PenguinBot3K | plugins/EiMM.py | Python | gpl-3.0 | 35,247 | 0.002475 | """
Plugin Name : EiMM
Plugin Version : 0.1
Description:
Utilities for the Mafia-spinoff free-for-all game,
Everyone is Mafia Mafia.
Contributors:
- Euklyd / Popguin
License:
Arcbot is free software: you can redistribute it and/or modify it
under the terms ... | 'Favor | ite EiMM Game?', 'Favorite EiMM Role?',
'Favorite type of EiMM?', 'About Me'
]
UPDATABLE_FIELDS = [
'Discord ID',
# 'UID',
# 'Primary Name',
'Also Known As',
'Pronouns',
'Home Community',
'Country',
'Timezone (in UTC)',
# 'Birth year',
'Birthday',
# 'Age',
# 'Age Rang... |
fodpeter/MathClock | equations/build.py | Python | apache-2.0 | 2,085 | 0.000959 | #!/usr/bin/python
import os
import requests
from collections import defaultdict
from glob import glob
def convert(dpi, equation):
url = 'http://latex.codecogs.com/png.latex?'
r = requests.get(url, params='\dpi{' + str(dpi) + '} ' + equation)
print('HTTP response: ' + str(r.status_code))
if (r.status_... | quations = readEquations('equations.txt')
outputDir = 'output'
mappingFile = outputDir + '/mapping.properties'
if not os.path.exists(outputDir):
os.mkdir(outputDir)
else:
for filename in glob(outputDir + "/*/*.png"):
os.remove(filename)
if os.path.exists(mappingFile):... |
for dpi in dpis:
dir = outputDir + '/' + str(dpi)
if not os.path.exists(dir):
os.mkdir(dir)
with open(mappingFile, 'w') as mapping:
for k, v in sorted(equations.items()):
ki = 0
for equation in sorted(v):
print('converting' + str(k) + ... |
idaholab/civet | ci/gitlab/api.py | Python | apache-2.0 | 19,475 | 0.001849 |
# Copyright 2016 Battelle Energy Alliance, LLC
#
# 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 agr... | is passed in is a personal access token
# or private token
self._headers["PRIVATE-TOKEN"] = self._token
self._session = requests
else:
self._session = requests
@copydoc(GitAPI.sign_in_url)
def sign_in_url(self):
return reverse('ci:git | lab:sign_in', args=[self._hostname])
def _gitlab_id(self, owner, repo):
name = '%s/%s' % (owner, repo)
return quote_plus(name)
def _repo_url(self, path_with_namespace):
return '%s/projects/%s' % (self._api_url, quote_plus(path_with_namespace))
def _project_url(self, project_id):
... |
SamuelDudley/APSyncWeb | APSyncFramework/modules/lib/APSync_module.py | Python | gpl-3.0 | 4,702 | 0.013186 | # A template for APSync process based modules
from multiprocessing import Process, Event
import threading
import time
import signal, select
import traceback
import setproctitle
from APSyncFramework.utils.common_utils import PeriodicEvent
from APSyncFramework.utils.json_utils import ping, json_wrap_with_target
from APSy... | while multiprocessing".format(self.name))
traceback.print_exc()
# TODO: logging here
print self.name, 'main finished'
def main(self):
pass
def in_queue_handling(self, lock=None):
while not self.needs_unloading.is_set():
(inputready,o... | for s in inputready:
while not self.in_queue.empty():
# drain the queue
data = self.in_queue.get_nowait()
if isinstance(data, Unload):
self.unload()
else:
# do something useful w... |
aronasorman/kolibri | kolibri/plugins/coach/views.py | Python | mit | 201 | 0 | from __future__ import absolute_import, print_function, unicode_literals
from django.views.generic.base import TemplateView
class CoachToolsView(TemplateView):
templa | te_name = "coach/coach.htm | l"
|
chengduoZH/Paddle | python/paddle/fluid/inferencer.py | Python | apache-2.0 | 685 | 0 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi | s 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, softwar | e
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: inferencer is moved into fluid.contrib.inferencer.
__all__ = []... |
gofed/gofed-ng | common/helpers/output.py | Python | gpl-3.0 | 1,931 | 0.001036 | #!/bin/python
# -*- coding: utf-8 -*-
# ####################################################################
# gofed-ng - Gol | ang system
# Copyright (C) 2016 Fridolin Pokorny, fpokorny@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) a | ny 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 copy of the GNU General Pub... |
compas-dev/compas | src/compas/files/off.py | Python | mit | 8,218 | 0.000608 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import compas
from compas import _iotools
class OFF(object):
"""Class for working with OFF files.
Parameters
----------
filepath : path string | file-like object | URL string
A path, ... | # if len(parts[1:]) >= f:
# face = [int(index) for index in parts[1:f + 1]]
# else:
# # add support for color info
# face = [int(index) for index in parts[1:]]
# while len(face) < f:
# line ... | p()
# if not line:
# break
# parts = line.split()
# if not parts:
# break
# face += [int(index) for index in parts]
if len(face) == f:
... |
AdeshAtole/coala | coalib/output/dbus/DbusDocument.py | Python | agpl-3.0 | 6,675 | 0.00015 | import os
import dbus.service # Ignore PyImportSortBear
from coalib.misc.Exceptions import get_exitcode
from coalib.output.Interactions import fail_acquire_settings
from coalib.output.printers.ListLogPrinter import ListLogPrinter
from coalib.parsing.Globbing import fnmatch
from coalib.processes.Processing import exe... | al
args = ["--config=" + self.config_file]
log_printer = ListLogPrinter()
exitcode = 0
try:
yielded_results = False
(sections,
local_bears,
global_bears,
targets) = gather_configura | tion(fail_acquire_settings,
log_printer,
arg_list=args)
for section_name in sections:
section = sections[section_name]
if not section.is_enabled(targets):
continue
... |
georgestarcher/TA-SyncKVStore | bin/ta_synckvstore/splunktaucclib/rest_handler/admin_external.py | Python | mit | 4,471 | 0 |
from __future__ import absolute_import
from functools import wraps
from splunk import admin
from solnlib.splunkenv import get_splunkd_uri
from solnlib.utils import is_true
from .eai import EAI_FIELDS
from .handler import RestHandler
__all__ = [
'make_conf_item',
'build_conf_info',
'AdminExternalHandler... | # use classic inheritance to be compatible for
# old version of Splunk private SDK
admin.MConfigHandler.__init__(
self,
*args,
**kwargs
)
self.handler = RestHandler(
get_splunkd_uri(),
self.getSessionKey(),
sel... | elf.payload = self._convert_payload()
def setup(self):
# add args for getting clear credentials
if self.requestedAction == admin.ACTION_LIST:
self.supportedArgs.addOptArg(self.ACTION_CRED)
# add args in payload while creating/updating
actions = (admin.ACTION_LIST, admin... |
antoinecarme/pyaf | tests/artificial/transf_RelativeDifference/trend_MovingAverage/cycle_30/ar_12/test_artificial_1024_RelativeDifference_MovingAverage_30_12_0.py | Python | bsd-3-clause | 279 | 0.082437 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset( | N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, e | xog_count = 0, ar_order = 12); |
kain88-de/mdanalysis | testsuite/MDAnalysisTests/core/test_segmentgroup.py | Python | gpl-2.0 | 3,335 | 0.0009 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- http://www.mdanalysis.org
# Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
... | t_atoms('all').segments
s.segids = 'ADK'
assert_equal(self.universe.segments.segids, ['ADK'],
err_msg="failed to set_segi | d on segments")
def test_set_segid_updates_self(self):
g = self.universe.select_atoms("resid 10:18").segments
g.segids = 'ADK'
assert_equal(g.segids, ['ADK'],
err_msg="old selection was not changed in place after set_segid")
def test_atom_order(self):
asser... |
red-hood/calendarserver | twistedcaldav/test/test_link.py | Python | apache-2.0 | 3,337 | 0.003596 | ##
# Copyright (c) 2008-2015 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | l(self):
| return self.hosturl
class LinkResourceTests(TestCase):
@inlineCallbacks
def test_okLink(self):
resource = CalendarHomeResource(self.site.resource, "home", object(), StubHome())
self.site.resource.putChild("home", resource)
link = LinkResource(resource, "/home/outbox/")
... |
shareactorIO/pipeline | source.ml/jupyterhub.ml/notebooks/zz_old/TensorFlow/SkFlow_DEPRECATED/iris.py | Python | apache-2.0 | 1,182 | 0.003384 | # Copyright 2015-present Scikit Flow 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... | ermissions and
# limitations under the License.
from sklearn import datasets, metrics, cross_validation
import skflow
# Load dataset.
iris = datasets.load_iris()
X_train, X_test, | y_train, y_test = cross_validation.train_test_split(iris.data, iris.target,
test_size=0.2, random_state=42)
# Build 3 layer DNN with 10, 20, 10 units respecitvely.
classifier = skflow.TensorFlowDNNClassifier(hidden_units=[10, 20, 10],
n_classes=3, steps=200)
# Fit and predict.
classifier.fit(X_train, y_train)... |
t-wissmann/qutebrowser | qutebrowser/config/websettings.py | Python | gpl-3.0 | 9,886 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014- | 2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish | ed by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 Genera... |
gnu-sandhi/sandhi | modules/gr36/gr-qtgui/python/__init__.py | Python | gpl-3.0 | 1,026 | 0.000975 | #
# Copyright 2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
#... | ge includes QT-based graphical
sinks.
'''
# The presence of this file turns this directory into a Python package
from qtgui_swig import *
import qtg | ui_swig as qtgui # to preserve the old interface
|
zooniverse/aggregation | experimental/algorithms/chimp.py | Python | apache-2.0 | 2,689 | 0.005206 | #!/usr/bin/env python
__author__ = 'greghines'
import numpy as np
import os
import pymongo
import urllib
import matplotlib.pyplot as plt
import cv2
# the directory to store the movie preview clips in
image_directory = "/home/greg/Databases/chimp/images/"
# connect to the mongodb server
client = pymongo.MongoClient()
... | on"]["previews"][0][0][:-5]
reason = s["metadata"]["retire_reason"]
# down every preview clip for this subject
for i in range(1,16):
url = preview_url + str(i) + ".jpg"
fname = id_+" | _"+str(i)+".jpg"
if not(os.path.isfile(image_directory+fname)):
urllib.urlretrieve(url, image_directory+fname)
# find the maximum mse between all pairs of images
differences = []
for i in range(1,16):
for j in range(i+1,16):
fname1 = image_directory+id_+"_"+str(i... |
h-medjahed/pyvcloud | examples/register_extension.py | Python | apache-2.0 | 1,517 | 0.004614 | #! /usr/bin/env python
import json
import time, datetime, os, sys
from pyvcloud.vcloudair import VCA
from pyvcloud.system import System
from pyvcloud.helper.CommonUtils import convertPythonObjToStr
def print_vca(vca):
if vca:
print 'vca token: ', vca.token
if vca.vcloud_session:
... | on: ', vca.vcloud_session.organization
else:
print 'vca vcloud session: ', vca.vcloud_session
el | se:
print 'vca: ', vca
host='vcd.cpsbu.eng.vmware.com'
username = 'administrator'
password = os.environ['PASSWORD']
org = 'System'
org_url = 'https://%s/cloud' % host
verify = False
log = True
version = '27.0'
extension_name = sys.argv[1]
vca = VCA(host=host, username=username, service_type='standalone', vers... |
yuanzhao/gpdb | concourse/scripts/build_orca.py | Python | apache-2.0 | 1,492 | 0.004692 | #!/usr/bin/python2
import argparse
import os
import subprocess
import sys
BASE_DIR = os.getcwd()
def build_install_orca(prefix, path):
# by default conan will install the files under /usr/local
return subprocess.call(["./configure --prefix={0} && make && make install_local".format(prefix)],
... | r.gz ./include | ./lib".format(BASE_DIR)],
shell=True, cwd=orca_install_dir_prefix)
def main():
parser = argparse.ArgumentParser(description='Main driver to build and install ORCA using conan')
parser.add_argument('--prefix', help='Configure prefix path', type=str, default='/tmp/')
required_argu... |
QijunPan/ansible | lib/ansible/modules/network/ios/ios_system.py | Python | gpl-3.0 | 12,626 | 0.00301 | #!/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... | module.fail_json(msg='vrf %s is not configured' % vrf)
def diff_list(want, have):
adds = [w for w in want if w not in have]
removes = [h for h in have if h not in want]
return (adds, removes)
def map_obj_to_commands(want, have, module):
comma | nds = list()
state = module.params['state']
needs_update = lambda x: want.get(x) and (want.get(x) != have.get(x))
if state == 'absent':
if have['hostname'] != 'Router':
commands.append('no hostname')
if have['lookup_source']:
commands.append('no ip domain lookup so... |
kensonman/mansonsolutions.sugar | src/sugar/views.py | Python | apache-2.0 | 4,129 | 0.030274 | # -*- coding: utf-8 -*-
#
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import HttpR... | ATETIME))
ws.cell(row=row, column=4, value=r.sugar)
ws.cell(row=row, column=5, value=r.pulse)
ws.cell(row=row, column=6, value=r.sys)
ws.cell(row=row, column=7, value=r.dia)
ro | w+=1
rst=HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
rst['Content-Disposition'] = 'attachment; filename=\"%s.xlsx\"'%filename
return rst
|
jamespcole/home-assistant | homeassistant/components/xeoma/camera.py | Python | apache-2.0 | 3,817 | 0 | """
Support for Xeoma Cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.xeoma/
"""
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.const import (
CONF_HOST,... | ry:
await xeoma.async_test_connection()
discovered_image_names = await xeoma.async_get_image_names()
discovered_cameras = [
{
CONF_IMAGE_NAME: image_name,
CONF_HIDE: False,
CONF_NAME: image_name,
CONF_VIEWER_USERNAME: us... | for image_name, username, pw in discovered_image_names
]
for cam in config.get(CONF_CAMERAS, []):
camera = next(
(dc for dc in discovered_cameras
if dc[CONF_IMAGE_NAME] == cam[CONF_IMAGE_NAME]), None)
if camera is not None:
if... |
etkirsch/legends-of-erukar | erukar/content/modifiers/material/random/Atherite.py | Python | agpl-3.0 | 1,596 | 0.005013 | from ..base.MagicOre import MagicOre
from erukar.system.engine import Observation
import erukar
class Atherite(MagicOre):
Probability = 200
Desirability = 4.0
InventoryDescription = "A whitish alloy infused with chaotic energies; enhances random effects by 25%"
InventoryName = "Atherite"
PriceMu... | = 12.5
WeightMultiplier = 3.1
DurabilityMultiplier = 1.2
Glances = [
Observation(acuity=5, sense=0, result="with a white {EssentialPart}"),
Observation(acuity=10, sense=0, result="with a whitish {EssentialPart} which shimmers a faint blue light "),
Observation(acuity=10, sense=10, r... | an white ore called Atherite, the {EssentialPart} shimmers in a faint blue light")
]
Inspects = [
Observation(acuity=5, sense=0, result="The {EssentialPart} is white with a faint blue sheen."),
Observation(acuity=10, sense=5, result="The {EssentialPart} is whitish, with a shimmering blue light.... |
fenglb/mysite | accounts/migrations/0005_auto_20160222_0832.py | Python | cc0-1.0 | 560 | 0.001786 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-22 00:32
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto | _20160221_1019'),
]
operations = [
migrations.AlterField(
| model_name='customuser',
name='expired_time',
field=models.DateField(default=datetime.datetime(2116, 1, 29, 8, 32, 18, 134168), verbose_name='\u5931\u6548\u65e5\u671f'),
),
]
|
hassanibi/erpnext | erpnext/schools/doctype/student/test_student.py | Python | gpl-3.0 | 270 | 0.007407 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frapp | e
import unittest
# | test_records = frappe.get_test_records('Student')
class TestStudent(unittest.TestCase):
pass
|
consbio/clover | trefoil/cli/__init__.py | Python | bsd-3-clause | 90 | 0.011111 | import click
@click.group(help="Co | mmand line inte | rface for trefoil")
def cli():
pass |
jsbain/stash | bin/echo.py | Python | mit | 1,000 | 0.007 | #!/usr/bin/env python
########################################################################.......
"""Print all arguments to stdout, separated by spaces.
"""
from __future__ import print_function
import sys
def main(args):
# Not using argparse here, because echo should echo anything that is not a
# valid... | erate(args):
if arg.startswith("-"):
if | set(arg[1:]) < set("neE"):
for char in arg[1:]:
if char == "n":
end = ""
elif char == "e":
escapes = True
elif char == "E":
escapes = False
remove.append(i... |
ed-/solum | functionaltests/api/v1/test_language_pack.py | Python | apache-2.0 | 8,151 | 0 | # Copyright 2014 - Rackspace
#
# 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,... | er(TestLanguagePackController, self).setUp()
def _delete_all(self):
resp, body = self.client.get('v1/language_packs')
data = json.loads(body)
self.assertEqual(resp.status, 200)
[self._delete_language_ | pack(pl['uuid']) for pl in data]
def _assert_output_expected(self, body_data, data):
self.assertEqual(body_data['description'], data['description'])
self.assertEqual(body_data['name'], data['name'])
self.assertEqual(body_data['language_implementation'],
data['langua... |
atodorov/anaconda | pyanaconda/ui/gui/spokes/lib/lang_locale_handler.py | Python | gpl-2.0 | 7,380 | 0.002033 | #
# Copyright (C) 2011-2012 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it wi... | ware Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat tra | demarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
"""
Module providing the LangLocaleHandler class that could be used as a mixin for
screens handling languages or lo... |
entering/pingdomexport | pingdomexport/tests/test_checks.py | Python | mit | 1,453 | 0.008947 | from pingdomexport import checks
from pingdomexport import configuration
class TestPicker:
def test_get_strategy_all(self):
picker = checks.Picker(
configuration.Checks('all', []),
{"checks": [{"id":1}, {"id":2}]}
)
assert picker.filter() == [{'id': 1}, {'id': 2}]
... | xclude', [1, 2]),
{"checks": [{"id":1}, {"id":2}]}
)
assert picker. | filter() == []
|
sebnil/python_uptimer | tests/test_requests.py | Python | mit | 934 | 0 | # force python 3.* compability
from __future__ import absolute_impor | t, division, print_function
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object)
# regular imports below:
import | unittest
from python_uptimer import up_check
import requests
from datetime import timedelta
class MyTestCase(unittest.TestCase):
def test_response_time(self):
jobs = [
up_check.Response('http://sebastiannilsson.com'),
up_check.Response('http://treplex.se'),
up_check.R... |
shoopio/shoop | shuup/campaigns/migrations/0010_hourbasketcondition.py | Python | agpl-3.0 | 1,137 | 0.001759 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-11-17 17:25
from __future__ import unicode_literals
import django.core.validators
import django.db.models.deletion
import re
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0009_h... | lds=[
('basketcondition_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='campaigns.BasketCondition')),
('hour_start', models.TimeField()),
('hour_end', models.TimeField()),
... | , message='Enter only digits separated by commas.')])),
],
options={
'abstract': False,
},
bases=('campaigns.basketcondition',),
),
]
|
jochym/Elastic | elastic/__init__.py | Python | gpl-3.0 | 2,543 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 1998-2011 by Paweł T. Jochym <pawel.jochym@ifj.edu.pl>
#
# This file is part of Elastic.
# Elastic 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 Softwar... | .0).
The ordering is: :math:`u_{xx}, u_{yy}, u_{zz}, u_{yz}, u_{xz}, u_{x | y}`.
The general ordering of :math:`C_{ij}` components is (except for triclinic
symmetry and taking into account customary names of constants - e.g.
:math:`C_{16} \\rightarrow C_{14}`):
.. math::
C_{11}, C_{22}, C_{33}, C_{12}, C_{13}, C_{23},
C_{44}, C_{55}, C_{66}, C_{16}, C_{26}, C_{36}, C_{45}
The function... |
village-people/flying-pig | ai_challenge/agents/_ignorebeta_dqn_agent_batch.py | Python | mit | 3,884 | 0.000515 | # 2017, Andrei N., Tudor B.
from sphinx.addnodes import centered
from ._ignore_Agent import Agent
from ._ignore_Agent import Transition
import matplotlib.pyplot as plt
from random import choice
import logging
import os
import numpy as np
import math
import random
import torch
import torch.nn as nn
import torch.opti... | self.eps_decay)
if sample > eps_threshold:
q = self._modelClass._model(Variable(observation, volatile=True))
action = q.data.max(1)
else:
action = torch.LongTensor([[self.action_space.samp | le()]])
return action
def _restart(self):
pass
def _epochFinished(self):
pass
def _report(self):
self._losses.append(self._lastLoss)
self.logger.info("Loss:: {}".format(self._lastLoss))
self._lastLoss = 0
def _saveModel(self, *args, **kwargs):
... |
Dylan-halls/Theseus | src/server/server.py | Python | mit | 2,762 | 0.034033 | import socket
from user_agents import parse
import multiprocessing
import ssl
import sys
from datetime import *
class HTTP_Server(object):
"""This is the http page spoofing Server"""
def __init__(self, bind_address, payloads_folder):
global http_responce, s, html
super(HTTP_Server, self).__init__()
bind_port =... | Connection = data.splitlines()[7]
Cache_Control = data.splitlines()[8]
except IndexError:
pass
#Print Status Message
ua = parse(user_agent)
print("[ HTTP ]", "[" ,datetime.now(), "]", "[" ,addr[0], "]", "[", str(ua).replace(" / ", '-') ,"]", request)
#Send File
if path == '/ | ':
er_resp = """
HTTP/1.1 200 OK
Content-Type: text/html
{}
"""
sock.sendall(er_resp.format(html).encode('utf-8'))
sock.close()
elif path == '/lock.png':
err_resp = """
HTTP/1.1 200 OK
Content-Type: image/png
""".encode('utf-8')
img_png = open(payloads_folder+path, 'rb')
img = img_png.read(... |
jrichte43/ProjectEuler | Problem-0263/solutions.py | Python | gpl-3.0 | 1,586 | 0.008207 |
__problem_title__ = "An engineers' dream come true"
__problem_url___ = "https://projecteuler.net/problem=263"
__problem_description__ = "Consider the number 6. The divisors of 6 are: 1,2,3 and 6. Every " \
"number from 1 up to and including 6 can be written as a sum of " \
... | ce of six is called a " \
"sexy pair (since "sex" is the Latin word for "six"). The first sexy " \
"pair is (23, 29). We may occasionally find a triple-pair, which means " \
"three consecutive sexy prime pairs, such that the | second member of " \
"each pair is the first member of the next pair. We shall call a " \
"number such that : Find the sum of the first four engineers’ " \
"paradises."
import timeit
class Solution():
@staticmethod
def solution1(... |
amanharitsh123/zulip | zerver/webhooks/travis/view.py | Python | apache-2.0 | 1,944 | 0.002572 | # Webhooks for external integrations.
from django.http import HttpRequest, HttpResponse
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success
from zerver.lib.validator import check_dict, ... | emoji = ':thumbsup:'
elif message_status in BAD_STATUSES:
emoji = ':thumbsdown:'
else:
emoji = "(No emoji specified for status '{}'.)".format(message_status)
body = MESSAGE_TEMPLATE.format(
message['author_name'],
message_status,
emoji,
message['compare_... | _url']
)
check_send_stream_message(user_profile, request.client, stream, topic, body)
return json_success()
|
Tuxemon/Tuxemon | tuxemon/item/effects/capture.py | Python | gpl-3.0 | 4,774 | 0.002723 | #
# Tuxemon
# Copyright (c) 2014-2017 William Edwards <shadowapex@gmail.com>,
# Benjamin Bean <superman2k5@gmail.com>
#
# This file is part of Tuxemon
#
# 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
#... | up variables for capture equation
status_modifier = 0
# TODO: Item power is set to 1 in order to not effect the | calculations
# Research the proper item_powers of pokeballs to use it as a multiplier.
item_power = 1
# The number of shakes that a tuxemon can do to escape.
total_shakes = 4
# The max catch rate.
max_catch_rate = 255
# In every shake a random number form [0-6553... |
linuxdeepin/deepin-storm | deepin_storm/common.py | Python | gpl-3.0 | 3,288 | 0.014294 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Hou Shaohui
#
# Author: Hou Shaohui <houshao55@gmail.com>
# Maintainer: Hou Shaohui <houshao55@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the ter... | os.rename(fn + ".tmp", fn)
except:
pass
def load_db(fn):
'''Load object from db file.'''
objs = None
if os.path.exists(fn):
f = open(fn, "rb")
try:
objs = cPickle.load(f)
except:
logger.logexception("%s is not a v... | se.", fn)
try:
os.unlink(fn)
except: pass
objs = None
f.close()
return objs
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`.
>>> o =... |
incaser/incaser-odoo-addons | website_maintenance/controllers/__init__.py | Python | agpl-3.0 | 213 | 0 | # -*- coding: utf-8 -*-
# ( | c) 2015 In | caser Informatica S.L. - Sergio Teruel
# (c) 2015 Incaser Informatica S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import main
|
GluuFederation/oxExternal | cache_refresh/sample/SampleScript.py | Python | mit | 2,443 | 0.003684 | # oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
# Copyright (c) 2016, Gluu
#
# Author: Yuriy Movchan
#
from org.gluu.model.custom.script.type.user import CacheRefreshType
from org.gluu.util import StringHelper, ArrayHelper
from java.util import Arrays, ArrayLis... | lass CacheRefresh(CacheRefreshType):
def __init__(self, currentTimeMillis):
self.currentTimeMillis = currentTimeMillis
def init(self, configurationAttributes):
print "Cache refresh. Initialization"
print "Cache refresh. Initialized suc | cessfully"
return True
def destroy(self, configurationAttributes):
print "Cache refresh. Destroy"
print "Cache refresh. Destroyed successfully"
return True
# Get bind credentials required to access source server
# configId is the source server
# configurati... |
ikeikeikeike/analytics-counter | analytics_counter/analytics_counter/settings.py | Python | mit | 1,032 | 0.004845 | # Scrapy settings for a | nalytics_counter project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'analytics_counter'
SPIDER_MODULES = ['analytics_counter.spiders']
NEWSPIDER_MODULE = 'an... | zilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" # Firefox 9.0
DOWNLOAD_HANDLERS = {
'http': 'scrapy_webdriver.download.WebdriverDownloadHandler',
'https': 'scrapy_webdriver.download.WebdriverDownloadHandler',
}
SPIDER_MIDDLEWARES = {
'scrapy_webdriver.middlewares.Webdri... |
djpine/linfit | setup.py | Python | lgpl-2.1 | 560 | 0.001789 |
#!/usr/bin/python3
# -*- | coding: utf-8 -*-
# Copyright © 2014 Martin Ueding <dev@martin-ueding.de>
# Licensed under The Lesser GNU Public License Version 2 (or later)
from setuptools import setup, find_packages
setup(
author="David Pine",
description="Least squares linear fit for numpy library of Python",
license="LGPL2",
na... | s://github.com/djpine/linfit",
download_url="https://github.com/djpine/linfit",
version="2014.9.3",
)
|
pitunti/alfaPitunti | plugin.video.alfa/channels/porntrex.py | Python | gpl-3.0 | 12,905 | 0.006206 | # -*- coding: utf-8 -*-
import re
import urllib
import urlparse
from core import httptools
from core import scrapertools
from core.item import Item
from platformcode import config, logger
host = "https://www.porntrex.com"
def mainlist(item):
logger.info()
itemlist = []
config.set_setting("url_error", ... | scrapedurl = urlparse.urljoin( | host, scrapedurl)
if duration:
scrapedtitle = "%s - %s" % (duration, scrapedtitle)
if '>HD<' in quality:
scrapedtitle += " [COLOR red][HD][/COLOR]"
itemlist.append(item.clone(action=action, title=scrapedtitle, url=scrapedurl, thumbnail=scrapedthumbnail,
... |
weiwang/project_euler | python/Q46.py | Python | mit | 334 | 0.005988 | ximport math
a = open("Q46.txt")
|
words = []
for i in a. | read().replace('"', '').strip("\"").split(","):
words.append(i)
triangle = []
for word in words:
num = sum([ord(a)-64 for a in word])
nn = math.trunc((2*num)**.5 )
if 2*num == (nn*(nn+1)):
triangle.append(True)
else:
triangle.append(False)
|
arokem/scipy | scipy/optimize/tests/test_linesearch.py | Python | bsd-3-clause | 10,206 | 0.000588 | """
Tests for line search routines
"""
from __future__ import division, print_function, absolute_import
from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
assert_array_almost_equal_nulp, assert_warns,
suppress_warnings)
import scipy.optimi... | for old_phi0 in np.random.randn(3):
| yield name, phi, derphi, old_phi0
def line_iter(self):
for name, f, fprime in self.line_funcs:
k = 0
while k < 9:
x = np.random.randn(self.N)
p = np.random.randn(self.N)
if np.dot(p, fprime(x)) >= 0:
# always pic... |
shengqh/ngsperl | lib/Annotation/findOverlapGene.py | Python | apache-2.0 | 1,368 | 0.017544 | import subprocess
import os.path
import re
import argparse
import sys
from pybedtools import BedTool
DEBUG = False
parser = argparse.ArgumentParser(description="find overlap gene.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
if not DEBUG:
parser.add_argument('-i', '--i... | engq1/vickers/20170720_AGO_human_CLIP/macs2/result/GSM1020022/GSM1020022_peaks.narrowPeak.bed"
gene_file = "/scratch/cqs/shengq1/references/smallrna/v3/hg19_miRBase21_GtRNAdb2_gencode19_ncbi.sorted.bed"
output_file="/scratch/cqs/shengq1/vickers/20170720_AGO_human_CLIP/macs2/result/GSM1020022/GSM1020022 | _peaks.narrowPeak.overlap.tsv"
closet = [nearest for nearest in BedTool(input_file).closest(gene_file, d=True)]
with open(output_file, 'w') as w:
for nearest in closet:
overlap = nearest.fields[12]
if overlap == u'0':
w.write(str(nearest))
|
nick-youngblut/SIPSim | tests/test_BD_Shift.py | Python | mit | 595 | 0.006723 | #!/usr/bin/env python
# import
from __future__ import print_function
## batteries
import os
i | mport sys
import pytest
## 3rd party
import numpy as np
import pandas as pd
## package
from SIPSim.Commands import BD_Shift as BD_Shift_CMD
from SIPSim import Utils
# data dir
test_dir = os.path.join(os.path.dirname(__file__))
data_dir = os.path.join(test_dir, 'data')
# load kde
def test_cmd():
f1 = os.path.join(... | gs)
|
seanbradley/mediacore_panda | mediacore_panda/__init__.py | Python | gpl-3.0 | 2,033 | 0.003443 | # This file is a part of MediaCore-Panda, Copyright 2011 Simple Station Inc.
#
# MediaCore 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 versi... | ort observes
from mediacore_panda.lib.storage import PandaStorage
log = logging.getLogger(__name__)
@observes(events.Environment.routes)
de | f add_routes(mapper):
mapper.connect('/admin/plugins/panda',
controller='panda/admin/settings',
action='panda')
mapper.connect('/admin/plugins/panda/save',
controller='panda/admin/settings',
action='panda_save')
@observes(events.Admin.MediaController.edit)
def add_panda_vars(**r... |
adelq/penndining | hours.py | Python | gpl-3.0 | 2,542 | 0.003147 | from datetime import datetime, time
class hall():
"""
Creates new objects with open and closing times
"""
def __init__(self, open, close):
self.open = open
self.close = close
class hours():
"""
Creates object for eating time with opening and closing times
"""
def __init... | ) - ctm
if wd == 6:
if status == "Brunch":
return time(15) - ctm
else:
return time(20) - ctm
else:
if status == "Lunch":
return time(14) - ctm
else:
return time(21) - ctm
def status(hall):
... | lse:
return "Open"
time_to_close("commons")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.