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 |
|---|---|---|---|---|---|---|---|---|
onezens/python | basic/15_regex_getimage.py | Python | mit | 386 | 0.03886 | #encoding=utf8
import re
import urllib
def getUrl(url):
page = urllib.urlopen(url)
return page.read()
def getImages(html):
images = re.findall(r'src="(.*?\.(jpg|png))"', html)
x = 1
for imageurl in images :
print('downloading %s'%imageurl[0])
urllib.urlretrieve(imageurl[0], './images/%d.jpg'%x)
x += | 1
html = getUrl('http://www.tooopen.com/im | g/87.aspx')
getImages(html)
|
morelab/weblabdeusto | server/src/test/deployments/federated_basic_sql/provider1/core_config.py | Python | bsd-2-clause | 1,626 | 0.014145 | from __future__ import print_function, unicode_literals
core_store_students_programs = False
core_store_students_programs_path = 'files_stored'
core_experiment_poll_time = 350 # seconds
# Ports
core_facade_port = 28345
core_facade_server_route = 'provider1-route'
# Will only work in JSON in this conf... | exp1|dummy3_with_other_name|Dummy experiments" : "dummy3_with_other_name@dummy3_with_other_name",
}
}
core_coordinator_external_servers = {
'dummy1@Dummy | experiments' : [ 'dummy1_external' ],
'dummy4@Dummy experiments' : [ 'dummy4' ],
}
_provider2_scheduling_config = ("EXTERNAL_WEBLAB_DEUSTO", {
'baseurl' : 'http://127.0.0.1:38345/weblab/',
'username' : 'provider1',
... |
joyhuang-web/flaskbb | tests/unit/utils/test_permissions.py | Python | bsd-3-clause | 3,474 | 0.000576 | """
This test will use the default permissions found in
flaskbb.utils.populate
"""
from flaskbb.utils.permissions import *
def test_moderator_permissions_in_forum(
forum, moderator_user, topic, topic_moderator):
"""Test the moderator permissions in a forum where the user is a
moderator.
""... | ic(admin_user, forum)
assert can_edit_post(admin_user, topic.user_id, forum)
assert can_delete_post(admin_user, topic.user_id, forum)
assert can_delete_topic(admin_user, topic.user_id, forum)
assert can_edit_user(admin_user)
assert can_ban_user(admin_user)
def test_super_moderator_permissions(fo... | r."""
assert can_moderate(super_moderator_user, forum)
assert can_post_reply(super_moderator_user, forum)
assert can_post_topic(super_moderator_user, forum)
assert can_edit_post(super_moderator_user, topic.user_id, forum)
assert can_delete_post(super_moderator_user, topic.user_id, forum)
asser... |
ethantang95/DIGITS | digits/extensions/data/imageProcessing/forms.py | Python | bsd-3-clause | 3,146 | 0.001907 | # Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import os
from flask.ext.wtf import Form
from wtforms import validators
from digits import utils
from digits.utils import subclass
from digits.utils.forms import validate_required_iff
@subclass
class Dataset... | ('non | e', 'None'),
],
default='none',
tooltip="Perform selected channel conversion."
)
|
pidpawel/komiksowiec | docs/source/conf.py | Python | mit | 9,830 | 0.000102 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Komiksowiec documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 3 23:11:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... | Language to be used for generating the HTML full-text | search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user c... |
antoinecarme/pyaf | tests/artificial/transf_RelativeDifference/trend_Lag1Trend/cycle_5/ar_/test_artificial_32_RelativeDifference_Lag1Trend_5__0.py | Python | bsd-3-clause | 271 | 0.084871 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 5, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, a | r_order = 0); | |
0x0mar/MITMf | sslstrip/SSLServerConnectionHSTS.py | Python | gpl-3.0 | 4,966 | 0.015304 | # Copyright (c) 2004-2009 Moxie Marlinspike
#
# 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 distri... | values)
if (key.lower() == 'access-control-allow-origin'):
value='*'
ServerConnection.handleHeader(self, key, value)
def stripFileFromPath(self, path):
(strippedPath, lastSlash, file) = path.rpartitio | n('/')
return strippedPath
def buildAbsoluteLink(self, link):
absoluteLink = ""
if ((not link.startswith('http')) and (not link.startswith('/'))):
absoluteLink = "http://"+self.headers['host']+self.stripFileFromPath(self.uri)+'/'+link
loggin... |
MartinHjelmare/home-assistant | homeassistant/components/futurenow/light.py | Python | apache-2.0 | 3,852 | 0 | """Support for FutureNow Ethernet unit outputs as Lights."""
import logging
import voluptuous as vol
from homeassistant.const import (
CONF_NAME, CONF_HOST, CONF_PORT, CONF_DEVICES)
from homeassistant.components.light import (
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light,
PLATFORM_SCHEMA)
import homeassist... |
def brightness(self):
"""Return the brightness of this light between 0..255."""
return self._brightness
@property
def supported_features(self):
"""Flag supported features."""
if self._dimmable:
return SUPPORT_BRIGHTNESS
return | 0
def turn_on(self, **kwargs):
"""Turn the light on."""
if self._dimmable:
level = kwargs.get(ATTR_BRIGHTNESS, self._last_brightness)
else:
level = 255
self._light.turn_on(to_futurenow_level(level))
def turn_off(self, **kwargs):
"""Turn the light... |
fsimkovic/cptbx | conkit/io/fasta.py | Python | gpl-3.0 | 4,452 | 0.000674 | # BSD 3-Clause License
#
# Copyright (c) 2016-19, University of Liverpool
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notic... | elif line.startswith(">"):
break
chunks.append(line)
line = f_handle.readline().rstrip()
_seq_string = "".join(chunks) # Sequence from chunks
sequence_entry = Sequence(id, _seq_string)
hierarchy.add(sequence_entry... | break
return hierarchy
def write(self, f_handle, hierarchy):
"""Write a sequence file instance to to file
Parameters
----------
f_handle
Open file handle [write permissions]
hierarchy : :obj:`~conkit.core.sequencefile.SequenceFile`, :obj:`~conkit.c... |
jakubbrindza/gtg | GTG/backends/__init__.py | Python | gpl-3.0 | 8,418 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau
#
# This program is free software: you can redistribute it and/or modify it under
# t... | {}):
'''
Constructs a new backend initialization dictionary. In more
exact terms, creates a dictionary, containing all the necessary
entries to initialize a backend.
'''
if backend_name not in self.backend_modules:
return None
dic = {}
module =... | ers = module.Backend.get_static_parameters()
# we all the parameters and their default values in dic
for param_name, param_dic in parameters.items():
dic[param_name] = param_dic[GenericBackend.PARAM_DEFAULT_VALUE]
dic["pid"] = str(uuid.uuid4())
dic["module"] = module.Backend.... |
Elchi3/kuma | kuma/users/providers/google/views.py | Python | mpl-2.0 | 1,558 | 0.003209 | from urllib.parse import urlparse
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import (
OAuth2CallbackView,
OAuth2LoginView,
)
from kuma.core.decorators import redirect_in_maintenance_mode
from kuma.core.ga_tracking import ACTIO... |
# See https://github.com/mdn/kuma/issues/6759
ht | tp_referer = request.META.get("HTTP_REFERER")
if http_referer:
if urlparse(http_referer).netloc == request.get_host():
track_event(CATEGORY_SIGNUP_FLOW, ACTION_AUTH_STARTED, "google")
return super().dispatch(request)
oauth2_login = redirect_in_maintenance_mode(
KumaOAut... |
mac389/inuit | src/get-facebook-posts.py | Python | apache-2.0 | 248 | 0.020161 | import requests, json
tokens = json.load(open('tokens.json','rb'))
APP_ID = token | s['id']
APP_SECRET = tokens['secret']
ACCESS_TOKEN = tokens['long_access_token']
base = 'http://graph.facebook/com'
payload = {''}
r | = requsts.get(base,payload)
|
NUKnightLab/cityhallmonitor | cityhallmonitor/migrations/0003_matterattachment_link_obtained_at.py | Python | mit | 440 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django | .db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cityhallmonitor', '0002_matter_attachments_obtained_at'),
]
operations = [
migrations.AddField(
model_name='matterattachment',
name='l | ink_obtained_at',
field=models.DateTimeField(null=True),
),
]
|
oridgar/PersonaLab | personalab/drivers/objects/libvirt.py | Python | gpl-3.0 | 583 | 0.006861 | from personalab.drivers.objects.base import Vm
class LibVirtVm(Vm):
"""
:type base_object: libvirt.virDomain
"""
def __init__(self,domain):
#self.base_object = libv | irt.virDomain()
self.base_object = domain
#super(self.__class__, self).__init__(domain)
def start(self):
self.base_object.create()
def stop(self):
self.base_object.destroy()
def restart(self):
self.base_object.reboot()
def reset(self):
self.base_object... | return self.base_object.name() |
free-free/pyblog | pyblog/cache/cache_abstract.py | Python | mit | 1,626 | 0.000615 | #-*- coding:utf-8 -*-
class CacheAbstractDriver:
def __init__(self, *args, **kw):
pass
def put(self, key, value, expires, key_prefix):
r"""
@put a value to cache system
@parameters:
| key :must be 'str' type or 'dict ' type
when 'key' is 'dict' type,value must be None value
value:list,tuple,dict,None,one of them
expires:must be 'int' type,units is seconds
key_prefix: 'str' type
"""
raise NotImplemented... | tem
"""
raise NotImplementedError
def get_delete(self, key, key_prefix):
r"""
@get and delete a cache value from cache system
"""
raise NotImplementedError
def delete(self, key, key_prefix):
r"""
@delete a cache value from cache system
... |
zmeadows/bloch_fit | plot/plot_filter_fft.py | Python | mit | 702 | 0.007123 | import sys
sys.path.append('/Users/zac/Research/muon_g2_2015/nmr/bloch_fit')
import matplotlib.pyplot as plt
from pulse import NMRPulseFiltered
import util as u
impor | t numpy as np
import math
p = NMRPulseFiltered(u.get_pulse_path())
d_hz = p.raw_freqs[1] - p.raw_freqs[0]
ei = (p.w_ref * 8 / (2*math.pi)) / d_hz
plt.figure(facecolor=u.LIGHTGREY)
plt.plot(p.raw_freqs[:ei], np.abs(p.raw_fft)[:ei], color=u.BLUE)
plt.plot(p.raw_freqs[:ei], np.abs(p.filter_fft)[:ei], color=u.RED, alpha... | p.min(0.99*np.abs(p.raw_fft)), 1.1*np.max(np.abs(p.raw_fft)))
plt.show()
|
msullivan/advent-of-code | 2015/A8b.py | Python | mit | 340 | 0.005882 | #!/usr/bin/env python3
import sys |
def main(args):
cmds = [s.strip() for s in sys.stdin]
sum = 0
for i in cmds:
a = i
a = a.replace('\\', '\\\\')
a = a.replace("\"", '\\"')
a = '"' + a + '"'
sum += len(a) - len(i)
print(sum)
if __ | name__ == '__main__':
sys.exit(main(sys.argv))
|
MichaelAquilina/pytest | testing/test_terminal.py | Python | mit | 31,303 | 0.000096 | """
terminal reporting of the full testing process.
"""
from __future__ import absolute_import, division, print_function
import collections
import sys
import _pytest._pluggy as pluggy
import _pytest._code
import py
import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED
from _pytest.terminal import TerminalReport... | makepyfile("""
def test_1():
import time
time.sleep(20)
""")
child = testdir.spawn_pytest("")
child.expect(".*test_runtest_location.*py")
child.sendeof()
child.kill(15)
def test_itemreport_subclasses_show_subc | lassed_file(self, testdir):
testdir.makepyfile(test_p1="""
class BaseTests(object):
def test_p1(self):
pass
class TestClass(BaseTests):
pass
""")
p2 = testdir.makepyfile(test_p2="""
from test_p1 import BaseTe... |
hatbot-team/hatbot | lang_utils/morphology/word_forms.py | Python | mit | 2,577 | 0.00369 | from pymorphy2.analyzer import Parse
__author__ = 'moskupols'
from lang_utils.morphology import morph
# def get_forms(initial):
# """
# Get all possible forms of a given word in initial form.
#
# >>> get_forms('мама')
# ['мам', 'мама', 'мамам', 'мамами', 'мамах', 'маме', 'мамой', 'мамою', 'маму', 'ма... | ans.extend(p.inflect(...))
def get_initial_forms(form: str, part_filter=None)->list:
"""
Gets all possible initial forms (there are several of them sometimes) of a given word.
Optional argument part_filter allows to prune unnecessary ambiguity with part of speech.
>>> get_initial_forms('Дядя')
[... | )
['самый']
>>> get_initial_forms('честных')
['честной', 'честный']
>>> get_initial_forms('правил')
['правило', 'править']
>>> get_initial_forms('правил', 'NOUN')
['правило']
>>> get_initial_forms('правил', ['VERB'])
['править']
:param form: a russian word
:param part_filter... |
MKridler/pyxley | pyxley/charts/nvd3/two_axis_focus.py | Python | mit | 2,870 | 0.003833 |
from .nvd3 import NVD3
from flask import jsonify, request
import numpy as np
class TwoAxisFocus(NVD3):
_allowed_axes = ["sigma", "minmax"]
def __init__(self, x, y1, y2, data_source, init_params={},
chart_id="new_chart", url="/new_chart/", colors=[], auto_scale="sigma",
y1_axis_range=[], y2_axi... | ata)
def get_bounds(self, y, method="sigma"):
if self.auto_scale == "sigma":
m_, s_ = y.mean(), y.std()
l = m_ - self.sigma*s_
u = m_ + sel | f.sigma*s_
else:
l = y.min()
u = y.max()
return [l, u]
def to_json(self, df):
if df.empty:
return {
"data": [],
"yAxis1": {"lower": 0, "upper": 1},
"yAxis2": {"lower": 0, "upper": 1}
}
i... |
kpj/PySpaMo | automata.py | Python | mit | 3,756 | 0.000532 | """
Implementation of several spatial models running on a lattice
"""
import numpy as np
from tqdm import tqdm
class CellularAutomaton(object):
""" General CA class
"""
def __init__(self, lattice):
self.lattice = lattice
def setup(self):
""" This function is called before any itera... | def apply_ru | le(self, mat):
""" Return the new lattice
"""
raise NotImplementedError
def iterate(self, steps, **kwargs):
""" Yield each step up to `steps` of the current CA
"""
self.setup(**kwargs)
yield self.lattice
for _ in tqdm(range(steps)):
self.... |
cshzc/X1Tool | src/server/apps/utils/__init__.py | Python | gpl-2.0 | 25 | 0 | __author__ = 'zh | ichengh'
| |
rsignell-usgs/notebook | tri_tide_movie/python/tri_tide_movie.py | Python | mit | 5,982 | 0.004681 |
# coding: utf-8
# In[7]:
import pytz
from datetime import datetime
from pandas import date_range
import iris
import warnings
import pyugrid
# In[8]:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# ncfile = ('http://geoport.whoi.edu/thredds/dodsC/usgs/vault0/models/tides/'
# '... |
w = units['knots'] * (U + 1j * V)
wf = np.NaN * np.ones_like(lonf, dtype=w.dtype)
wf[inbox] = w
# FIXME: Cannot use masked arrays and tricontour!
# wf = ma.masked_invalid(wf)
# cs = ax.tricontour(lonf, la | tf, trif, np.abs(wf).filled(fill_value=0))
# fig.colorbar(cs)
q = ax.quiver(lon, lat, U, V, scale=40)
ax.axis(bbox) # Vineyard sound 2.
ax.set_title('{}'.format(glocals[k]))
fig, ax = plt.subplots(figsize=(7, 5))
FuncAnimation(fig, update_figure, interval=100, frames=ntimes)
# In[ ]:
plt.figure(fig... |
qrkourier/ansible | lib/ansible/modules/cloud/amazon/ec2_vpc_subnet.py | Python | gpl-3.0 | 9,267 | 0.002806 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterf... | e))
to_add = dict((k, tags[k]) for k in tags if k not in cur_tags or cur_tags[k] != tags[k])
if to_add and not check_mode:
conn.create_tags(Resources=[subnet['id']], Tags=ansible_dict_to_boto3_tag_list(to_add))
except botocore.exceptions.ClientError as e:
if e.response['Error']... | _dict_to_snake_dict(e.response))
def ensure_map_public(conn, module, subnet, map_public, check_mode):
if check_mode:
return
try:
conn.modify_subnet_attribute(SubnetId=subnet['id'], MapPublicIpOnLaunch={'Value': map_public})
except botocore.exceptions.ClientError as e:
module.fail_... |
jayvdb/coala | coalib/misc/BuildManPage.py | Python | agpl-3.0 | 7,352 | 0 | import argparse
import datetime
from distutils.core import Command
from distutils.errors import DistutilsOptionError
class BuildManPage(Command):
# Start ignoring LineContinuationBear
"""
Add a ``build_manpage`` command to your setup.py.
To use this Command class add a command to call this class::
... | g_desc)
else:
return ''
def _mk_options(self):
formatter = self._parser._get_formatter()
# positionals, optionals and user-defined groups
for action_group in self._parser._action_groups:
formatter.start_section(None)
formatter.add_text(None)
... | epilog
formatter.add_text(self._parser.epilog)
# determine help from format above
return '.SH OPTIONS\n' + formatter.format_help()
def _mk_footer(self):
sections = self._ext_sections
if not hasattr(sections, '__iter__'):
return ''
footer = []
... |
kamcpp/tensorflow | tensorflow/python/kernel_tests/constant_op_test.py | Python | apache-2.0 | 26,533 | 0.011495 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Versi | on 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BAS... | permissions and
# limitations under the License.
# ==============================================================================
"""Tests for ConstantOp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from te... |
thedrow/samsa | pykafka/topic.py | Python | apache-2.0 | 7,391 | 0.000271 | """
Author: Keith Bourgoin, Emmett Butler
"""
__license__ = """
Copyright 2015 Parse.ly, 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 ... | perty
def partitions(self):
"""A dictionary containing all known partitions for this topic"""
return self._partitions
def get_producer(self, use_rdkafka=False, **kwargs):
"""Create a :class:`pykafka.producer.Producer` for this topic.
For a description of all available `kwargs`,... | """
if not rdkafka and use_rdkafka:
raise ImportError("use_rdkafka requires rdkafka to be installed")
if isinstance(self._cluster.handler, GEventHandler) and use_rdkafka:
raise ImportError("use_rdkafka cannot be used with gevent")
Cls = rdkafka.RdKafkaProducer if ... |
jpelias/pyTelegramBotAPI | telebot/__init__.py | Python | gpl-2.0 | 20,143 | 0.003426 | # -*- coding: utf-8 -*-
from __future__ import print_function
import threading
import time
import re
import sys
import six
import logging
logger = logging.getLogger('TeleBot')
formatter = logging.Formatter('%(asctime)s (%(filename)s:%(lineno)d) %(levelname)s - %(name)s: "%(message)s"')
console_output_handler = loggi... | R)
from telebot import apihelper, types, util
"""
Module : telebot
"""
class TeleBot:
""" This is TeleBot Class
Methods:
getMe
sendMessage
forwardMessage
sendPhoto
sendAudio
sendDocument
sendSticker
sendVideo
sendLocation
sendChat... | ):
"""
:param token: bot API token
:param create_threads: Create thread for message handler
:param num_threads: Number of worker in thread pool.
:return: Telebot object.
"""
self.token = token
self.update_listener = []
self.polling_thread = None
... |
bchiroma/DreamProject_2 | dream/plugins/BatchesWIPSpreadsheet.py | Python | gpl-3.0 | 1,317 | 0.019742 | from copy import copy
import json
import time
import random
import operator
from datetime import datetime
from dream.plugins import plugin
class BatchesWIPSpreadsheet(plugin.InputPreparationPlugin):
""" Input prepration
read wip-srpeadsheet data and update the wip property of the stations.
"""
def prepr... |
wipData=data['input'].get('wip_spreadsheet', None)
node=data['graph']['node']
if wipData:
wipData.pop(0) # po | p the column names
for wipItem in wipData:
partId=wipItem[0]
# in case there is no id, do not process the element
if not partId:
continue
stationId=wipItem[1]
numberOfUnits=wipItem[2]
unitsToProcess=wipItem[3]
if not unitsToProcess:
uni... |
mtekel/digitalmarketplace-supplier-frontend | app/main/forms/suppliers.py | Python | mit | 1,562 | 0 | from flask.ext.wtf import Form
from wtforms import IntegerField, StringField, FieldList
from wtforms.validators import DataRequired, Email, ValidationError
def word_length(limit=None, message=None):
message = message or 'Must not be more than %d words'
message = message % limit
def _length(form, field):
... | n field
if len(field.data.split()) > limit:
raise ValidationError(message)
return _length
class EditSupplierForm(Form):
description = StringField('Supplier summary', validators=[
word_length(50, 'Your summary must not be more than %d words')
])
clients = FieldList(StringF... | onError('You must have 10 or fewer clients')
class EditContactInformationForm(Form):
id = IntegerField()
address1 = StringField('Business address')
address2 = StringField('Business address')
city = StringField('Town or city')
country = StringField()
postcode = StringField(validators=[
... |
mferenca/HMS-ecommerce | ecommerce/extensions/analytics/utils.py | Python | agpl-3.0 | 4,120 | 0.003398 | from functools import wraps
import json
import logging
from threadlocals.threadlocals import get_current_request
logger = logging.getLogger(__name__)
def is_segment_configured():
"""Returns a Boolean indicating if Segment has been configured for use."""
return bool(get_current_request().site.siteconfigurat... | nce_exceptions(msg):
"""Silences exceptions raised by the decorated function.
| Also logs the provided message. Used to silence exceptions raised by
non-essential signal receivers invoked with `send()`, to prevent critical
program flow from being interrupted.
Arguments:
msg (str): A message to be logged when an exception is raised.
"""
def decorator(func): # pylint: d... |
srottem/indy-sdk | wrappers/python/tests/payment/test_build_get_payment_sources_request.py | Python | apache-2.0 | 828 | 0.006039 | from indy import IndyError
from indy import payment
from indy.error import ErrorCode
from tests.payment.constants import *
import pytest
@pytest.mark.asyncio
async def test_build_get_payment_sources_request_works_for_unknown_payment_method(wallet_handle, did_trustee):
with pytest.raises(IndyError) as e:
... | ndle, did_trustee, payment_address)
assert ErrorCode.PaymentUnknownMethodError == e.value.error_code
@pytest.mark.asyncio
async def test_build_get_payment_sources_request_works_for_invalid_payment_address(wallet_handle, did_trustee):
with pytest.raises(IndyE | rror) as e:
await payment.build_get_payment_sources_request(wallet_handle, did_trustee, "pay:null1")
assert ErrorCode.PaymentIncompatibleMethodsError == e.value.error_code |
problemshift/kf5py | setup.py | Python | mit | 711 | 0.002813 | from setuptools import setup
setup(
name='kf5py',
py_modules = ['kf5py'],
version='0.1.8',
author='Chris Teplovs',
author_email='dr.chris@problemshift.com',
url='http://problemshift.github.io/kf5py/',
lice | nse='LICENSE.txt',
description='Python-based utilities for KF5.',
install_requires=[
"requests >= 2.3.0"
],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Development Status :: 3 - Alp... | esearch",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"
]
)
|
nist-ionstorage/electrode | electrode/pattern_constraints.py | Python | gpl-3.0 | 8,125 | 0.000738 | # -*- coding: utf8 -*-
#
# electrode: numeric tools for Paul traps
#
# Copyright (C) 2011-2012 Robert Jordens <jordens@phys.ethz.ch>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, e... | ve : str
Derivative to constrain/optimize. String of characters from
"xyz". See `utils.name_to_deriv.keys()` for possible values.
Not all possible cartesian derivatives are allowed, only those
that are evaluated as the basis for the given order. Use
`MultiPotentialObjective` to c... | system. np.eye(3) if None.
**kwargs : any
Passed to `SingleValueConstraint()`
"""
def __init__(self, x, derivative, rotation=None, **kwargs):
super(PotentialObjective, self).__init__(**kwargs)
self.x = np.asanyarray(x, np.double)
self.derivative = derivative
self.orde... |
syci/ingadhoc-odoo-addons | warning_box/__openerp__.py | Python | agpl-3.0 | 1,526 | 0.000655 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2013 jmesteve All Rights Reserved
# https://github.com/jmesteve
# <jmesteve@me.com>
#
# This program is... | ='the message')
""",
'author': 'jmesteve, ADHOC SA',
'w | ebsite': 'https://github.com/jmesteve',
'license': 'AGPL-3',
"depends": ['base'],
"data": [
'warning_box.xml',
],
"active": False,
"installable": True
}
|
bastibl/gnuradio | gr-dtv/python/dtv/atsc_rx_filter.py | Python | gpl-3.0 | 2,603 | 0.006915 | #!/usr/bin/env /usr/bin/python
#
# Copyright 2014 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 2, or (at your o... | the file COPYING. If not, write t | o
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
from __future__ import division
from __future__ import unicode_literals
from gnuradio import gr, filter
from . import dtv_swig as dtv
# FIXME move these into separate constants module
ATSC_CHANNEL_BW = 6.0e6
ATSC_SYMB... |
wright-group/WrightTools | tests/kit/diff.py | Python | mit | 1,245 | 0.001606 | """Test diff."""
# --- import -------------------------------------------------------------------------------------
import numpy as np
import WrightTools as wt
# --- test ---------------------------------------------------------------------------------------
def test_ascending_1():
x = np.linspace(0, 10, 1... | np.sin(x)
d = wt.kit.diff(x, y, 3)
assert np.all((np.abs(d + np.cos(x)) < 0.0001)[2:-3])
def test_ascending_4():
x = np.linspace(0, 10, 1000)
y = np.sin(x)
d = wt.kit.diff(x, y, 4)
assert np.all((np.abs(d - np.sin(x)) < 0.0001)[3:-4])
def test_descending | _1():
x = np.linspace(10, 0, 1000)
y = np.sin(x)
d = wt.kit.diff(x, y)
assert np.all((np.abs(d - np.cos(x)) < 0.0001)[1:-1])
def test_descending_3():
x = np.linspace(10, 0, 1000)
y = np.sin(x)
d = wt.kit.diff(x, y, 3)
assert np.all((np.abs(d + np.cos(x)) < 0.0001)[3:-3])
|
BrentonEarl/slpkg | slpkg/sbo/slackbuild.py | Python | gpl-3.0 | 13,275 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# slackbuild.py file is part of slpkg.
# Copyright 2014-2015 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installations
# https://github.com/dslackw/slpkg
# Slpkg is free software: you can redi... | self.dependencies = []
self.package_not_found = []
self.package_found = []
self.deps_dict = {}
self.answer = ""
self.match = False
| self.count_ins = 0
self.count_upg = 0
self.count_uni = 0
self.msg.reading()
self.data = SBoGrep(name="").names()
self.blacklist = BlackList().packages(pkgs=self.data, repo="sbo")
def start(self, if_upgrade):
"""Start view, build and install SBo packages
""... |
dgunter/scapytojson | examples/basic_sniff.py | Python | mit | 1,348 | 0.001484 | '''
The MIT License (MIT)
Copyright (c) 2015 Dan Gunter
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 restrictio | n, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
... | RRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEAL... |
carmark/vbox | src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/GenFds/Vtf.py | Python | gpl-2.0 | 7,215 | 0.01885 | ## @file
# process VTF generation
#
# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found ... |
for ComponentObj in self.ComponentStatementList :
| BsfInf.writelines ("COMP_NAME" + \
" = " + \
ComponentObj.CompName + \
T_CHAR_LF )
if ComponentObj.CompLoc.upper() == 'NONE':
BsfInf.writelines ("COMP_LOC" + \
... |
catapult-project/catapult-csm | telemetry/telemetry/testing/run_tests_unittest.py | Python | bsd-3-clause | 3,839 | 0.003647 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.core import util
from telemetry.testing import run_tests
class MockArgs(object):
def __init__(self):
self.positional_... | AllEnabled',
'testNoChromeOS',
'testNoMac',
'testNoMavericks',
'testNoSystem',
'testWinOrLinuxOnly',
'testHasTabs']),
self._GetEnabledTests('canary', 'win', 'win7', True))
def testDoesntHaveTabs(self):
| self.assertEquals(
set(['testAllEnabled',
'testNoChromeOS',
'testNoMac',
'testNoMavericks',
'testNoSystem',
'testWinOrLinuxOnly']),
self._GetEnabledTests('canary', 'win', 'win7', False))
def testSkip(self):
args = MockArgs()
ar... |
nick3085/CMTPRG01-5-praktijkopdracht-materialenapp | materialenapp/materialmanager/migrations/0004_auto_20170728_1418.py | Python | mit | 874 | 0.002288 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-07-28 14:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('materialmanager', '0003_remove_delivery_supplier'),
]
... | name='location',
field=models.ForeignKey(null=True | , on_delete=django.db.models.deletion.SET_NULL,
to='materialmanager.Location'),
),
migrations.AddField(
model_name='delivery',
name='supplier',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL,
... |
davemc84/bitcoin-payable-black-scholes | bs.py | Python | mit | 1,318 | 0.002276 | import json
from flask import Flask, request
from two1.lib.wallet import Wallet
from two1.lib.bitserv.flask import Payment
from scipy.stats import norm
from math import *
app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)
@app.route('/bs')
@payment.required(10)
def BlackScholes():
data = {}
... | K*exp(-R*T)*norm.cdf(d2))/365
data['cVega'] = S*sqrt(T)*norm.pdf(d1)/100
data['cRho'] = K*T*exp(-R*T)*norm.cdf(d2)/100
data['pDelta'] = data['cDelta']-1
data['pGamma'] = da | ta['cGamma']
data['pTheta'] = (-(S*V*norm.pdf(d1))/(2*sqrt(T))+R*K*exp(-R*T)*norm.cdf(-d2))/365
data['pVega'] = data['cVega']
data['pRho'] = -K*T*exp(-R*T)*norm.cdf(-d2)/100
return json.dumps(data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
|
CloudBoltSoftware/cloudbolt-forge | blueprints/google_cloud_function/sync.py | Python | apache-2.0 | 2,506 | 0.007183 | """
Discover google cloud functions on google cloud
"""
from common.methods import set_progress
from resourcehandlers.gcp.models import GCPHandler
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import json
... | {
'name': result.get('name').split('/')[-1],
'google_rh_id': handler.id,
'function_name': result.get('name'),
'available_memory_mb': result.get('availableMemoryMb'),... | ount_email': handler.serviceaccount,
'https_trigger': result.get('httpsTrigger').get('url'),
'source_archive_url': result.get('sourceArchiveUrl'),
}
)
return discovered_functions
|
jesopo/bitbot | modules/inactive_channels.py | Python | gpl-2.0 | 2,786 | 0.003948 | import datetime
from src import ModuleManager, utils
PRUNE_TIMEDELTA = datetime.timedelta(weeks=4)
SETTING_NAME = "inactive-prune"
SETTING = utils.IntRangeSetting(0, None, SETTING_NAME,
"Amount of days of inactivity before we leave a channel")
MODE_SETTING_NAME = "inactive-prune-modes"
MODE_SETTING = utils.BoolS... | "0")
| def hourly(self, event):
parts = []
now = utils.datetime.utcnow()
botwide_days = self.bot.get_setting(SETTING_NAME, None)
botwide_mode_setting = self.bot.get_setting(MODE_SETTING_NAME, False)
for server in self.bot.servers.values():
serverwide_days = server.get_se... |
grapesmoker/geogame2 | geogame_core/admin_views/__init__.py | Python | gpl-2.0 | 25 | 0.04 | fro | m admin_views | import * |
cemarchi/biosphere | Src/BioAnalyzer/Managers/GenePrioritization/GlobalDifferentialMessengerRnaSampleManager.py | Python | bsd-3-clause | 2,299 | 0.007829 | from typing import Dict
from yaak import inject
from Src.BioAnalyzer.CrossCutting.DTOs.GenePrioritization.GlobalDifferentialSampleDto import GlobalDifferentialSampleDto
from Src.BioAnalyzer.CrossCutting.Filters.GenePrioritization.FeSingleGlobalDifferentialSample import \
FeSingleGlobalDifferentialSample
from Src.... | """
:param diff_mrna_sample:
:return:
"""
diff_mrna_sample = GlobalDifferentialSampleDto(
values=list(set([v for v in diff_mrna_sample.values if v.element_id > 0])))
fe_diff_mrna = self.get_one(FeSingle | GlobalDifferentialSample(), {'values': 0})
if fe_diff_mrna.result:
self._repository.replace_one(diff_mrna_sample)
else:
self._repository.add_one(diff_mrna_sample)
def get_one(self, fe_diff_mrna: FeSingleGlobalDifferentialSample,
include_or_exclude_fields: D... |
radheygupta/editorialsnow | editorials/admin.py | Python | apache-2.0 | 703 | 0.007112 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django import forms
from .models import Editorials
class EditorialsModelForm(forms.ModelForm):
class Meta:
model = Editorials
fields = '__all__'
widgets = {
'con | tent': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
'subtitle': forms.Textarea(attrs={'cols': 80, 'rows': 3}),
}
class EditorialsAdmin( admin.ModelAdmin ):
form = EditorialsModelForm
list_display = ('title', 'publis | hed_date', 'news_paper')
list_filter = ['published_date']
search_fields = ['title']
admin.site.register(Editorials, EditorialsAdmin)
|
titusfortner/selenium | py/selenium/webdriver/support/wait.py | Python | apache-2.0 | 4,895 | 0.001839 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | od provided with the driver as an argument until the \
return value evaluates to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`, or
``True`` if `method` has ra... | while True:
try:
value = method(self._driver)
if not value:
return value
except InvalidSelectorException as e:
raise e
except self._ignored_exceptions:
return True
time.sleep(self._po... |
innotechsoftware/Quantum-GIS | tests/src/python/test_qgsspatialindex.py | Python | gpl-2.0 | 2,052 | 0.000487 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsSpatialIndex.
.. note:: This program is free software; you can redistribute it and/or modi | fy
it under the terms of the GNU General Public License as published by
the Free S | oftware Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Alexander Bruy'
__date__ = '20/01/2011'
__copyright__ = 'Copyright 2012, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import unittest
fr... |
dayatz/taiga-back | taiga/projects/epics/models.py | Python | agpl-3.0 | 5,936 | 0.003033 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... | s:
self.status = se | lf.project.default_epic_status
super().save(*args, **kwargs)
class RelatedUserStory(WatchedModelMixin, models.Model):
user_story = models.ForeignKey("userstories.UserStory", on_delete=models.CASCADE)
epic = models.ForeignKey("epics.Epic", on_delete=models.CASCADE)
order = models.BigIntegerField(... |
mikaperlin/scripts-configs-etc | templates/py_figs.py | Python | mit | 1,445 | 0.018685 | # dependency
import matplotlib as mp
# set fonts and use latex packages
params = { "font.family" : "serif",
"font.serif" : "Computer Modern",
"text.usetex" : True,
"text.latex.preamble" : r"\usepackage{amsmath}",
"font.size" : font_size }
rcParams.update(params)
# default ... | ","m","y"]
# using scientific notation for plot axes
plt.ticklabel_format(axis = "both", style = "sci", scilimits = (-2,2))
# setting colorbar limits (with pcolormesh) and scientific nota | tion
cb = colorbar()
clim(0,1) # range from 0 to 1
cb.formatter.set_powerlimits((-2, 3))
cb.update_ticks()
|
packagecontrol/st_package_reviewer | st_package_reviewer/check/repo/check_readme.py | Python | mit | 188 | 0 | from . import RepoChecker
class CheckReadme(RepoChecker):
| def check(self):
readme = self.repo. | readme()
if not readme:
self.fail("Missing a README file")
|
sonntagsgesicht/regtest | .aux/venv/lib/python3.9/site-packages/pygments/lexers/stata.py | Python | apache-2.0 | 6,414 | 0.002027 | """
pygments.lexers.stata
~~~~~~~~~~~~~~~~~~~~~
Lexer for Stata
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, default, include, words
from pygments.token import Comment, Keyword, Name... | ch anything else as a character inside the comment
(r'.', Comment.Multiline),
],
'comments-star': [
(r'///.*?\n', Comment.Single,
('#pop', 'comments-triple-slash')),
(r'(^//|(?<=\s)//)(?!/)', Comment.Singl | e,
('#pop', 'comments-double-slash')),
(r'/\*', Comment.Multiline, 'comments-block'),
(r'.(?=\n)', Comment.Single, '#pop'),
(r'.', Comment.Single),
],
'comments-triple-slash': [
(r'\n', Comment.Special, '#pop'),
# A // breaks ou... |
nabsboss/CouchPotatoServer | libs/guessit/__init__.py | Python | gpl-3.0 | 5,753 | 0.00365 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2011 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... |
# Do python3 detection before importing any other module, to be sure that
# it will then always be available
# with code from http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
import sys
if sys.version_info[0] >= 3:
PY3 = True
un | icode_text_type = str
native_text_type = str
base_text_type = str
def u(x):
return str(x)
def s(x):
return x
class UnicodeMixin(object):
__str__ = lambda x: x.__unicode__()
import binascii
def to_hex(x):
return binascii.hexlify(x).decode('utf-8')
else:
PY... |
flomotlik/formica | tests/unit/test_config_file.py | Python | mit | 4,899 | 0.001429 | import pytest
from path import Path
import yaml
from uuid import uuid4
from formica import cli
from tests.unit.constants import (REGION, PROFILE, STACK,
CHANGE_SET_PARAMETERS, CHANGE_SET_STACK_TAGS,
FULL_CONFIG_FILE, CHANGE_SET_CAPABILITIES,
... | m1, "B": 2, 'C': True, 'D': param2}
def test_merges_vars(mocker, tmpdir, session):
stacks = mocker.patch('formica.cli.template')
param1 = str(uuid4())
file_name = 'test.config.yaml'
with Path(tmpdir):
with open(file_name, 'w') as f:
f.write(yaml.dump(FULL_CONFIG_FILE))
with... | -c', file_name])
call_args = stacks.call_args[0][0]
assert call_args.vars['OtherVar'] == param1
def test_exception_with_wrong_config_type(mocker, tmpdir, session, logger):
file_name = 'test.config.yaml'
with Path(tmpdir):
with open(file_name, 'w') as f:
f.write(yaml.dump({'... |
LLNL/spack | var/spack/repos/builtin/packages/py-azure-mgmt-iotcentral/package.py | Python | lgpl-2.1 | 955 | 0.002094 | # 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)
class PyAzureMgmtIotcentral(PythonPackage):
"""Microsoft Azure IoTCentral Management Client Library for Python."""
... | 256='c175f6642be514ad0efd3dc03d09e50d923596fd9e634381793dcc46bb8a57c7')
| version('3.0.0', sha256='f6dacf442ccae2f18f1082e80bcbdcaa8c0efa2ba92b48c5db6ee01d37240047')
depends_on('py-setuptools', type='build')
depends_on('py-msrest@0.5.0:', type=('build', 'run'))
depends_on('py-msrestazure@0.4.32:1', type=('build', 'run'))
depends_on('py-azure-common@1.1:1', type=('build', 'r... |
openstack/oslo.serialization | oslo_serialization/serializer/json_serializer.py | Python | apache-2.0 | 1,376 | 0 | # Copyright 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | ing
def dump(self, obj, fp):
return jsonutils.dump(obj, fp)
def dump_as_bytes(self, ob | j):
return jsonutils.dump_as_bytes(obj, default=self._default,
encoding=self._encoding)
def load(self, fp):
return jsonutils.load(fp, encoding=self._encoding)
def load_from_bytes(self, s):
return jsonutils.loads(s, encoding=self._encoding)
|
andrei-karalionak/ggrc-core | src/service_specs/environment.py | Python | apache-2.0 | 1,401 | 0.015703 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import threading
from ggrc import db
from ggrc.app import app
from ggrc.models import create_db, drop_db
from wsgiref.simple_server import make_server
from ggrc import settings
use_migrations = True
def ... | context.thread.start()
def after_all(context):
context.server.shutdown()
context.thread.join()
db.session.remove()
drop_db(use_migrations)
i | f getattr(settings, 'MEMCACHE_MECHANISM', False) is True:
from google.appengine.api import memcache
from google.appengine.ext import testbed
context.testbed.deactivate()
|
harpesichord/Door-Access | door/exception.py | Python | mit | 679 | 0.005891 | class ShirtsioError(Exception):
def __init__(self, message=None, http_body=None, http_status=None, json_body=None):
super(ShirtsioError, self).__init__(message)
self.http_body = http_body and http_body.decode('utf-8')
self.http | _status = http_status
self.json_body = json_body
class APIError(ShirtsioError):
pass
class APIConnectionError(ShirtsioError):
pass
class InvalidRequestError(ShirtsioError):
def __init__(self, message, http_body=None, http_s | tatus=None, json_body=None):
super(InvalidRequestError, self).__init__(message, http_body, http_status, json_body)
class AuthenticationError(ShirtsioError):
pass |
arky/pootle-dev | pootle/runner.py | Python | gpl-2.0 | 6,998 | 0.000286 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# 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 t... |
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.pootle/pootle.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.sample'
|
def init_settings(settings_filepath, template_filename):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
"""
... |
wxmgcs/devops | alarm/models.py | Python | mit | 987 | 0.008273 | #coding: utf-8
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Log(models.Model):
title = models.CharField(max_length=255, default='', blank=True, null=True, verbose_name=u'标题')
content = models.CharField(max_length=255, default='', blank=True, null=True, ... | o_now=True)
def __unicode__(self):
ret | urn self.peer
class Meta:
default_permissions = () |
erget/tnsmaster | tnsnames/format.py | Python | mit | 101 | 0 | from enum import En | um
__autho | r__ = 'dirkfuchs'
class Format(Enum):
oneLine = 0
oracle = 1
|
EdLogan18/logan-repository | plugin.program.super.favourites/default.py | Python | gpl-2.0 | 93,932 | 0.010263 | #
# | Copyright (C) 2014-
# Sean Poyser (seanpoyser@gmail.com)
#
# This Program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This Progr... | NTABILITY 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 XBMC; see the file COPYING. If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# http://www... |
Steven-Eardley/pibot_motor | Moves.py | Python | mit | 2,279 | 0.002633 | """Some primitive movement definitions"""
import Robot
def go_straight(speed=50, distance=0):
"""
Travel forwards or backwards in a straight line.
:param speed: Speed to travel, as % of maximum
:param distance: Distance to travel, in millimetres. +ve for forwards, -ve for backwards
:return: 0 for ... | mm at {1}% speed".format(distance, speed)
def rotate(speed=50, degrees=0):
"""
Rotate the bot while stationary.
:param degrees: Number of degrees to rotate, +ve for clockwise, -ve for anticlockwise
:return: 0 for success; 1 for failure
"""
r = Robot.get_robot()
print "rotate:\t{0} deg at {1... | s, speed)
def rotate_min(speed=50, heading=0):
"""
Slightly smarter stationary rotate method which chooses its own direction of rotation
:param heading: New heading to point towards (0-360)
:return: 0 for success; 1 for failure
"""
r = Robot.get_robot()
heading = heading % 360
if 180 - ... |
bigswitch/horizon | openstack_dashboard/dashboards/project/stacks/forms.py | Python | apache-2.0 | 18,998 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | raise forms.ValidationError(six.text_type(e))
return cleaned
def clean_uploaded_files(self, prefix, field_label, cleaned, files):
"""Cleans Template & Environment data from form upload.
Does some of the crunchy bits for processing uploads vs raw
data depending on what the... | for environment data & template data.
:type prefix: str
:param prefix: prefix (environment, template) of field
:type field_label: str
:param field_label: translated prefix str for messages
:type input_type: dict
:param prefix: existing cleaned fields from form
:r... |
pagea/unstyle | unstyle/features/characterfeatures.py | Python | mit | 526 | 0 | """Module containing character feature extractors."""
import string
from unstyle.features.featregister import register_feat
@register_feat
def characterSpace(text):
"""Return the total number of characters | ."""
return len(text)
@register_feat
def letterSpace(text):
"""Return the total number of letters (excludes spaces and punctuation)" | ""
count = 0
alphabet = string.ascii_lowercase + string.ascii_uppercase
for char in text:
if char in alphabet:
count += 1
return count
|
wiliamsouza/cars | cars/__init__.py | Python | apache-2.0 | 715 | 0.002797 | import os
| from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.login import LoginManager
UPLOAD_FOLDER = '/srv/cars/cars/data/images'
if 'TRAVIS' in os.environ:
UPLOAD_FOLDER = '{0}/{1}'.format(os.environ['TRAVIS_BUILD_DIR'],
'cars/data/images')
app = Fl... | t_key'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
db = MongoEngine(app)
db.connection.admin.command('setParameter', textSearchEnabled=True)
lm = LoginManager(app)
lm.init_app(app)
lm.login_view = 'login'
from . import controllers
__version__ = '0.1'
|
maxwward/SCOPEBak | askbot/migrations/0076_transplant_followed_by_2.py | Python | gpl-3.0 | 27,054 | 0.008354 | # encoding: 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):
# Removing M2M table for field followed_by on 'Exercise'
db.delete_table('exercise_followed_by')
def... | 'True', 'related_name': "'locked_problems'", 'null': 'True', 'to': "orm['auth.User']"}),
'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'exercise': ('dj | ango.db.models.fields.related.ForeignKey', [], {'related_name': "'problems'", 'to': "orm['askbot.Exercise']"}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'text': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'vote_down_count': ('django.db... |
fitzgen/zoolander | zoolander/colors.py | Python | mit | 1,572 | 0.002545 | """
Zoolander's color handling module.
"""
import operator
class HexMetaClass(type):
OPERATORS = ("add", "sub", "mul", "div")
def __new__(mcs, name, bases, attrs):
cls = type.__new__(mcs, name, bases, attrs)
def overload(op):
"""
Overload this operator with a function ... | stance(other, my_class):
return my_class(hex(op_fn(self.num, other.num)))
elif isinstance(other, int) or isinstance(other, float):
return my_class(hex(op_fn(self.num, other)))
elif isinstance(other, str):
return my_class(hex(sel... | s for %s, '%s' and '%s'" % (
str(op_fn), type(self), type(other)
))
return overloaded_fn
for op in mcs.OPERATORS:
setattr(cls, "__%s__" % op, overload(op))
setattr(cls, "__r%s__" % op, "__%s__" % op)
return cls
class Hex... |
alirizakeles/tendenci | tendenci/apps/navs/utils.py | Python | gpl-3.0 | 866 | 0.008083 | from django.core.cache import cache
from django.conf import settings
from django.template.loader import render_to_string
from tendenci.apps.navs.cache import NAV_PRE_KEY
def cache_nav(nav, show_title=False):
"""
Caches a nav's rendered html code
"""
keys = [settings.CACHE_PRE_ | KEY, NAV_PRE_KEY, str(nav.id)]
key = '.'.join(keys)
value = render_to_string("navs/render_nav.html", {'nav':nav, "show_title": show_title})
cache.set(key, value, 432000) #5 days
return value
def get_nav(id):
"""
Get the nav from | the cache.
"""
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(id)]
key = '.'.join(keys)
nav = cache.get(key)
return nav
def clear_nav_cache(nav):
"""
Clear nav cache
"""
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(nav.id)]
key = '.'.join(keys)
cache.delete(key)
|
Microsoft/PTVS | Python/Product/Pyvot/Pyvot/xl/version.py | Python | apache-2.0 | 704 | 0.005682 | # PyVot
# Copyright(c) Microsoft Corporation
# 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
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LI | MITATION ANY
# IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
# MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
__version__ = "0.1.2" |
goulu/pdfminer | tools/pdfdiff.py | Python | mit | 5,794 | 0 | #!/usr/bin/env python3
"""
compares two pdf files.
"""
import io
import logging
import sys
import pdfminer.settings
from pdfminer import high_level, layout
pdfminer.settings.STRICT = False
logging.basicConfig()
def compare(file1, file2, **kwargs):
# If any LAParams group arguments were passed,
# create a... | mv = kwargs.get(param, None)
if paramv is not None:
laparams[param] = paramv
kwargs['laparams'] = laparams
s1 = io.StringIO()
with open(file1, "rb") as fp:
high_level.extract_text_to_fp(fp, s1, **kwargs)
s2 = io.StringIO()
with open(file2, "rb") as fp:
... |
extension = os.path.splitext(kwargs['outfile'])[1][1:4]
if extension.lower() == 'htm':
return difflib.HtmlDiff().make_file(s1, s2)
except KeyError:
pass
return difflib.unified_diff(s1, s2, n=kwargs['context_lines'])
# main
def main(args=None):
import argparse
P = a... |
sniboboof/data-structures | radixal.py | Python | mit | 1,895 | 0.005277 | def radixsort(mylist):
if mylist == []:
return []
answerdict = {}
for item in mylist:
try:
answerdict[item%10].append(item)
except KeyError:
answerdict[item%10] = [item, ]
i = 1
while len(answerdict.keys()) > 1:
answerdict = radixhelper(answerd... | r
for i in xrange(digit):
exactdigit = exactdigit // 10
exactdigit %= 10
try:
outdict[exactdigit].append(number)
except KeyError:
outdict[exactdigit] = [number, ]
return outdict
def radixsortstring(mylist):
if myli... | ength, len(singlestring))
for i in xrange(maxlength):
answerdict = radixstringhelper(answerdict, maxlength-(i+1))
answerlist=[]
for bucket in answerdict.values():
answerlist.extend(bucket)
return answerlist
def radixstringhelper(indict, index):
shorties = indict.pop('shorties', [])
... |
duncanmmacleod/gwsumm | gwsumm/tabs/misc.py | Python | gpl-3.0 | 3,545 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2013-2016)
#
# This file is part of GWSumm
#
# GWSumm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... | not found')
page = markup.page()
pag | e.div(class_='alert alert-danger')
page.p()
page.strong("The page you are looking for doesn't exist")
page.p.close()
page.p("This could be because the times for which you are looking "
"were never processed (or haven't even happened yet), or "
"because no pa... |
thombashi/subprocrunner | setup.py | Python | mit | 2,928 | 0.000683 | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import os.path
from typing import Dict
import setuptools
MODULE_NAME = "subprocrunner"
REPOSITORY_URL = "https://github.com/thombashi/{:s}".format(MODULE_NAME)
REQUIREMENT_DIR = "requirements"
ENCODING = "utf8"
pkg_info = {} # type: Dict[str,... | ": REPOSITORY_URL, "Tracker": "{:s}/issues".format(REPOSITORY_URL)},
python_requires=">=3.5",
install_requires=install_requires,
extr | as_require={"logging": LOGGING_REQUIRES, "test": tests_requires + LOGGING_REQUIRES},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"License :: OSI Approved :: MIT License",
"Opera... |
eduNEXT/edunext-platform | import_shims/lms/grades/rest_api/v1/__init__.py | Python | agpl-3.0 | 377 | 0.01061 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable | =redefined-builtin,wrong- | import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('grades.rest_api.v1', 'lms.djangoapps.grades.rest_api.v1')
from lms.djangoapps.grades.rest_api.v1 import *
|
kennydude/django-pgviews | django_pgviews/management/commands/clear_pgviews.py | Python | unlicense | 1,195 | 0.000837 | import logging
from django.core.management.base import BaseComm | and
from django.apps import apps
from django.db import connection
from django_pgviews.view import clear_view, View, MaterializedView
log = logging.getLogger('django_pgviews.sync_pgviews')
class Command(BaseCommand):
help = """Cl | ear Postgres views. Use this before running a migration"""
def handle(self, **options):
"""
"""
for view_cls in apps.get_models():
if not (isinstance(view_cls, type) and
issubclass(view_cls, View) and
hasattr(view_cls, 'sql')):
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_MovingAverage_Seasonal_DayOfWeek_MLP.py | Python | bsd-3-clause | 174 | 0.045977 | import tests.model_control.test_ozone_custom_models_ | enabled as testmod
testmod.build_model( ['RelativeDi | fference'] , ['MovingAverage'] , ['Seasonal_DayOfWeek'] , ['MLP'] ); |
mfnch/pyrtist | pyrtist/lib2deep/put.py | Python | lgpl-2.1 | 2,455 | 0.000815 | # Copyright (C) 2017 Matteo Franchin
#
# This file is part of Pyrtist.
# Pyrtist is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 2.1 of the License, or
# (at your option) any late... | the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# | along with Pyrtist. If not, see <http://www.gnu.org/licenses/>.
'''Implementation of Put functionality for DeepWindows.
This module allows passing Put objects to DeepWindow in order to place a
DeepWindow inside another DeepWindow, similarly to what is done for Windows
in the pyrtist.lib2d module.
'''
__all__ = (... |
akhof/PWA | PWA/src/PWA/Response.py | Python | mit | 288 | 0.010417 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Response():
def __init__ | (self, server):
self._server = server
| self.response_code = 200
self.content_type = None
self.content = ""
self.headers = {}
self.cookies = {}
|
portify/io_scene_dts | import_dts.py | Python | mit | 18,549 | 0.002696 | import bpy
import os
from bpy_extras.io_utils import unpack_list
from .DtsShape import DtsShape
from .DtsTypes import *
from .write_report import write_debug_report
from .util import default_materials, resolve_texture, get_rgb_colors, fail, \
ob_location_curves, ob_scale_curves, ob_rotation_curves, ob_rotation_dat... | bmat.diffuse_color = default_materials[dmat.name.lower()]
else: # give it a random color
bmat.diffuse_color = color_source.__next__()
| if dmat.flags & Material.SelfIlluminating:
bmat.use_shadeless = True
if dmat.flags & Material.Translucent:
bmat.use_transparency = True
if dmat.flags & Material.Additive:
bmat.torque_props.blend_mode = "ADDITIVE"
elif dmat.flags & Material.Subtractive:
bmat.torque_props.ble... |
makyo/honeycomb | administration/migrations/0009_auto_20161109_0428.py | Python | mit | 454 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-09 04:28
from __future__ import unicode_literals
fr | om djang | o.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('administration', '0008_auto_20161107_1918'),
]
operations = [
migrations.AlterField(
model_name='ban',
name='end_date',
field=models.DateField(blank=True),
... |
jjagielka/reporter | src/reports/models.py | Python | apache-2.0 | 2,148 | 0.01676 | from django.db import models
from django.db import models
from django.utils.translation import ugettext as _
# from django.core.urlresolvers import reverse_lazy, reverse
from django.conf import settings
from projects.models import Project, Customer
class Report (models.Model):
HIGHLIGHT = 'HL'
LOWLIGHT =... | SER_MODEL, related_name='+', editable=False)
modified = models.DateTimeField (auto_now=True)
modified_by = models.ForeignKey (settings.AUTH_USER_MODEL, related_name='+', edi | table=False)
class Meta:
verbose_name = _('Report')
verbose_name_plural = _('Reports')
ordering = ['light','project','category']
unique_together = ("target", "year", "period")
abstract = True
def __str__(self):
return self.title
#return str(self.project... |
mcecchi/SuperOcto | RoboLCD/RoboLCD/lcd/z_offset_wizard.py | Python | agpl-3.0 | 12,560 | 0.008758 | from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.logger import Logger
from kivy.properties import ObjectProperty, S... | , title=title, back_destin | ation=back_destination, content=layout)
Logger.info("2nd Screen: RENDERED")
def check_temp_and_change_screen(self):
temps = roboprinter.printer_instance._printer.get_current_temperatures()
#find the temperature
if 'tool0' in temps:
extruder_one_temp = temps['tool0']['ac... |
LordSputnik/python-mbio | mbio/entities/entity.py | Python | mit | 235 | 0.008511 |
class Entity(object):
RELEASE, REC | ORDING = range(0,2)
def __init__(self, *args, **kwargs):
pass
def json(self):
raise NotImplementedError
def parse_json(self, jso | n):
raise NotImplementedError
|
Azure/azure-sdk-for-python | sdk/core/azure-core/tests/async_tests/test_base_polling_async.py | Python | mit | 30,931 | 0.004106 | #--------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), t... | esponse_type = None
async def mock_run(client_self, request, **kwargs):
return TestBasePolling.mock_update(client_self.http_request_type, client_self.http_response_type, request.url)
CLIENT._pipeline.run = types.MethodType(mock_run, CLIENT)
@pytest.fixture
def client():
# The poller itself don't use it, so we... | c_pipeline_client_builder():
"""Build a client that use the "send" callback as final transport layer
send will receive "request" and kwargs as any transport layer
"""
def create_client(send_cb):
class TestHttpTransport(AsyncHttpTransport):
async def open(self): pass
asyn... |
mysql/mysql-utilities | mysql-test/suite/replication/t/export_rpl_errors.py | Python | gpl-2.0 | 7,565 | 0 | #
# Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
#
# 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 th... | master "
res = mutlib.System_test.run_test_case(self, 0, cmd_str + option,
comment)
| if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = "Test case {0} - error: --rpl-user missing user".format(
test_num)
option = " --rpl=master --rpl-user=missing "
res = mutlib.System_test.run_test_case(self, 1, cmd_str + option,... |
pankshok/xoinvader | xoinvader/animation.py | Python | mit | 8,490 | 0.000236 | """Animation.
Animation is set of keyframes.
Value of selected attribute changes in time.
Keyframe:
(time, value)
Objects have animation manager which manages animation graph and switching."""
from operator import itemgetter
from eaf import Timer
from xoinvader.utils import Point
class AnimationBoundariesExce... | rent += 1
def _check_animation_state(self):
"""Check animation state and restart if needed.
:raise StopIteration: when animation exceeded frames.
"""
if le | n(self._keyframes) == self._current:
if self._loop:
self._current = 0
self._timer.restart()
else:
self._timer.stop()
raise StopIteration
def linear_equation(val1, val2, time1, time2, current_time):
"""Linear equation to get in... |
stasm/app-validator | tests/js/test_features.py | Python | bsd-3-clause | 4,061 | 0 | from functools import wraps
from nose.tools import eq_
from js_helper import TestCase
def uses_feature(name):
def wrap(func):
@wraps(func)
def inner(self, *args, **kw):
func(self, *args, **kw)
self.assert_has_feature(name)
return inner
return wrap
class Feat... | s(FeatureTester):
"""Tests for feature APIs in the navigator.* object."""
TESTS = [
("APPS", "navigator.mozApps.install('foo/bar.webapp');"),
("APPS", "navigator.apps.install('foo/bar.webapp');"),
("PACKAGED_APPS", "navigator.apps.installPackage('foo/bar.webapp');"),
("PAY", "na... | zContacts.foo();"),
("DEVICE_STORAGE", "navigator.getDeviceStorage();"),
("GEOLOCATION", "navigator.getCurrentPosition();"),
("IDLE", "navigator.addIdleObserver();"),
("NETWORK_INFO", "navigator.connection.foo();"),
("NETWORK_STATS", "navigator.networkStats.foo();"),
("PU... |
Teekuningas/mne-python | examples/visualization/plot_montage.py | Python | bsd-3-clause | 2,108 | 0 | # -*- coding: utf-8 -*-
"""
.. _plot_montage:
Plotting sensor layouts of EEG systems
======================================
This example illustrates how to l | oad all the EEG system montages
shipped in MNE-python, and display it on fsaverage template.
""" # noqa: D205, D400
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Joan Massich <mailsik@gmail.com>
#
# License: BSD Style.
import os.path as op
im | port mne
from mne.channels.montage import get_builtin_montages
from mne.datasets import fetch_fsaverage
from mne.viz import set_3d_title, set_3d_view
###############################################################################
# Check all montages against a sphere
for current_montage in get_builtin_montages():
... |
eestay/edx-platform | lms/djangoapps/verify_student/models.py | Python | agpl-3.0 | 36,885 | 0.002305 | # -*- coding: utf-8 -*-
"""
Models for Student Identity Verification
This is where we put any models relating to establishing the real-life identity
of a student over a period of time. Right now, the only models are the abstract
`PhotoVerification`, and its one concrete implementation
`SoftwareSecurePhotoVerification`... | ### Fields Set During Approval/Denial #####################
# If the review was done by | an internal staff member, mark who it was.
reviewing_user = models.ForeignKey(
User,
db_index=True,
default=None,
null=True,
related_name="photo_verifications_reviewed"
)
# Mark the name of the service used to evaluate this attempt (e.g
# Software Secure).
re... |
catapult-project/catapult | common/py_utils/py_utils/camel_case_unittest.py | Python | bsd-3-clause | 1,740 | 0.002299 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import ab | solute_import
import unittest
from py_utils import camel_case
class CamelCase | Test(unittest.TestCase):
def testString(self):
self.assertEqual(camel_case.ToUnderscore('camelCase'), 'camel_case')
self.assertEqual(camel_case.ToUnderscore('CamelCase'), 'camel_case')
self.assertEqual(camel_case.ToUnderscore('Camel2Case'), 'camel2_case')
self.assertEqual(camel_case.ToUnderscore('Cam... |
ampyche/ampyche | amp-cgi-bin/getters/getallplaylists.py | Python | mit | 1,063 | 0.031985 | #!/usr/bin/python3
import cgi
import json
import sqlite3 as lite
class GetAllPlaylist():
def __init__(self):
db_loc = "/usr/share/ampyche/db/ampychePlaylist.db"
self.db_loc = db_loc
ppll = ''
self.ppll = ppll
ppllpp = ''
self.ppllpp = ppllpp
def _make_a_list(self, genlist):
agen = []
for gen in gen... | ts")
plists = cur.fetchall()
con.close()
#plists = self._make_a_ | list(plists)
# for p in plists:
# ppllone = "<li class='playlistLi'><a href='#' class='plplay ui-btn ui-mini ui-icon-bullets ui-btn-icon-right'><h3>"
# ppllthree = "%s</h3></a></li>" %p
# self.ppll = self.ppll + ppllone + ppllthree
# bazooka = self.ppll + "</ul>"
# return bazooka
return plists
print("Cont... |
sniemi/SamPy | sandbox/src1/examples/ftface_props.py | Python | bsd-2-clause | 3,413 | 0.008204 | #!/usr/bin/env python
"""
This is a demo script to show you how to use all the properties of an
FT2Font object. These describe global font properties. For
individual character metrices, use the Glyp object, as returned by
load_char
"""
import matplotlib
from matplotlib.ft2font import FT2Font
#fname = '/usr/local/sha... | :', font.ascender
# the descender in 26.6 units
print 'Descender :', font.descender
# the height in 26.6 units
print 'Height :', font.height
# maximum horizontal cursor advance
print 'Max adv width :', font.max_advance_width
# same for vertical layout
pri... | ax_advance_height
# vertical position of the underline bar
print 'Underline pos :', font.underline_position
# vertical thickness of the underline
print 'Underline thickness :', font.underline_thickness
print 'Italics :', font.style_flags & FT_STYLE_FLAG_ITALIC != 0
print 'Bold ... |
fanout/django-eventstream | django_eventstream/storage.py | Python | mit | 2,978 | 0.031229 | import sys
import json
import datetime
from django.utils import timezone
from django.core.serializers.json import DjangoJSONEncoder
from .event import Event
is_python3 = sys.version_info >= (3,)
# minutes before purging an event from the database
EVENT_TIMEOUT = 60 * 24
# attempt to trim this many events per pass
EV... | id:
raise EventDoesNotExist(
'No such event %d' % last_id,
cur_id)
# exclude the first result
db_events = db_events[1:]
out = []
for db_event in db_events:
e = Event(
db_event.channel,
db_event.type,
json.loads(db_event.data),
id=db_event.eid)
out.append(e)
return out
def... | ounter.objects.get(name=channel)
return ec.value
except models.EventCounter.DoesNotExist:
return 0
def trim_event_log(self):
from . import models
now = timezone.now()
cutoff = now - datetime.timedelta(minutes=EVENT_TIMEOUT)
while True:
events = models.Event.objects.filter(
created__lt=cutoff
... |
googleapis/python-aiplatform | samples/model-builder/create_training_pipeline_custom_job_sample.py | Python | apache-2.0 | 2,513 | 0.000398 | # Copyright 2021 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | g_pipeline_custom_job_sample]
def create_training_pipeline_custom_job_sample(
project: str,
location: str,
staging_bucket: str,
display_name: str,
script_path: str,
container_uri: str,
model_serving_container_image_uri: str,
dataset_id: Optional[str] = None,
mode | l_display_name: Optional[str] = None,
args: Optional[List[Union[str, float, int]]] = None,
replica_count: int = 0,
machine_type: str = "n1-standard-4",
accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED",
accelerator_count: int = 0,
training_fraction_split: float = 0.8,
validation_fractio... |
jhl667/galaxy_tools | tools/bwa/bwa_mem.py | Python | apache-2.0 | 12,929 | 0.022355 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #rlk moved this line to fall after the #! line
## yufei.luo@gustave.roussy 22/07/2013
## Copyright © 2014 CRS4 Srl. http://www.crs4.it/
## Modified by:
## Nicola Soranzo <nicola.soranzo@crs4.it>
"""
Runs BWA on single-end or paired-end data.
Produces a SAM file containing... | tmp_stderr.close()
if returncode != 0:
raise Exception, stderr
except Exception, e:
# clean up temp dirs
if os.path.exists( tmp_index_dir ):
s | hutil.rmtree( tmp_index_dir )
if os.path.exists( tmp_dir ):
shutil.rmtree( tmp_dir )
raise Exception, 'Error indexing reference sequence. ' + str( e )
else:
ref_file_name = options.ref
# if options.illumina13qual:
# illumina_quals = "-I"
# else:
# ... |
qsnake/h5py | h5py/tests/test_dataset.py | Python | bsd-3-clause | 1,798 | 0.013904 |
"""
Test basic behavior of h5py.highlevel.Dataset, not including slicing
or keyword arguments
"""
import numpy as np
import h5py
import unittest
from common import TestCasePlus, INTS, FLOATS, COMPLEX, STRINGS, res
class TestDataset(TestCasePlus):
def setUp(self):
self.f = h5py.File(res.get_nam... | ):
# Test dataset creation from shape and type, or raw data
types = INTS + FLOATS + COMPLEX + STRINGS + ('b',)
shapes = ( (), (1,), (10,), (20,1,15), (7,200,1) )
for s in shapes:
srcdata = np.arange(np.product(s)).reshape(s)
for t in types:
msg ... | test %s %s" % (s, t)
data = srcdata.astype(t)
dset = self.make_dset(s, t)
dset[...] = data
assert np.all(dset[...] == data), "%r %r" % (dset[...], data)
dset = self.make_dset(data=data)
assert np.all(dset[...] == data)... |
latticelabs/Mitty | mitty/tests/benchmarking/creed_test.py | Python | gpl-2.0 | 5,564 | 0.015636 | from nose.tools import assert_raises
import mitty.benchmarking.creed as creed
class MyRead:
def __init__(self, qname, secondary, paired, read1, unmapped, reference_id, pos, cigarstring):
self.qname, self.is_secondary, self.is_paired, self.is_read1 = qname, secondary, paired, read1
self.is_unmapped, self.re... | ((195, 200, 195, 200),
# (215, 225, 230, 240),
# (230, 235, 230, 235))], # Copy 0 ...
# [ # Copy 1
# ((15, 30, 15, 30),
# (40, 50, 40, 50)),
# ((55, 65, 55, 65),
# (75, 80, 75, 80)),
# ((85, 95, 85, 95),
# (105, 115, 105, 115)),
# ((152, 158, 152, 158),... | (172, 178, 172, 178))] # Copy 1
# ]
#
# import pysam
# bam_fp = pysam.AlignmentFile(per_bam_fname, 'wb')
# for r_pos in read_positions:
# r = pysam.AlignedSegment()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.