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 |
|---|---|---|---|---|---|---|---|---|
thormuller/yescoin2 | contrib/testgen/base58.py | Python | mit | 2,818 | 0.007452 | '''
Yescoin base58 encoding and decoding.
Based on https://yescointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return byte... | e long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value | ] + result
# Yescoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == '\0': nPad += 1
else: break
return (__b58chars[0]*nPad) + result
def b58decode(v, length = None):
""" decode v into a string of len bytes
... |
Clear-ICT/odoo-addons | sale_tax_number_check/__openerp__.py | Python | agpl-3.0 | 1,340 | 0 | # -*- coding: utf-8 -*-
#
#
# Copyright (C) 2015 Sucros Clear Information Technologies PLC.
# All Rights Reserved.
#
# This program is free software: you can redistri | bute it and/or modify it
# under the terms of the GNU Affero General Public | License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICU... |
quantumlib/Cirq | cirq-core/cirq/interop/quirk/cells/input_cells.py | Python | apache-2.0 | 2,927 | 0.00205 | # Copyright 2019 The Cirq Developers
#
# 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 ... |
def generate_all_input_cell_makers() -> Iterator[CellMaker]:
# Quantum inputs.
yield from _input_family("inputA", "a")
yield from _input_family("inputB", "b")
yield from _input_family("inputR", "r")
yield from _input_family("revinputA", "a", rev=True)
yield from _input_family("revinputB", "b",... | rgs: SetDefaultInputCell('a', args.value))
yield CellMaker("setB", 2, lambda args: SetDefaultInputCell('b', args.value))
yield CellMaker("setR", 2, lambda args: SetDefaultInputCell('r', args.value))
def _input_family(identifier_prefix: str, letter: str, rev: bool = False) -> Iterator[CellMaker]:
for n in ... |
AdamISZ/joinmarket_core | setup.py | Python | gpl-3.0 | 394 | 0.010152 | from setuptools import setup
setup(name='joinmarket_core',
version='0.1',
description='J | oinmarket library for Bitcoin coinjoins',
url='http://github.com/Joinma | rket-Org/joinmarket',
#author='Flying Circus',
#author_email='flyingcircus@example.com',
license='GPL',
packages=['joinmarket_core'],
install_requires=['libnacl',],
zip_safe=False) |
WillSkywalker/Radha | Radha/models.py | Python | apache-2.0 | 2,002 | 0.004505 | from sqlalchemy import MetaData, Column, Integer, String, Unicode, Text, UnicodeText, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.inspection import inspect
metadata = MetaData()
Base = declarative_base(metadata=metadata)
cla | ss EroticArticle(Base):
__tablename__ = 'eroticarticle'
id = Column(Integer, primary_key=True)
viewcount = Column(Integer)
title = Column(String(128), index=True)
chinese_title = Column(Unicode(64))
content = relationship('Paragraph', backref='eroticarticle', lazy='dynamic') # Column(Text())
... | = Column(String(128))
def get_content(self, rel):
return [(para.para_idx, para.content) for para in getattr(self, rel)]
def to_dict(self):
cols = {col.name: getattr(self, col.name) for col in self.__table__.columns}
cols['tags'] = list(map(lambda x: x.strip(), self.tags.split('\xa0– ')... |
tzpBingo/github-trending | codespace/python/tencentcloud/tia/v20180226/tia_client.py | Python | mit | 13,462 | 0.002225 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | se = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeModelResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = ... | Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudS... |
NetApp/manila | manila/share/drivers/nexenta/ns5/nexenta_nas.py | Python | apache-2.0 | 17,739 | 0 | # Copyright 2016 Nexenta Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | Initializing Nexenta driver.')
super(NexentaNasDriver, self).__init__(False, *args, **kwargs)
self.configuration = kwargs.get('configuration')
if self.configuration:
self.configuration.append_config_values(
options.nexenta_connection_opts)
self.confi... | fig_values(
options.nexenta_dataset_opts)
else:
raise exception.BadConfigurationException(
reason=_('Nexenta configuration missing.'))
self.nef = None
self.nef_protocol = self.configuration.nexenta_rest_protocol
self.nef_host = self.co... |
ii0/python-goose | tests/parsers.py | Python | apache-2.0 | 10,416 | 0.002016 | # -*- coding: utf-8 -*-
"""\
This is a python port of "Goose" orignialy licensed to Gravity.com
under one or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.
Python port was written by Xavier Grangier for Recrutae
Gravity.co... | ems_result = self.parser.css_select(doc, "p > a")
self.assertEqual(len(items_result), 1)
def test_childNodesWithText(self):
html = '<html><body>'
html += '<p>this is a test <a class="link">link</a> and this is <strong class="link">strong</strong></p> | '
html += '<p>this is a test and this is <strong class="link">strong</strong></p>'
html += '</body></html>'
doc = self.parser.fromstring(html)
p = self.parser.getElementsByTag(doc, tag='p')[0]
def test_replacetag(self):
html = self.get_html('parser/test1.html')
doc =... |
yangming85/lettuce | lettuce/django/apps.py | Python | gpl-3.0 | 2,947 | 0.001018 | # -*- 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... | install | ed apps that are not from django.contrib
returns a list of tuples with (path_to_app, app_module)
"""
apps = get_apps()
if isinstance(only_the_apps, tuple) and any(only_the_apps):
def _filter_only_specified(module):
return module.__name__ in only_the_apps
apps = filter(_fil... |
a301-teaching/a301_code | notebooks/python/shapefiles.py | Python | mit | 3,397 | 0.017368 |
# coding: utf-8
# ## Reading and writing shapefiles
#
# Recall the [qgis lesson 1 tutorial](https://github.com/a301-teaching/a301_code/blob/master/notebooks/qgis/qgis_lesson_1.ipynb)
#
# In that lesson, you used qgis to plot volcanoe data that was stored as
# [shapefiles](https://en.wikipedia.org/wiki/Shapefile)
# ... | e.fromtimestamp(item,timezone.utc) for item in cloudsat_times]
# ### Define a simple schema (the only info is location and point num)
# In[7]:
schema = { 'geometry': 'Point','properties':{'num':'int' }}
#
# copy the projection from the tif file so we put the groundtrack
# in the same coordinates
driver='ESRI Shapef... | sterio.open(tiff_file,'r')
crs = raster.crs.to_dict()
proj = pyproj.Proj(crs)
with fiona.open("ground_track", "w", driver=driver,
schema=schema,crs=crs,encoding='utf-8') as output:
for index,lon_lat in enumerate(zip(cloudsat_lons,cloudsat_lats)):
lon,lat=lon_lat
x,y=proj(lon,lat)
... |
dymkowsk/mantid | scripts/test/AbinsCalculateDWSingleCrystalTest.py | Python | gpl-3.0 | 2,485 | 0.004024 | from __future__ import (absolute_import, division, print_function)
import unittest
from mantid.simpleapi import *
import numpy as np
import json
from AbinsModules import CalculateDWSingleCrystal, LoadCASTEP, AbinsTestHelpers
class AbinsCalculateDWSingleCrystalTest(unittest.TestCase):
temperature = 10 # 10 K
... | calculation of DW
good_data = self._get_good_data(filename=name)
good_tester = CalculateDWSingleCrystal(temperature=self.temperature, abins_data=good_data["DFT"])
calculated_data = good_tester.calculate_data()
# check if evaluated DW are correct
self.as | sertEqual(True, np.allclose(good_data["DW"], calculated_data.extract()))
def _get_good_data(self, filename=None):
castep_reader = LoadCASTEP(input_dft_filename=AbinsTestHelpers.find_file(filename=filename + ".phonon"))
dw = self._prepare_data(filename=AbinsTestHelpers.find_file(filename=filename +... |
ArtemBernatskyy/FundExpert.NET | mutual_funds/settings.py | Python | gpl-3.0 | 6,336 | 0.001106 | """
Django settings for mutual_funds project.
Generated by 'django-admin startproject' using Django 1.9.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import ... |
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTION | S': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
... |
cdondrup/PyBayes | support/dist.py | Python | gpl-2.0 | 4,637 | 0.003019 | # Copyright (c) 2011 Matej Laitl <matej@laitl.cz>
# Distributed under the terms of the GNU General Public License v2 or any
# later version of the license, at your option.
"""
An extension to distutils' Distribution to handle Python/Cython build of PyBayes
"""
try:
# 3.x
from distutils.command.build_py import... | s(self):
self.cmdclass['build'] = build
self.cmdclass['build_ext'] = self.build_ext
# .pyc files just litter site-packages in Cython build
install = self.get_command_obj('install')
install.compile = 0
install.optimise = 0
def _find_cython(self):
"""Returns t... | Cython in found on system, false otherwise.
If true is returned, also sets some variables useful for Cython build
"""
# autodetect (or check for) cython
try:
from Cython.Distutils import build_ext
from Cython.Distutils.extension import Extension
except Im... |
rhizolab/rhizo | tests_with_server/stress-testing/each_controller.py | Python | mit | 401 | 0 | import os
import gevent
from rh | izo.main import c
path_on_server = c.path_on_server()
name = path_on_server.rsplit('/', 1)[1]
print(name, os.getcwd(), path_on_server)
# loop forever sending messages
message_index = 0
while True:
message = 'msg-%s-%d' % (name, message_index)
print('%s: send: %s' % (name, message))
c.send_message(messag... | += 1
|
DarthMaulware/EquationGroupLeaks | Leak #1 - Equation Group Cyber Weapons Auction - Invitation/EQGRP-Free-File/Firewall/EXPLOITS/ELCO/fosho/requests/hooks.py | Python | unlicense | 898 | 0.001114 | # -*- coding: utf-8 -*-
| """
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``args``:
A dictionary of the arguments being sent to Request().
``pre_request | ``:
The Request object, directly before being sent.
``post_request``:
The Request object, directly after being sent.
``response``:
The response generated from a Request.
"""
import traceback
HOOKS = ('args', 'pre_request', 'post_request', 'response')
def dispatch_hook(key, hooks, hook_data):
'''... |
karan/py-lkd.to | setup.py | Python | mit | 1,225 | 0 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='lkd',
version='2',
packages=['lkd', 'tests'],
author='Karan Goel',
author_email='karan@goel.im',
maintainer='Karan Goel',
maintainer_email='karan@goel.im',
url='http://www.goel.im... | ense',
long_description='Python wrapper for lkd.to API.',
classifiers=[
'Development Status :: 4 - Be | ta',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
... |
frostyfrog/mark2 | mk2/events/player.py | Python | mit | 952 | 0.011555 | from . import Event
class PlayerEvent(Event):
def setup(s):
s.username = s.username.encode('ascii')
#Raised in manager
class PlayerJoin(PlayerEvent):
username = Event.Arg(required=True)
ip | = Event.Arg(required=True)
class PlayerQuit(PlayerEvent):
username = Event.Arg(required=True)
reason = Event.Arg(required=True)
class PlayerChat(PlayerEvent):
username = Event.Arg(required=True)
message = Event.Arg(required=True)
class PlayerDeath(PlayerEvent):
text = Event.Arg()
... | g(required=True)
cause = Event.Arg(required=True)
killer = Event.Arg()
weapon = Event.Arg()
format = Event.Arg(default="{username} died")
def get_text(self, **kw):
d = dict(((k, getattr(self, k)) for k in ('username', 'killer', 'weapon')))
d.update(kw)
return self.f... |
deka108/meas_deka | assessment/utilities/answer_transformer.py | Python | apache-2.0 | 1,384 | 0 | """
# Name: check_answer_api/utilities/answer_transformer.py
# Description:
# Created by: Unknown
# Date Created: ---
# Last Modified: Dec 2, 2016
# Modified by: Martinus Alexander
"""
import re
import pattern_dictionary_all
import pattern_dictionary_standardize_mathquill
""" |
Helper method to make sure that the process is recursive.
"""
def replace_recurs | ive(pattern, repl, expression):
count = 1
expr = expression[:]
while count != 0:
expr, count = re.subn(pattern, repl, expr)
return expr
"""
Transform expression in Latex format into ASCII (Sympy) format.
Approach: Recursive transformation using regular expression.
"""
def transform_latex_to_... |
TigerND/dtx-core | src/utils/snippets/sorted_collection.py | Python | mit | 11,282 | 0.001684 | from bisect import bisect_left, bisect_right
class SortedCollection(object):
'''Sequence sorted by a key function.
SortedCollection() is much easier to work with than using bisect() directly.
It supports key functions like those use in sorted(), min(), and max().
The result of the key function call is... | return iter(self._items)
def __reversed__(self):
return reversed(sel | f._items)
def __repr__(self):
return '%s(%r, key=%s)' % (
self.__class__.__name__,
self._items,
getattr(self._given_key, '__name__', repr(self._given_key))
)
def __reduce__(self):
return self.__class__, (self._items, self._given_key)
def __conta... |
tanghaibao/goatools | tests/test_propagate_counts_w_relationships.py | Python | bsd-2-clause | 3,155 | 0.006022 | #!/usr/bin/env python
"""Test propagate_counts up relationships as well as parent-child links."""
import sys
import os
# from itertools import combinations
# import collections as cx
from goatools.go_enrichment import GOEnrichmentStudy
from goatools.base import get_godag
from goatools.test_data.genes_NCBI_10090_Prote... | ormat(N=len(results_r0)))
prt.write('{N} results with r1\n'.format(N=len(results_r1)))
prt.write('{N} results with all regulates\n'.format(N=len(results_rr)))
prt.write('{N} results with part_of\n'.format(N=len(results_rp)))
assert len(results_r1) > len(results_rr)
assert len(results_rr) > len(resul... | p)
assert len(results_rp) > len(results_r0)
# TBD: Add warning message that relationships are ignored
# Check that relationships are ignored in propagate counts if they were not loaded
_get_results(godag_r0, propagate_counts=True, relationships=False, prt=prt)
## results_r0b = _get_results(godag_r0... |
MrMjolnir/python-projects | sportscalendar/sportscalendar/spiders/livetrail.py | Python | apache-2.0 | 1,631 | 0.003679 | import scrapy
from sportscalendar.items import scItem
# Suiza 4:
# datasport
# http://www.kikourou.net/resultats/
# https://livetrail.net/
# http://statistik.d-u-v.org/calendar.php
# hago carreraspopulares?
class DsSpider(scrapy.Spider):
name = "ds"
allowed_domains = ["livetrail.net"]
start_urls = {
... | mbre'] = carrera.xpath('td[2]/a/text()').extract()[0]
tipo = carrera.xpath('td[3]/text()').extract()[0]
item['surl'] = tipo + " " + carrera.xpath('td[7]/a/img/@title').extract()[0]
item['sitio'] = carrera.xpath('td[15]/a/@href').re(r"q=(.*)")[0]
item['fecha'] = carrera.... | item
# def parse_carreras(self, response):
# for carrera_title in response.css('div.entries > ul > li a::text').extract():
# yield {
# 'fecha': response.xpath('//tr[re:test(@class, "odd|even")]//span/text()').extract(),
# 'tipo': response.xpath('//tr[re:test(@class, "odd|even")]//... |
audreyr/opencomparison | apiv1/models.py | Python | mit | 14 | 0 | # boil | erplate
| |
BornToDebug/homeStruction | website/imageGeneration.py | Python | apache-2.0 | 1,352 | 0.005917 | import django
import os
from django.utils import timezone
# Initial setup required
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "homeStruction.settings")
django.setup()
from project.models import Temperature, Light, Humidity
import matplotlib
matplo | tlib.use("Agg")
from matplotlib.dates import DateFormatter
from matplotlib import pyplot as plt
def generateImage(Model, ytext):
plt.figure(figsize=(8.00, 6.00), dpi=100)
modelArray = Model.objects.order_by('-time_recorded').\
filter(time_reco | rded__gte=timezone.now() - timezone.timedelta(days=1))
print modelArray
dateArray = []
valueArray = []
for item in modelArray:
dateArray.append(item.time_recorded)
if Model is Light:
valueArray.append(item.value/10)
else:
valueArray.append(item.value)
... |
SivagnanamCiena/coding-skills-sample-code | coding204-reading-a-file/read-file-one-line.py | Python | apache-2.0 | 1,784 | 0.006726 | # Read from a file one line at a time.
# amwhaley@cisco.com
# twitter: @mandywhaley
# http://developer.cisco.com
# http://learninglabs.cisco.com
# Jan 15, 2015
# * THIS SAMPLE APPLICATION AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
# * OF ANY KIND BY CISCO, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMIT... | O WARRANT THAT THE SOFTWARE IS ERROR FREE OR THAT CUSTOMER WILL BE ABLE
# * TO OPERATE THE SOFTWARE WITHOUT PROBLEMS OR INTERRUPTIONS. NOR DOES CISCO
# * WARRANT THAT THE SOFTWARE OR ANY EQUIPMENT ON WHICH THE SOFTWARE IS USED WILL
# * BE FREE OF VULNERABILITY TO INTRUSION OR ATTACK. THIS SAMPLE APPLICATION IS
# * NO | T SUPPORTED BY CISCO IN ANY MANNER. CISCO DOES NOT ASSUME ANY LIABILITY
# * ARISING FROM THE USE OF THE APPLICATION. FURTHERMORE, IN NO EVENT SHALL CISCO
# * OR ITS SUPPLIERS BE LIABLE FOR ANY INCIDENTAL OR CONSEQUENTIAL DAMAGES, LOST
# * PROFITS, OR LOST DATA, OR ANY OTHER INDIRECT DAMAGES EVEN IF CISCO OR ITS
# * SUP... |
m42e/tvnamer | tests/test_parsing.py | Python | unlicense | 5,676 | 0.007576 | #!/usr/bin/env python
"""Test tvnamer's filename parser
"""
from helpers import assertEquals
from tvnamer.utils import (FileParser, DatedEpisodeInfo, NoSeasonEpisodeInfo)
from test_files import files
def test_autogen_names():
"""Tests set of standard filename formats with various data
"""
"""Mostly b... | '])
# Only EpisodeInfo has seasonnumber
if not isinstance(p, (DatedEpisodeInfo, NoSeasonEpisodeInfo)):
assertEqu | als(p.seasonnumber, name_data['seasno'])
#end cur_test
cur_test.description = cdata['description']
yield cur_test
def check_case(curtest):
"""Runs test case, used by test_parsing_generator
"""
parser = FileParser(curtest['input'])
theep = parser.parse()
if theep.seriesnam... |
GregorCH/ipet | ipet/concepts/Editable.py | Python | mit | 3,432 | 0.007576 | """
Created on 26.12.2013
@author: bzfhende
"""
import collections
class Editable:
"""
an editable object defines a set of attributes to be editable after construction
"""
editabletypes = [float, str, int, bool]
def getEditableAttributes(self):
"""
return a list of attributes which ... | butesToStringDict() == other.attributesToStringDict()
class EditableAttributeError(Exception):
"""
class to represent an error if this editable were to be used now for an evaluation
"""
DEFAULT_MESSAGE = "Attribute {0} is set incorrectly"
def __init__(self, attr, message=None):
"""
... | attr : the name of the attribute that failed
message : (optional) message to understand the reason of this error, otherwise, a template {0} is used
""".format(EditableAttributeError.DEFAULT_MESSAGE)
if type(attr) is not str:
raise TypeError("Passed argument 'attr' must be of typ... |
bigswitch/nova | nova/conf/mks.py | Python | apache-2.0 | 1,253 | 0.001596 | # Copyright 2016 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | ns')
mks_opts = [
cfg.StrOpt('mksproxy_base_url',
default='http://127.0.0.1:6090/',
help='Location of MKS web console proxy, in the form '
'"http://127.0.0.1:6090/"'),
cfg.BoolOpt('enabled',
default=False,
help='Enable MKS relate... | ]
ALL_MKS_OPTS = mks_opts
def register_opts(conf):
conf.register_group(mks_group)
conf.register_opts(ALL_MKS_OPTS, group = mks_group)
def list_opts():
return {mks_group: ALL_MKS_OPTS}
|
davidxmoody/kata | project-euler/completed/euler45.py | Python | mit | 486 | 0.012346 | from itertools import count
def gen_triangle():
for n in count(1):
yield int(n*(n+1)/2)
def gen_pentagonal():
for n in count(1):
yield int(n*(3*n-1)/2)
def gen_hexagonal():
for n in count(1):
yield n*(2*n-1)
gens = gen_triangle(), gen_pentagonal(), gen_hexagonal()
a, b, c = [(gen... | 1]), b, c), key=(lam | bda x: x[0]))
|
caesar2164/edx-platform | openedx/core/djangoapps/external_auth/tests/test_openid_provider.py | Python | agpl-3.0 | 21,198 | 0.002455 | #-*- encoding=utf-8 -*-
'''
Created on Jan 18, 2013
@author: brian
'''
import openid
from openid.fetchers import HTTPFetcher, HTTPResponse
from urlparse import parse_qs, urlparse
from django.conf import settings
from django.test import TestCase, LiveServerTestCase
from django.core.cache import cache
from django.test.... | ed as an openid provider.
provider_url = reverse('openid-provider-login')
factory = RequestFactory()
request = factory.request()
abs_provider_url = request.build_absolute_uri(location=provider_url)
# In order for this absolute URL to work (i.e. to | get xrds, then authentication)
# in the test environment, we either need a live server that works with the default
# fetcher (i.e. urlopen2), or a test server that is reached through a custom fetcher.
# Here we do the latter:
fetcher = MyFetcher(self.client)
openid.fetchers.setDe... |
sroehl/python_homeautomation | python_homeautomation/web/run.py | Python | mit | 134 | 0 | from p | ython_homeautomation.web.Home_Auto import app
def run_webserver( | ):
app.run(host='0.0.0.0', port=9000, use_reloader=False)
|
dantebarba/docker-media-server | plex/Sub-Zero.bundle/Contents/Libraries/Shared/subliminal_patch/subtitle.py | Python | gpl-3.0 | 17,123 | 0.002862 | # coding=utf-8
import logging
import traceback
import re
import types
import chardet
import pysrt
import pysubs2
from bs4 import UnicodeDammit
from pysubs2 import SSAStyle
from pysubs2.subrip import parse_tags, MAX_REPRESENTABLE_TIME
from pysubs2.time import ms_to_times
from subzero.modification import SubtitleModi... | d encoding %s', encoding)
| self._guessed_encoding = encoding
return encoding
logger.warning('Could not guess encoding from language')
# fallback on chardet
encoding = chardet.detect(self.content)['encoding']
logger.info('Chardet found encoding %s', encoding)
if not encoding:... |
wevote/WeVoteServer | twitter/functions.py | Python | mit | 6,256 | 0.002078 | # twitter/functions.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import tweepy
import wevote_functions.admin
from config.base import get_environment_variable
from exception.models import handle_exception
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.... | th, timeout=10)
# Strip out the twitter handles "False" or "None"
if twitter_handle is False:
twitter_handle = ''
elif twitter_handle is None:
twitter_handle = ''
elif twitter_handle:
twitter_handle_lower = twitter_handle.lower()
if twitter | _handle_lower == 'false' or twitter_handle_lower == 'none':
twitter_handle = ''
twitter_handle_found = False
twitter_json = {}
from wevote_functions.functions import convert_to_int
twitter_user_id = convert_to_int(twitter_user_id)
try:
if positive_value_exists(twitter_handle):
... |
YufeiZhang/Principles-of-Programming-Python-3 | Labs/lab1/octagram.py | Python | gpl-3.0 | 1,247 | 0.00401 | # Draws a dodecadon with the colour of each sector alternating red and blue.
#
# Written by Eric Martin for COMP9021
from turtle impo | rt *
import math
def draw_triangle(i, colour, n, vertices):
color(colour)
begin_fill()
| goto(vertices[i + n])
goto(vertices[(i+1)%n])
end_fill()
def draw_inside(colour, n, vertices):
color(colour)
begin_fill()
for i in range(n):
goto(vertices[i%n])
goto(vertices[(i+1)%n])
end_fill()
def find_points(edge_length, n, vertices):
length = 2 * edge_length * abs(m... |
SteveDiamond/cvxpy | cvxpy/cvxcore/tests/python/test_linops.py | Python | gpl-3.0 | 9,122 | 0.00011 | import unittest
from cvxpy import *
import numpy as np
from cvxpy.tests.base_test import *
import scipy.sparse as sp
class TestLinOps(BaseTest):
def assertDataEqual(self, original_data, canon_data):
for key in ['A', 'b', 'c', 'G', 'h']:
M1, M2 = original_data[key], canon_data[key]
... | .randn(rows, cols)
self.assertConstraintsMatch([x1 + x2 == A])
def test_sum_sparse(self):
rows, cols = 75, 100
x1 = Variable(rows, cols)
x2 = Variable(rows, cols)
A_sp = sp.rand(rows, cols, density=0.01)
self.assertConstraintsMatch([x1 + x2 == A_sp])
def test_pr... | )
def test_mul_dense(self):
rows, cols = 15, 17
A = np.random.randn(rows, cols)
b = Variable(rows, 1)
x = Variable(cols, 1)
y = Variable(rows, 1)
self.assertConstraintsMatch([A*x == b, A*x == y])
def test_mul_sparse(self):
rows, cols = 75, 100
... |
GaretJax/csat | csat/client.py | Python | mit | 2,111 | 0.000474 | import json
import socket
class Function(object):
def __init__(self, proxy, name):
self.proxy = proxy
self.name = name
def __call__(self, *args):
return self.proxy.call(self.name, *args)
class RemoteJsonError(RuntimeError):
pass
class CouldNotConnect(RuntimeError):
pass
... | Error:
raise RemoteJsonError('Remote JSON error: {}'.format(
response['error']['code']))
def _send_json(self, payload):
payload = json.dumps(payload)
self._send_netstring(payload)
def _send_netstring(self, payload):
payload = '{}:{},'.format(len(payload), pa... | if self.socket is None:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.connect(self.endpoint)
except socket.error:
raise CouldNotConnect()
self.socket.send(payload)
def _recv_json(self):
retu... |
michael-conway/policy-domains | ingest-domain/rules/src/ingest_policy_domain.py | Python | bsd-2-clause | 1,404 | 0.003561 | # ingest policy domain code
import logging
import init_domain
class IngestPolicyDomain:
def __init__(self, host="irods421.irodslocal"):
self.logger = logging.getLogger(__name__)
self.host = host
self.logger.info("initializing IngestPolicyDomain()")
def initialize_domain(self):
... | th("/zone1/home/ingest/landing_zone"):
self.logger.info("landing_zone")
return "landing_zone"
if path.startswith("/zone1/home/ingest/sip_validated"):
self.logger.info("sip_validated")
return "sip_validated"
if path.startswith("/zone1/home/ingest/ | aip_assembly"):
self.logger.info("aip_assembly")
return "aip_assembly"
if path.startswith("/zone1/home/ingest/aip_pickup_window"):
self.logger.info("aip_assembly")
return "aip_pickup_window"
raise LookupError("Cannot resolve path %s" % path)
if __name__... |
usc-isi-i2/mydig-webservice | ws/data_persistence.py | Python | mit | 1,945 | 0.001542 | import json
import threading
import os
import codecs
import logging
from config import config
logger = logging.getLogger(config['logging']['name'])
# 1.acquire file write lock
# 2.write to file.new
# 4.rename file to file.old
# 5.rename file.new to file
# 6.remove file.old
# 7.release write lock
# *. lock should be... | e_path):
new_path = file_path + '.new'
old_path = file_path + '.old'
has_file = os.path.exists(file_path)
has_new = os.path.exists(new_path)
has_old = os.path.exists(old_path)
if has_file and not has_new and not has_old:
pass
elif not has_file and has_old and has_new:
os.rem... | has_file and not has_old and has_new:
os.remove(new_path)
else:
pass
|
dimaleks/uDeviceX | docs/source/_mirheo/ParticleVectors/__init__.py | Python | gpl-3.0 | 24,860 | 0.008045 | class Mesh:
r"""
Internally used class for describing a simple triangular mesh
"""
def __init__():
r"""__init__(*args, **kwargs)
Overloaded function.
1. __init__(off_filename: str) -> None
Create a mesh by reading the OFF file
Args:
off_filename: path of ... | h by giving coordinates and connectivity, with a different stress-free shape.
Args:
vertices: vertex coordinates
stress_free_vertices: vertex coordinates of the stress-free shape
faces: connectivity | : one triangle per entry, each integer corresponding to the vertex indices
"""
pass
def getFaces():
r"""getFaces(self: ParticleVectors.Mesh) -> List[List[int[3]]]
returns the vertex indices for each triangle of the mesh.
"""
pass
def getVertices():... |
benob/chainer | tests/cupy_tests/manipulation_tests/test_kind.py | Python | mit | 1,126 | 0 | import unittest
from cupy import testing
@testing.gpu
class TestKind(unittest.TestCase):
_multiprocess_can_split_ = True
@testing.for_all_dtypes()
@testing.numpy_cupy_array_equal(type_check=False)
def test_asfortranarray1(self, xp, dtype):
x = xp.zeros((2, 3), dtype)
ret = xp.asfort... | asfortranarray3(self, xp, dtype):
x = xp.zeros((2, 3, 4), dtype)
ret = xp.asfort | ranarray(xp.asfortranarray(x))
self.assertTrue(x.flags.c_contiguous)
self.assertTrue(ret.flags.f_contiguous)
return ret.strides
|
compston/TAP-Workshop | utilities/Gnip-Analysis-Pipeline/insights/output.py | Python | mit | 8,810 | 0.013621 | import sys
import json
import os
from matplotlib import use
use("Agg")
import matplotlib.pyplot as plt
from collections import defaultdict
import datetime
from matplotlib import dates, use
def dump_conversation(results,args):
# the name of the analysis
uid = results["audience_id_string"]
data_loc = "/... | = sorted([(datetime.datetime.strptime(x[0], "%H"),x[1])
for x in hour], key = lambda x:x[0])
times = [x[0] for x in times_values]
values = [x[1] for x in times_values]
fig, ax = plt.subplots( nrows=1, ncols=1, figsize = (10,4))
ax.plot(times, values)
ax.set_xlabel("... | ay (based on local time)", size = 14)
ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))
fig.autofmt_xdate()
fig.savefig(data_loc + uid + "/" + uid + "_hourly_timeline.png")
# urls
urls = sorted(results["urls"].items(), key = lambda x: x[1], reverse = True)
print "\nnumber of times twee... |
lucalianas/ProMort | promort/shared_datasets_manager/migrations/0001_initial.py | Python | mit | 2,500 | 0.0044 | # Generated by Django 3.1.8 on 2021-05-09 16:06
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('slid... | dataset', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='items', to='shared_datasets_manager.shareddataset')),
('slides_set_a', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='shared_dataset_item_a', to='slides_manager.slidesset')),
... | slidesset')),
],
options={
'unique_together': {('dataset', 'slides_set_a_label'), ('slides_set_a', 'slides_set_b'), ('dataset', 'slides_set_b_label'), ('dataset', 'dataset_index')},
},
),
]
|
kezabelle/clastic | clastic/tests/test_routing.py | Python | bsd-3-clause | 6,586 | 0.000456 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from nose.tools import raises, eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseR | esponse
from clastic import Application, render_basic
from clastic.application import BaseApplication
from clastic.route import BaseRoute, Route
from clastic.route import (InvalidEndpoint,
InvalidPattern,
InvalidMethod)
from clastic.route import S_STRICT, S_REWRIT... |
mpetyx/pychatbot | AIML/AliceTwitter/GAEAlice/multipart.py | Python | apache-2.0 | 5,097 | 0.000392 | '''
Classes for using multipart form data from Python, which does not (at the
time of writing) support this directly.
To use this, make an instance of Multipart and add parts to it via the factory
methods field and file. When you are done, get the content via the get method.
@author: Stacy Prowell (http://stacyprowe... | dition to disposition.
@type headers: dict
'''
self.parts.append(Part(name, filename, value, headers))
return
def get(self):
'''
Get the multipart form data. This returns the content type, which
specifies the boundary marker, and also returns the body contai... |
all += part.get()
all.append('--' + Part.BOUNDARY + '--')
all.append('')
# We have to return the content type, since it specifies the boundary.
content_type = 'multipart/form-data; boundary=%s' % Part.BOUNDARY
return content_type, Part.CRLF.join(all) |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_4_0_0/models/effectevidencesynthesis.py | Python | bsd-3-clause | 20,867 | 0.008291 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/EffectEvidenceSynthesis) on 2019-05-07.
# 2019, SMART Health IT.
from . import domainresource
class EffectEvidenceSynthesis(domainresource.DomainResource):
""" A quantified estimate o... | vidence synthesis.
Type `str`. """
super(EffectEvidenceSynthesis, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(EffectEvidenceSynthesis, self).elementProperti | es()
js.extend([
("approvalDate", "approvalDate", fhirdate.FHIRDate, False, None, False),
("author", "author", contactdetail.ContactDetail, True, None, False),
("certainty", "certainty", EffectEvidenceSynthesisCertainty, True, None, False),
("contact", "contact", ... |
joegomes/deepchem | deepchem/utils/save.py | Python | mit | 5,030 | 0.016302 | """
Simple utils to save and load from disk.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
# TODO(rbharath): Use standard joblib once old-data has been regenerated.
import joblib
from | sklearn.externals import joblib as old_joblib
import gzip
import pickle
import pandas as pd
import numpy as np
import os
from rdkit import Chem
def log(string, verbose=True):
"""Print string if verbose."""
if verbose:
print(string)
def save_to | _disk(dataset, filename, compress=3):
"""Save a dataset to file."""
joblib.dump(dataset, filename, compress=compress)
def get_input_type(input_file):
"""Get type of input file. Must be csv/pkl.gz/sdf file."""
filename, file_extension = os.path.splitext(input_file)
# If gzipped, need to compute extension agai... |
ryankanno/py-utilities | py_utilities/compression/tar_utilities.py | Python | mit | 1,077 | 0.000929 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
import tarfile
def create_tarball(dirs_to_tarball, tarball_name, save_dir,
backup_date_fmt="%Y%m%d_%H%M%S", gzip=True):
if gzip:
tar_opts = 'w:gz'
file_suffix = 'tar.gz'
else:
tar_opts = 'w:'
... | else:
tarball_filename = "{0}.{1}".format(
tarball_name,
file_suffix)
tarball_filepath = os.path.join(save_dir, tarball_filename)
try:
tar = tarfile.open(tarball_filepath, tar_opts)
for dir in dirs_to_tarball:
tar.add(dir)
except: # pragma: no... | return tarball_filepath
else:
return None
# vim: filetype=python
|
elbeardmorez/quodlibet | quodlibet/quodlibet/ext/events/auto_library_update.py | Python | gpl-2.0 | 6,971 | 0.000287 | # -*- coding: utf-8 -*-
# Automatic library update plugin
#
# (c) 2009 Joe Higton
# 2011 - 2016 Nick Boultbee
#
# 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 Licens... | pass
GLib.idle_add(self.update, event)
def process_IN_MOVED_FROM(self, event):
self._log(event)
GLib.idle_add(self.update, event)
def _log(self, event):
print_d('%s for "%s" on %s' % (event.maskname, event.name, event.path))
def add(self, event):
"""Add a libr... | nt.name)
if event.dir:
print_d('Scanning directories...')
songs = []
for path, dnames, fnames in os.walk(path):
print_d('Found %d file(s) in "%s"' % (len(fnames), path))
for filename in (os.path.join(path, fn) for fn in fnames):
... |
nesaro/pydsl | pydsl/contrib/grammar/DayOfMonth.py | Python | gpl-3.0 | 437 | 0.006865 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (C) 2008-2014 Nestor Arocha
def matchFun(myinput):
from collections import Iterable
if isinstance(myinput, Iterable):
myinput = "".join([str(x) for x in myinput])
strnumber = str | (myinput)
try:
number = int(strnumber)
except ValueError:
return False
if 0 < number < 32:
return Tru | e
return False
iclass = "PythonGrammar"
|
veusz/veusz | veusz/widgets/page.py | Python | gpl-2.0 | 13,301 | 0.001729 | # Copyright (C) 2004 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# 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
# ... | axis in loopcheck:
axis = None
if axis is not None and therange is not None:
self.ranges[axis] = [
N.nanmin((self.ranges[axis][0], therange[0])),
N.nanmax((self.ranges[axis][1], therange[1])) |
]
else:
plotter.getRange(axis, plotterdep, self.ranges[axis])
def processWidgetDeps(self, dep):
"""Process dependencies for a single widget."""
widget, widget_dep = dep
|
ypersyntelykos/GitSavvy | core/commands/quick_stage.py | Python | mit | 3,133 | 0.000958 | from collections import namedtuple
import sublime
from sublime_plugin import WindowCommand
from ..git_command import GitCommand
MenuOption = namedtuple("MenuOption", ["requires_action", "menu_text", "filename", "is_untracked"])
CLEAN_WORKING_DIR = "Nothing to commit, working directory clean."
ADD_ALL_UNSTAGED_FILES... | ng.
Display filenames with one of the follow | ing indicators:
* [M] modified
* [A] added
* [D] deleted
* [R] renamed/moved
* [C] copied
* [U] updated but unmerged
* [?] untracked
"""
def run(self):
sublime.set_timeout_async(self.run_async)
def run_async(self):
menu_options = se... |
xgds/xgds_plot | xgds_plot/pandasUtil.py | Python | apache-2.0 | 12,685 | 0.000867 | #__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... | ections, for example if the db se | rver is
restarted.
"""
global dbConnectionG
if dbConnectionG:
try:
dbConnectionG.close()
except: # pylint: disable=W0702
logging.warning('pandasUtil.closeDbConnection: unable to close dbConnectionG %s', dbConnectionG)
logging.warning('pandasUtil.close... |
jbzdak/finna-be-octo-robot | stopwords_cffi.py | Python | apache-2.0 | 688 | 0.005814 | # -*- coding: utf-8 -*-
import os, sys
so = os.p | ath.join(os.path.dirname(__file__), "cpp", "libstopwords.so")
stopwords = os.path.join(os.path.dirname(__file__), "outfile.txt").encode("utf-8")
from cffi import FFI
ffi = FFI()
ffi.cdef("""
u | int32_t init( const char* infile, void** lg);
void deinit(void* ctx);
const char* guess_language(void* ctx, const char* text, const char* delim);
""")
sw = ffi.dlopen(so)
path = ffi.new("char[]", stopwords)
ctx = ffi.new("void **")
if sw.init(path, ctx) != 0:
raise ValueError()
ctx = ctx[0]
snippet = ffi.new("... |
jelliedpizza/RoleBot | RoleBot/brain.py | Python | agpl-3.0 | 4,740 | 0.01962 | import discord
from discord.ext import commands
import json
import asyncio
import sys
import checks
import os
try:
from urllib.request import urlretrieve
except Exception as e:
pass
import json
import unicodedata
os.chdir(os.path.dirname(os.path.realpath(__file__)))
with open('config.json') as json_data_file:
c... | name = unicodedata.name(c, 'Name not found.')
return f'`\ | \U{digit:>08}`\t: {name} - {c} \N{EM DASH} <http://www.fileformat.info/info/unicode/char/{digit}>'
await bot.say('\n'.join(map(to_string, characters)))
@bot.command(hidden=True, pass_context=True)
@checks.is_owner()
async def dbug(ctx, *, te):
"""Run a command"""
try:
await bot.say("```py\n" + str(eva... |
alogfans/yaoj | main/blog/templatetags/to_html.py | Python | mit | 363 | 0.033058 | import markdown, datetime
from django import template
from django.template.base import (Node, NodeList, TemplateSyn | taxError)
register = template.Library()
@register.filter(name='toHtml')
def toHtml(markdownfile):
return markdown.markdown(markdownfile)
@register.filter(name='toNowTime')
def toNowTime(black | _hole):
return datetime.now()
|
jonasjberg/autonameow | autonameow/vendor/guessit/rules/properties/other.py | Python | gpl-2.0 | 6,252 | 0.004319 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
other property
"""
import copy
from rebulk.remodule import re
from rebulk import Rebulk, Rule, RemoveMatch, POST_PROCESS, AppendMatch
from ..common import dash
from ..common import seps
from ..common.validators import seps_surround
from ...rules.common.formatters impo... | ount_match = copy.copy(propers[-1])
proper_count_match.name = 'proper_count'
proper_count_match.value = len(raws)
return proper_count_match
class ValidateHasNeighbor(Rule):
"""
Validate tag has-neighbor
"""
consequence = RemoveMatch
def when(self, matches, cont... | ]
for to_check in matches.range(predicate=lambda match: 'has-neighbor' in match.tags):
previous_match = matches.previous(to_check, index=0)
previous_group = matches.markers.previous(to_check, lambda marker: marker.name == 'group', 0)
if previous_group and (not previous_match ... |
SirDavidLudwig/KattisSolutions | problems/sodasurpler/sodasurpler.py | Python | gpl-3.0 | 99 | 0.030303 | e, f, c = map(int, input().split())
d | = 0
t = e+f
while t >= c:
d += t//c
t = t% | c+t//c
print(d)
|
greenstone/keadatabase-back | src/locations/management/commands/loadregions.py | Python | agpl-3.0 | 1,458 | 0.002058 | import io, tempfile
from django.core import management
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.utils import LayerMapping
from locations.models import Region
class Command(management.BaseCommand):
help = 'Allows the import of regions'
def check_current_status(self):
""... | '))
region_mapping = {'name': 'NAME', 'polygon': 'POLYGON'}
region_shp = '../data/kx-nz-regional-councils-2012-yearly-pattern-SHP/nz-regional-councils-2012-yearly-pattern.shp'
lm = LayerMapping(
Region,
region_shp,
region_mapping,
transform=Fals... | ,
)
lm.save(strict=True, verbose=False)
self.stdout.write(self.style.SUCCESS('\nImport complete'))
def handle(self, *args, **options):
self.check_current_status()
confirm = input('\nReady to import? Type \'yes\' to continue: ')
#confirm = 'yes' # for debugging
... |
vnleonenko/Influenza | core/models/seir.py | Python | gpl-3.0 | 14,250 | 0.002513 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Моделирование процесса распространения гриппа на основе системы ДУ
Идентификация параметров модели на основе данных измерений градиентным методом локального поиска
-*- Flu Model -*-
S - Susceptible (восприимчивые к болезни)
E - | Exposed (латентные - первые заразившиеся)
I - Infected (инфицированные с признаками болезни)
R - Recovered (выздоровевшие)
-*- ФОРМА УРАВНЕНИЙ -*-
dS/dt = -k1*S*I | <-- текущее здоровых
dE/dt = +k1*S*I - k2*E <-- текущее инфицированных латентных
dI/dt = +k2*E - k3*I <-- текущее инфицированны
dR/dt = +k3*I <--- ВЫЗДОРОВЕЛО ВСЕГО (ТОЛЬКО РОСТ):
-*- СМЕРТНОСТЬ -*-
dR/dt = +k4*T <--- УМЕРЛО ВСЕГО (ТОЛЬКО РОСТ... |
kennedyshead/home-assistant | homeassistant/components/myq/binary_sensor.py | Python | apache-2.0 | 2,370 | 0.000422 | """Support for MyQ gateways."""
from pymyq.const import (
DEVICE_STATE as MYQ_DEVICE_STATE,
DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE,
KNOWN_MODELS,
MANUFACTURER,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
BinarySensorEntity,
)
from homeassistant.help... | eturn the name of the garage door if any."""
return f"{self._device.name} MyQ Gateway"
@property
def is_on(self):
"""Return if the device is online."""
if not self.coordinator.last_update_success:
| return False
# Not all devices report online so assume True if its missing
return self._device.device_json[MYQ_DEVICE_STATE].get(
MYQ_DEVICE_STATE_ONLINE, True
)
@property
def available(self) -> bool:
"""Entity is always available."""
return True
@p... |
seece/cbpp | error.py | Python | mit | 730 | 0.052055 | import sys
class Message:
def __init__(self, row, message):
self.row = row
self.message = message
def toString(self):
if (self.row):
return str(self.row) + ": " + self.message
else:
return self.message
class ErrorLog:
def __init__(self):
self.log = []
self.em | it = True # print to console on add
self.halt = False # quit when add is called
def add(self, row, message):
msg = Message(row, message)
self.log.append(msg)
| if self.emit:
print(msg.toString())
if self.halt:
sys.exit(msg.message)
def getLog(self):
return self.log
def count(self):
return len(self.log)
def __iter__(self):
return iter(self.log)
infos = ErrorLog()
errors = ErrorLog()
warnings = ErrorLog()
|
justasabc/kubernetes-ubuntu | ke/images/python/global_load_data.py | Python | apache-2.0 | 866 | 0.032333 | """
Class Hierarchy
G{classtree: GlobalLoadData}
Package tree
G{packagetree: global_load_data}
Import Graph
G{importgraph: global_load_data}
"""
LOAD_LEVEL_NORMAL = 0
LOAD_LEVEL_EXPAND = 1
LOAD_LEVEL_SHRINK = 2
class GlobalLoadData:
def __init__(self,global_lo | ad_data_dict):
print "[GlobalLoadData] init ..."
self.global_load_data_dict = global_load_data_dict
print "[GlobalLoadData] OK"
def get_load_lower(self,name):
return self.global_load_data_dict[name]['lower']
def get_load_upper(self,name):
return self.global_load_data_dict[name]['upper']
def cal_load_lev... | turn LOAD_LEVEL_SHRINK
elif load > upper:
return LOAD_LEVEL_EXPAND
else:
return LOAD_LEVEL_NORMAL
class GlobalLoadDataTesting(GlobalLoadData):
pass
|
devilry/devilry-django | devilry/devilry_superadmin/management/commands/devilry_periodsearch.py | Python | bsd-3-clause | 573 | 0.006981 | from django.db.models import Q
from d | evilry.apps.core.models import Period
from devilry.devilry_superadmin.management.commands.devilry_subjectsearch import NodeSearchBase
class Command(NodeSearchBase):
help = 'Search for a period by short_name. Matches any part of the short_name.'
nodecls = Period
def get_qry(self, term):
return sel... | name__icontains=term) | Q(parentnode__short_name__icontains=term))
def get_short(self, record):
return '{0}.{1}'.format(record.parentnode.short_name, record.short_name)
|
dokterbob/django-shopkit | shopkit/core/__init__.py | Python | agpl-3.0 | 1,274 | 0.00157 | # Copyright (C) | 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-shopkit.
#
# django-shopkit is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# ... | thout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Frank... |
delaere/WebAccess | cgi-bin/getCanvas.py | Python | apache-2.0 | 623 | 0.008026 | #!/usr/bin/env python
# -*- | coding: UTF-8 -*-# enable debugging
import sys
sys.path.append('/usr/lib/root/')
import cgi
import cgitb
cgitb.enable()
import ROOT
import tempfile
print "Content-Type: image/svg+xml"
print
parameters = cgi.FieldStorage()
if parameters.has_key("file") and parameters.has_key("canvas"):
filename = parameters["file"].... | = ROOT.TFile(filename)
tcanvas = f.Get(canvas)
out = tempfile.NamedTemporaryFile(suffix=".svg")
tcanvas.SaveAs(out.name)
s = out.read()
key = canvas.split("/")[-1]
print "<!--"+key+"-->"
print s
|
OstapHEP/ostap | ostap/math/random_ext.py | Python | bsd-3-clause | 6,045 | 0.049462 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# @file ostap/math/random_ext.py
# The simple extention for the standard python module random
# @author Vanya BELYAEV
# @date 2012-04-28
# =====================================================... | # =============================================================================
_poisson = None
if not _poisson :
try :
from numpy.ran | dom import poisson as _poisson
def _poisson_ ( self , mu ) : return _poisson ( mu )
logger.debug ('use numpy.random.poisson')
except ImportError :
pass
if not _poisson :
try :
from scipy.random import poisson as _poisson
def _poisson_ ( self , mu ) : return _poisson ( m... |
Javantea/satispy | satispy/cnf.py | Python | bsd-3-clause | 5,607 | 0.003567 | cnfClass = None
class Variable(object):
def __init__(self, name, inverted=False):
self.name = name
self.inverted = inverted
def __neg__(self):
v = Variable(self.name)
v.inverted = not self.inverted
return v
def __and__(self, other):
c = cnfClass.create_from... |
def __neg__(self):
cnfs = []
for d in sel | f.dis:
c = NaiveCnf()
for v in d:
c.dis.append(frozenset([-v]))
cnfs.append(c)
ret = NaiveCnf()
for cnf in cnfs:
ret |= cnf
return ret
def __rshift__(self, other): # implies
return -self | other
def __str__(self)... |
ryansb/netHUD | nethud/dpqueue.py | Python | mit | 927 | 0.001079 | from twisted.internet.defer import Deferred, DeferredQueue, succeed
from colle | ctions import defaultdict
class DeferredPriorityQueue(DeferredQueue):
def __init__(self):
DeferredQueue.__init__(self, None, None)
self.pending = defaultdict(list)
def put(self, priority, obj):
if self.waiting:
self.waiting.pop(0).callback(obj)
else:
se... | ret_val = self.pending[min_].pop(0)
if not self.pending[min_]:
del self.pending[min_]
return succeed(ret_val)
else:
d = Deferred(canceller=self._cancelGet)
self.waiting.append(d)
return d
def peek(self):
return succeed(hea... |
boundarydevices/android_external_chromium_org | ppapi/tests/create_nonsfi_test_nmf.py | Python | bsd-3-clause | 2,605 | 0.008445 | #!/usr/bin/env python
# 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.
"""Simple tool to generate NMF file by just reformatting given arguments.
This tool is similar to native_client_sdk/src/tools/create_n... | heir contents,
but it does not work for Non-SFI nexes (which don't have a marker to
distinguish them from SFI nexes).
This script simply reformats the command line arguments into NMF JSON form | at.
"""
import argparse
import collections
import json
import logging
import os
_FILES_KEY = 'files'
_PORTABLE_KEY = 'portable'
_PROGRAM_KEY = 'program'
_URL_KEY = 'url'
_X86_32_NONSFI_KEY = 'x86-32-nonsfi'
def ParseArgs():
parser = argparse.ArgumentParser()
parser.add_argument(
'--program', metavar='FILE... |
gecos-team/gecos-firstboot | firstboot/pages/pcLabel/__init__.py | Python | gpl-2.0 | 3,149 | 0.002224 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software 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 o | f the Lice | nse, or
# (at your option) any later version.
#
# This software 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... |
CitrineInformatics/python-citrination-client | citrination_client/models/columns/categorical.py | Python | apache-2.0 | 2,304 | 0.001736 | from citrination_client.models.columns.base import BaseColumn
from citrination_client.base.errors import CitrinationClientError
from six import string_types
class CategoricalColumn(BaseColumn):
"""
A categorical column configuration for a data view. Parameterized
with the basic column options and a list o... | :param units: Optionally, the units for the column
:type units: str
:param categories: An array of strings that are valid values for data
in this column
:type categories: list of str
"""
super(CategoricalColumn, self).__init__(name=name,
... | categories = categories
def build_options(self):
return {
"categories": self.categories
}
@property
def categories(self):
return self._categories
@categories.setter
def categories(self, value):
self._validate_categories(value)
self._categories =... |
erikrose/dxr | dxr/testing.py | Python | mit | 7,767 | 0.000386 | from commands import getstatusoutput
import json
from os import chdir, mkdir
import os.path
from os.path import dirname
from shutil import rmtree
import sys
from tempfile import mkdtemp
import unittest
from urllib2 import quote
from nose.tools import eq_
try:
from nose.tools import assert_in
except ImportError:
... | return output
# ---- More permanent stuff: ----
class TestCase(unittest.TestCase):
"""Abstract container for general convenience functions for DXR tests"""
def client(self):
# TODO: DRY between here and the config file with 'target'.
app = make_app(os.path.join(self._config_dir_path, 'tar... | fig['TESTING'] = True # Disable error trapping during requests.
return app.test_client()
def found_files(self, query, is_case_sensitive=True):
"""Return the set of paths of files found by a search query."""
return set(result['path'] for result in
self.search_results(quer... |
vickyi/scoala | pachong/pythonClass/switch.py | Python | mit | 685 | 0.026277 | import datetime
day = datetime.datetime.now().weekday()
def get_sunday():
return "Today it's Sunday"
def get_monday():
return "Today it's Monday"
def get_tuesday():
return "Today it's Tuesday"
def get_wedne | sday():
return "Today it's Wednesday"
def get_thursday():
return "Today it's Thursday"
def get_friday():
return "Today it's Friday"
def get_saturday():
return "Today it's Saturday"
def get_default():
return "Looking forward to the Weekend"
switcher = {
0:get_sunday,
1:get_monday,
2 | :get_tuesday,
3:get_wednesday,
4:get_thursday,
5:get_friday,
6:get_default
}
dayName = switcher.get(day,get_default)()
print(dayName) |
denebolar/pyKmlChart | kmlChart/kmlInterface.py | Python | apache-2.0 | 12,427 | 0.002495 | """
Interface to produce files.
"""
from xml | .etree import ElementTree
| from argparse import ArgumentTypeError
# Register XML name spaces
namespaces = {
'': 'http://www.opengis.net/kml/2.2',
'gx': 'http://www.google.com/kml/ext/2.2',
'atom': 'http://www.w3.org/2005/Atom',
'xal': 'urn:oasis:names:tc:ciq:xsdschema:xAL:2.0',
}
for prefix, namespace in namespaces.... |
jyeatman/dipy | doc/examples/reconst_dki.py | Python | bsd-3-clause | 10,048 | 0.00199 | """
=====================================================================
Reconstruction of the diffusion signal with the kurtosis tensor model
=====================================================================
The diffusion kurtois model is an expansion of the diffusion tensor model. In
addition to the diffusion t... | ed diffusion weighting, $\mathbf{b}$, the
signal in the absence of diffusion gradient sensitisation, $S_0$, and the
values of diffusion, $\mathbf{D(n)}$, and diffusion kurtosis, $\mathbf{K(n)}$,
along the spatial direction $\mathbf{n}$ [NetoHe2015]_:
.. math::
S(n,b)=S_{0}e^{-bD(n)+\frac{1 | }{6}b^{2}D(n)^{2}K(n)}
$\mathbf{D(n)}$ and $\mathbf{K(n)}$ can be computed from the DT and KT using
the following equations:
.. math::
D(n)=\sum_{i=1}^{3}\sum_{j=1}^{3}n_{i}n_{j}D_{ij}
and
.. math::
K(n)=\frac{MD^{2}}{D(n)^{2}}\sum_{i=1}^{3}\sum_{j=1}^{3}\sum_{k=1}^{3}
\sum_{l=1}^{3}n_{i}n_{j}n_{k}n_... |
CaptainDesAstres/Blender-Render-Manager | log.py | Python | mit | 2,242 | 0.084305 | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module who manage the log of the script'''
import os
class Log:
'''class who manage the log of the script
there is to log:
the file where is save the log at each new line,
the string who is print eache time that the standart output is erase'''
def __init__(self, star... | rt+'.log','a')
self.logFile.write(self.log)
self.write('log creation\n')
self.menu = []
self.runMenu = None
def __del__(self):
'''close the log file when the object is deleted'''
self.logFile.close()
del(self.log)
del(self.logFile)
def __str__(self):
'''return string log'''
... | os.system('clear')
print(self.log)
if menu :
self.printMenu()
def write(self, txt, sep = '\n'):
'''add lines to the log'''
self.logFile.write(txt+sep)
self.log += txt+sep
def error(self, err, log = True):
'''Display a error message and add it to the log'''
err = '\033[31mError : '+er... |
BitcoinUnlimited/BitcoinUnlimited | qa/rpc-tests/electrum_reorg.py | Python | mit | 1,875 | 0.002667 | #!/usr/bin/env python3
# Copyright (c) 2019 The Bitcoin Unlimited developers
"""
Tests to check if basic electrum server integration works
"""
import random
from test_framework.util import waitFor, assert_equal
from test_framework.test_framework import BitcoinTestFramework
from test_framework.loginit import logging
fro... | wait | For(10, lambda: compare(n, "index_height", n.getblockcount()))
waitFor(10, lambda: compare(n, "mempool_count", 0, True))
n.sendtoaddress(n.getnewaddress(), 1)
assert_equal(1, len(n.getrawmempool()))
waitFor(10, lambda: compare(n, "mempool_count", 1, True))
blocks = n.generate(50... |
skosukhin/spack | lib/spack/spack/util/naming.py | Python | lgpl-2.1 | 9,591 | 0 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | Replace "++" with "pp" and "+" with "-plus"
# e.g. gtk+ -> gtk-plus
# e.g. voro++ -> voropp
name = name.replace('++', 'pp')
name = name.replace('+', '-plus')
# Simplify Lua package names
# We don't want "lua" to occur multiple times in the name
name = re.sub('^(lua)([^-])', r'\ | 1-\2', name)
# Simplify Bio++ package names
name = re.sub('^(bpp)([^-])', r'\1-\2', name)
return name
def valid_module_name(mod_name):
"""Return whether mod_name is valid for use in Spack."""
return bool(re.match(_valid_module_re, mod_name))
def valid_fully_qualified_module_name(mod_name):
... |
ryankanno/vor | vor/backends/cc/visa.py | Python | mit | 463 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .base import CreditCardProvider
from .gencc import visaPrefixList
from .gencc import credit_card_number
from random import Random
class VisaProvider(CreditCardProvider):
def __init__(self, *args, **kwargs):
super(VisaProvider, self).__init_ | _(*args, **kwargs)
def get_credit_card_number(self):
return credit_card_number(Random().seed(), visaPrefixList, 16, 10)
# vim | : filetype=python
|
looker/sentry | src/sentry/interfaces/sdk.py | Python | bsd-3-clause | 2,602 | 0.000384 | from __future__ import absolute_import
__all__ = ('Sdk', )
from distutils.version import LooseVersion
from django.conf import settings
from sentry.interfaces.base import Interface, InterfaceValidationError
from sentry.utils.safe import trim
def get_with_prefix(d, k, default=None, delimiter=":"):
"""\
Retri... | d[key]
return default
class Sdk(Interface):
"""
The SDK used to transmit this event.
>>> {
> | >> "name": "sentry-java",
>>> "version": "1.0",
>>> "integrations": ["log4j"]
>>> }
"""
@classmethod
def to_python(cls, data):
name = data.get('name')
if not name:
raise InterfaceValidationError("No 'name' value")
version = data.get('version')
... |
JimmyMow/OpenBazaar-Server | api/ws.py | Python | mit | 13,034 | 0.002992 | __author__ = 'chris'
import json
import os
import time
from constants import DATA_FOLDER
from market.profile import Profile
from keyutils.keys import KeyChain
from random import shuffle
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol
from protos.countries import CountryCode
from ... | :
val = objects.Value()
val.ParseFromString(mod)
n = objects.Node()
n.ParseFromString(val.serializedData)
node_to_ask = Node(n.guid, n.ip, n. | port, n.signedPublicKey)
if n.guid == KeyChain(self.factory.db).guid:
parse_profile(Profile(self.factory.db).get(), node_to_ask)
else:
self.factory.mserver.get_profile(node_to_ask)\
.a... |
indautgrp/frappe | frappe/patches/v5_0/modify_session.py | Python | mit | 185 | 0.021622 | import frappe
def execute | ():
if "device" not in frappe.db.get_table_columns("Sessions"):
frappe.db.sql("alter table ta | bSessions add column `device` varchar(255) default 'desktop'")
|
hyounggyu/xni | xni/__init__.py | Python | lgpl-3.0 | 132 | 0 | impor | t os
pkg_dir = os.pat | h.abspath(os.path.dirname(__file__))
sample_dir = os.path.join(pkg_dir, 'sample')
__version__ = '0.5.0'
|
unreal666/outwiker | src/test/core/test_attachwatcher.py | Python | gpl-3.0 | 20,012 | 0 | # -*- coding: utf-8 -*-
import os
import shutil
from tempfile import mkdtemp
import wx
from outwiker.core.attachment import Attachment
from outwiker.core.tree import WikiDocument
from outwiker.pages.text.textpage import TextPageFactory
from outwiker.core.application import Application
from outwiker.core.attachwatche... | kiroot |
self._application.selectedPage = self.page_01
watcher = AttachWatcher(self._application, self._period_ms)
watcher.initialize()
Attachment(self._application.selectedPage).getAttachPath(True)
wx.MilliSleep(500)
self.myYield()
watcher.clear()
self.assertE... |
lsbardel/zipline | zipline/finance/risk/period.py | Python | apache-2.0 | 9,654 | 0.000207 | #
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | ctools
import logbook
import math
import numpy as np
import numpy.linalg as la
from six import iteritems
from | zipline.finance import trading
import pandas as pd
from . import risk
from . risk import (
alpha,
check_entry,
information_ratio,
sharpe_ratio,
sortino_ratio,
)
log = logbook.Logger('Risk Period')
choose_treasury = functools.partial(risk.choose_treasury,
risk... |
zacharyvoase/django-clsview | src/djclsview.py | Python | unlicense | 10,065 | 0.008147 | # -*- coding: utf-8 -*-
__version__ = '0.0.3'
from functools import partial, wraps
__all__ = ['View']
class View(object):
"""
Abstract superclass for class-based views.
Class-based views (CBVs) are classes which behave in a similar way to Django
view functions. The underlying requirement ... | Name(request, *args, **kwargs)` will instantiate the class and
then call the object (i.e. `obj.__call__()`), returning whatever that method
returns (which should be a `django.http.HttpResponse` instance). Thus, at
the highest level, view classes may be used identically to view functions.
Si | nce usual instantiation has been modified, you can instantiate a view
class with `ViewClass._new(request, *args, **kwargs)`. This might be useful
if you need to access functionality defined on another view class (although
a separate utility class or mixin is usually a better idea for shared
functionalit... |
ArtezGDA/MappingTheCity-Data | ElectionData/ElectionData-Scraper-Wikipedia.py | Python | mit | 560 | 0.028571 | from bs4 import BeautifulSoup
import urllib
r = urllib.urlopen("https://nl.wikipedia.org/wiki/Tweede_Kamerverkiezingen_2012").read()
soup = BeautifulSoup(r, "html.parser")
for item in soup.findAll("div", {"class": "thumb tright"}):
t | ekst = item.findAll("div", {"class": "thumbcaption"}) [0].getText()
lijstSP = item.findAll('p', {"style": "margin:0px;font-size:90%;"})[0].getText()
SP = item.findAll('a', {"title": "Socialistische Partij (Nederland)"})[0].getText()
print tekst
print lijstSP
print SP | |
qianlv/MachineLearningAlgorithm | mla/LinearModel.py | Python | mit | 3,742 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import random
from mla.base import add_intercept
class BasicRegression:
def __init__(self, method="sgd", eta=0.01, penalty='None', gamma=0.01,
tolerance=0.0001, max_iters=10000):
... | BasicRegression):
"""Docstring for LogisticRegression. """
def sigmod(self, X):
return 1.0 / (1 + np.exp(-X))
def _costGrad(self, X, y, w):
s = self.sigmod(np.dot(w, X.T))
grad = | np.dot((s - y), X)
return grad
def _costStocGrad(self, X, y, w):
# randindex = sorted(sample(range(self.n_samples), 3))
randindex = int(random.uniform(0, self.n_samples))
return self._costGrad(X[randindex].reshape((1, self.n_features + 1)),
y[randinde... |
exedre/webscraping-course-2014 | esempi/esempio0_json.py | Python | gpl-2.0 | 845 | 0.011834 | import json
import sys
import urllib
keyword = sys.argv[1]
def getTimes(query,num):
"Questa funzione fa una ricerca su NY Times"
url = "http://query.nytimes.com/svc/cse/v2/sitesearch.json?query="+query.replace(" ","%20")+"&pt=article&page="+str(num)
jtext = urllib.urlopen(url)
return jtext
def search... | int(resp['results']['meta']['payload'])
for res in resp['results']['results']:
print res['snippet']
headline = res['hdl']
# snippet = res['snippet']
# author = res['cre']
url = res['url']
print headline.encode('utf-8')
print ur... | er+=1
search(keyword)
|
htygithub/bokeh | examples/compat/mpl/listcollection.py | Python | bsd-3-clause | 1,602 | 0.002497 | from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
import numpy as np
from bokeh import mpl
from bokeh.plotting import output_file, show
def make_segments(x, y):
'''
Create list of line segments from x and y coordinates.
'''
points = np.array([x, y]).T.reshape(-1, 1, 2... | 'y', 'm', 'k']
widths = [5, 10, 20, 40, 20, 10, 5]
segments = make_segments(x, y)
lc = LineCollection(segments, colors=colors, linewidth=widths, alpha=alpha)
ax = plt.gca()
ax.add_collection(lc)
return lc
# Colored sine wave
x = np.linspace(0, 4 * np.pi, 100)
y = np.sin(x)
colorline(x, y)
... | o_bokeh())
|
leeseuljeong/leeseulstack_neutron | neutron/quota.py | Python | apache-2.0 | 12,508 | 0 | # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | ues are permitted by the limit restriction.
This method will raise a QuotaResourceUnknown exception if a
given resource is unknown or if it is not a simple limit
resource.
If any of the proposed values is over the defined quota, an
Over | Quota exception will be raised with the sorted list of the
resources which are too high. Otherwise, the method returns
nothing.
:param context: The request context, for access checks.
:param tennant_id: The tenant_id to check quota.
:param resources: A dictionary of the registe... |
kdart/pycopia | SNMP/bin/show_neighbors.py | Python | apache-2.0 | 888 | 0.001126 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# Licensed under the Apache License, Version | 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# ... | ed.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Show CDP neighbors using SNMP.
"""
import sys
from pycopia.Devices import Discovery
def main(argv):
host = argv[1]
community = argv[2]
dev = Discovery.get_manager(host, community)
Discover... |
iitis/PyLTEs | pyltes/powerConfigurator.py | Python | mit | 5,818 | 0.007047 | __author__ = 'mslabicki'
import pygmo as pg
#
from pyltes.powerOptimizationP | roblemsDef import maximalThroughputProblemRR
from pyltes.powerOptimizationProblemsDef import local_m | aximalThroughputProblemRR
from pyltes.powerOptimizationProblemsDef import maximalMedianThrProblemRR
from pyltes.powerOptimizationProblemsDef import local_maximalMedianThrProblemRR
from pyltes.powerOptimizationProblemsDef import minInterQuartileRangeroblemRR
from pyltes.powerOptimizationProblemsDef import local_minI... |
armando-migliaccio/neutron | neutron/plugins/cisco/network_plugin.py | Python | apache-2.0 | 17,219 | 0.000116 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache... | quest,
cexc.PortVnicNotFound: wexc.HTTPNotFound}
def __init__(self):
"""Load the model class."""
self._model = importutils.import_object(config.CISCO.model_class)
if hasattr(self._model, "MANAGE_STATE") and self._model.MANAGE_STATE:
self._maste | r = False
LOG.debug(_("Model %s manages state"), config.CISCO.model_class)
native_bulk_attr_name = ("_%s__native_bulk_support"
% self._model.__class__.__name__)
self.__native_bulk_support = getattr(self._model,
... |
googleapis/python-bigquery | google/cloud/bigquery/iam.py | Python | apache-2.0 | 1,554 | 0 | # Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BigQuery API IAM policy definitions
For all allowed roles and permissions, see:
https://cloud.google.com/bigquery/docs/access-control
"""
# BigQuery-specific IAM roles available... | ssions to
read and update data and metadata for the table or view."""
BIGQUERY_DATA_OWNER_ROLE = "roles/bigquery.dataOwner"
"""When applied to a table or view, this role provides permissions to
read and update data and metadata for the table or view, share the
table/view, and delete the table/view."""
BIGQUERY_DATA_V... |
paperrune/Neural-Networks | History/Batch-Normalization/Tensorflow.py | Python | mit | 4,020 | 0.00995 | import numpy as np
import tensorflow as tf
import time
batch_size = 128
decay = 0.99
epochs = 20
learning_rate = 0.5
is_training = tf.placeholder(tf.bool)
# input image dimensions
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_... | hesis, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ | ops):
train = optimizer.minimize(cost)
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1)), tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
start_time = time.time()
iterations = 0
for step in range(epochs):
... |
aptech/gsoop | setup.py | Python | mit | 1,966 | 0.027467 | #!/usr/bin/env python
"""
setup.py file for GAUSS Engine Python bindings
For building Python extension _ge.so
"""
import os
import sys
from setuptools import setup, Extension
lib_dir = os.environ.get("MTENGHOME")
if not lib_dir:
print("Please set your MTENGHOME environment variable. Aborting.")
sys.exit(1... | .cpp",
"src/gesymbol.cpp"]
include_dirs = ["include", "src"] + ([lib_dir + "/pthreads"] if is_win else [])
library_dirs = [lib_dir]
define_macros = [("GAUSS_LIBRARY", None)]
extra_compile_args = ["-std=c++11"] if not is_win else None
swig_opts = ["-c++"] + (["-py3"] | if sys.version_info >= (3,0) else [])
def mk_extension(ge_suffix=''):
return Extension("_ge{}".format(ge_suffix),
sources = sources + ['ge{}.i'.format(ge_suffix)],
include_dirs = include_dirs,
library_dirs = [lib_dir],
libraries = ["mteng{}".format(ge_suffix)] + (["pthreadVC... |
wwfifi/uliweb | uliweb/__init__.py | Python | bsd-2-clause | 1,358 | 0.0162 | ####################################################################
# Author: Limodou@gmail.com
# License: BSD
####################################################################
__author__ = 'limodou'
__author_email__ = 'limodou@gmail.com'
__url__ = 'https://github.com/limodou/uliweb'
__license__ = 'BSD'
v... | _file__)
sys.path.insert(0, os.path.join(workpath, 'lib'))
class UliwebError(Exception): pass
from .core.SimpleFrame import (Request, Response, redirect, Redirect, error, json, jsonp,
POST, GET, url_for, expose, get_app_dir, get_apps, function, Finder, decorators,
functions, response, request, ... | Middleware(object):
ORDER = 500
def __init__(self, application, settings):
self.application = application
self.settings = settings
#jupyter extension support
#you should use %load_ext uliweb to load it
#it'll add settings, functions, application to global environment
def load_i... |
Orav/kbengine | kbe/src/lib/python/Lib/wsgiref/__init__.py | Python | lgpl-3.0 | 610 | 0 | """wsgiref -- a WSGI (PEP 3333) Reference Library
Current Contents:
* util -- Miscellaneous useful functions and wrappers
* headers -- Manage response headers
* handlers -- base classes for server/gateway implementations
* simple_server -- a simple BaseHTTPServer that supports WSGI
* validate -- valid... | n wrapper that sits between an app and a server
| to detect errors in either
To-Do:
* cgi_gateway -- Run WSGI apps under CGI (pending a deployment standard)
* cgi_wrapper -- Run CGI apps under WSGI
* router -- a simple middleware component that handles URL traversal
"""
|
spectralDNS/shenfun | shenfun/la.py | Python | bsd-2-clause | 43,062 | 0.000999 | r"""
This module contains linear algebra solvers for SparseMatrices,
TPMatrices and BlockMatrices.
"""
import numpy as np
from numbers import Number, Integral
from scipy.sparse import spmatrix, kron
from scipy.sparse.linalg import spsolve, splu
from scipy.linalg import solve_banded
from shenfun.config import config
fro... | b[s].reshape((N, P))
| if b.dtype.char in 'fdg' or self.dtype in 'FDG':
u[s] = lu.solve(br).reshape(u[s].shape)
else:
u.real[s] = lu.solve(br.real).reshape(u[s].shape)
u.imag[s] = lu.solve(br.imag).reshape(u[s].shape)
if axis > 0:
u = np.moveaxis(u, 0,... |
digitalprime/pastebunker | pastebunker/views.py | Python | mit | 6,040 | 0.022185 | from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import *
from pyramid.security import authenticated_userid
from pyramid.security import forget
from pyramid.security import remember
from sqlalchemy.exc import DBAPIError
from sq... | HTTPFound(self.request.route_url('public', id=short_url.encode_url(post.id)))
else:
return HTTPFound(self.request.route_url('private', id=short_url.encode_url(post.id)))
return {'title': self.re | quest.registry.settings['title']}
except Exception:
raise
#return HTTPFound(self.request.route_url("index"))
class MarkdownView():
def __init__(self, request, in_file):
self.request = request
self.file = in_file
@view_config(request_method='GET')
def get(self):
try:
with open(self.file, "r") as f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.