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 |
|---|---|---|---|---|---|---|---|---|
ProkopHapala/SimpleSimulationEngine | python/pySimE/space/exp/OrbitalTransferOpt/OrbOpt_map/OrbitalTransfer_non_uniform.py | Python | mit | 8,038 | 0.046778 | #!/usr/bin/env python
from pylab import *
from Simplex_optimization import Simplex
from ClampedCubicSpline import *
from Random_optimization import MCBias_Run,MCBias2_Run
nnodes = 12
nsplines = nnodes + 1
perNode = 10
nsamp = (nsplines)*perNode
Gen= [0.0]*2*nnodes
def R2omega(R):
return sqrt(1.0/R*... | istory)>2:
GenHistory = transpose(array(GenHistory ))
subplot(2,5,10);
for i in range(nnodes):
plot( GenHistory[i ]-Gen0[i ], 'r-' );
plot( GenHistory[i+nnodes]-Gen0[i+nnodes], 'b-' );
#legend( bbox_to_anchor=(0.5, 1.00, 1., 0.000) )
ts, Os,Rs,Fs = evalGen( ti, Gen)
subpl... | ts, Os,Rs,Fs = evalGen( ti, GenRnd)
subplot(2,5,5); plot( ts, Fs[4], 'g-', lw=2 ); grid()
print " Initial gen ", Gen0
print " final gen ", Gen
savefig("plost.png", bbox_inches='tight')
'''
figure(num=None, figsize=(20, 5))
plotMaps(0,2, Gen0)
plotMaps(1,2, Gen )
savefig("valley.png", bbox_inches='tight')
'''
sh... |
annoviko/pyclustering | pyclustering/cluster/tests/unit/ut_xmeans.py | Python | gpl-3.0 | 23,984 | 0.004128 | """!
@brief Unit-tests for X-Means algorithm.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import unittest
# Generate images without having a window appear.
import matplotlib
matplotlib.use('Agg')
from pyclustering.cluster.tests.xmeans_templates im... | erAllocationSampleSimple1MetricMinkowski4(self):
metric = distance_metric(type_metric.MINKOWSKI, degree=4)
| XmeansTestTemplates.templateLengthProcessData(SIMPLE_SAMPLES.SAMPLE_SIMPLE1, [[3.7, 5.5], [6.7, 7.5]], [5, 5], splitting_type.BAYESIAN_INFORMATION_CRITERION, 20, False, metric=metric)
def testBicClusterAllocationSampleSimple1MetricCanberra(self):
metric = distance_metric(type_metric.CANBERRA)
... |
BillGuard/cabot | cabot/cabotapp/graphite.py | Python | mit | 2,507 | 0.000399 | from django.conf import settings
import requests
import logging
graphite_api = settings.GRAPHITE_API
user = settings.GRAPHITE_USER
password = settings.GRAPHITE_PASS
graphite_from = settings.GRAPHITE_FROM
auth = (user, password)
def get_data(target_pattern):
resp = requests.get(
graphite_api + 'render', a... | ['is_leaf']) == 1:
metrics.append(obj['path'])
else:
get_leafs_of_node(obj['path'])
get_leafs_of_node('')
return metrics
def parse_metric(metric, mins_to_check=5):
"""
Returns dict with:
- num_series_with_data: Number of series with data
- num_series... | : 0,
'num_series_no_data': 0,
'error': None,
'all_values': [],
'raw': ''
}
try:
data = get_data(metric)
except requests.exceptions.RequestException, e:
ret['error'] = 'Error getting data from Graphite: %s' % e
ret['raw'] = ret['error']
logging.... |
rzhxeo/youtube-dl | youtube_dl/extractor/__init__.py | Python | unlicense | 17,033 | 0.000059 | from __future__ import unicode_literals
from .abc import ABCIE
from .abc7news import Abc7NewsIE
from .academicearth import AcademicEarthCourseIE
from .addanime import AddAnimeIE
from .adobetv import AdobeTVIE
from .adultswim import AdultSwimIE
from .aftonbladet import AftonbladetIE
from .aljazeera import AlJazeeraIE
f... | .flickr import FlickrIE
from .folketinget import FolketingetIE
from .fourtube import FourTubeIE
from .foxgay import FoxgayIE
from .foxnews import FoxNewsIE
from .franceculture import FranceCultureIE
from .franceinter import FranceInterIE
from .francetv import (
PluzzIE,
FranceTvInfoIE,
FranceTVIE,
Gene... | freevideo import FreeVideoIE
from .funnyordie import FunnyOrDieIE
from .gamekings import GamekingsIE
from .gameone import (
GameOneIE,
GameOnePlaylistIE,
)
from .gamespot import GameSpotIE
from .gamestar import GameStarIE
from .gametrailers import GametrailersIE
from .gdcvault import GDCVaultIE
from .generic im... |
looker-open-source/sdk-codegen | examples/python/cloud-function-user-provision/main.py | Python | mit | 4,360 | 0.016743 | """This Cloud Function leverages Looker Python SDK to manage user provision.
It takes an email address as an input, then checks if this email has been
associated with an existing Looker user. If a current user is found, then an
email to reset the password will be sent. Otherwise, a new user will be created,
and a s... | [])
email = values[0][0]
return email
# [END main_gsheet(request)]
# [START looker_user_provision]
def looker_user_provision(email):
user_id = search_users_by_email(email=email)
if user_id is not None:
sdk.send_user_credentials_email_password_reset(user_id=user_id)
return f'A user with this email: {... | :
create_users(email=email)
return f'New user created; Setup/Welcome email sent to {email}.'
def search_users_by_email(email):
"""An email can only be assigned to one user in a Looker instance.
Therefore, search_user(email=test@test.com) will result in either
an empty dictionary, or a dictionary contai... |
HopeFOAM/HopeFOAM | ThirdParty-0.1/ParaView-5.0.1/VTK/Rendering/Core/Testing/Python/CamBlur.py | Python | gpl-3.0 | 1,969 | 0.00965 | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtk | Renderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create the piplinee, ball and spikes
sphere = vtk.vtkSphereSource()
sphere.SetThetaResolution(7)
sphere.SetPhiResolution(7)
sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInpu... | Mapper)
cone = vtk.vtkConeSource()
cone.SetResolution(5)
glyph = vtk.vtkGlyph3D()
glyph.SetInputConnection(sphere.GetOutputPort())
glyph.SetSourceConnection(cone.GetOutputPort())
glyph.SetVectorModeToUseNormal()
glyph.SetScaleModeToScaleByVector()
glyph.SetScaleFactor(0.25)
spikeMapper = vtk.vtkPolyDataMapper()
spikeMa... |
metamx/Diamond | src/collectors/elasticsearch/elasticsearch.py | Python | mit | 11,323 | 0.001148 | # coding=utf-8
"""
Collect the elasticsearch stats for the local node
#### Dependencies
* urlib2
"""
import urllib2
import re
try:
import json
json # workaround for pyflakes issue #13
except ImportError:
import simplejson as json
import diamond.collector
RE_LOGSTASH_INDEX = re.compile('^(.*)-\d\d\... | metric_path = '%s.%s' % (prefix, key)
| self._set_or_sum_metric(metrics, metric_path, value)
def _copy_two_level(self, metrics, prefix, data, filter=lambda key: True):
for key1, d1 in data.iteritems():
self._copy_one_level(metrics, '%s.%s' % (prefix, key1), d1, filter)
def _index_metrics(self, metrics, prefix, index):
... |
Dangetsu/vnr | Frameworks/Sakura/py/libs/lingoes/lingoesparse.py | Python | gpl-3.0 | 6,775 | 0.020245 | # coding: utf8
# lingoesparse.py
# 1/15/2013 jichi
#
# LD2 and LDX
# http://code.google.com/p/lingoes-extractor/source/browse/trunk/src/cn/kk/extractor/lingoes/LingoesLd2Extractor.java
# https://code.google.com/p/dict4cn/source/browse/trunk/importer/src/LingoesLd2Reader.java
# http://devchina.wordpress.com/2012/03/01/l... | treams = [] #[ int]
while (it + pos) < limit:
it = byteutil.toint(data, pos)
pos += 4
deflateStreams.append(it)
inflatedBytes = _inflate(data, deflateStreams, pos) # [byte]
if inflatedBytes:
return _ex | tract(inflatedBytes, inflatedWordsIndexLength, inflatedWordsIndexLength + inflatedWordsLength, *args, **kwargs)
#final int offsetCompressedData = data.position()
#System.out.println("索引词组数目:" + definitions)
#System.out.println("索引地址/大小:0x" + Integer.toHexString(offsetIndex) + " / " + (offsetCompressedDataHeader ... |
covrom/django_sample | mysite/mysite/settings.py | Python | mit | 3,237 | 0.002162 | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... | /settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': '... | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'Europe/Moscow'
... |
s0lst1c3/eaphammer | local/hostapd-eaphammer/tests/hwsim/test_wpas_ctrl.py | Python | gpl-3.0 | 96,304 | 0.00216 | # wpa_supplicant control interface
# Copyright (c) 2014, Qualcomm Atheros, Inc.
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
from remotehost import remote_compatible
import logging
logger = logging.getLogger()
import os
import socket
import subprocess
import t... | ("scan_ssid", "1"),
("bssid", "00:11:22:33:44:55"),
("proto", "WPA RSN OSEN"),
("eap", "TLS"),
("go_p2p_dev_addr", "22:33:44:55:66:aa"),
("p2p_client_list", "22:33:44:55:66:bb 02:11:22:33:44:55")]
if "SAE" not in dev[0].get_capabil | ity("auth_alg"):
tests.append(("key_mgmt", "WPS OSEN"))
else:
tests.append(("key_mgmt", "WPS SAE FT-SAE OSEN"))
dev[0].set_network_quoted(id, "ssid", "test")
for field, value in tests:
dev[0].set_network(id, field, value)
res = dev[0].get_network(id, field)
if res !=... |
great-expectations/great_expectations | great_expectations/datasource/simple_sqlalchemy_datasource.py | Python | apache-2.0 | 3,666 | 0.002182 | import copy
import logging
from great_expectations.datasource.data_connector.configured_asset_sql_data_connector import (
ConfiguredAssetSqlDataConnector,
)
from great_expectations.datasource.new_datasource import BaseDatasource
logger = logging.getLogger(__name__)
class SimpleSqlalchemyDatasource(BaseDatasourc... | ction: dict = None,
tables: dict = None,
**kwargs
):
introspection = introspection or {}
tables = tables or {}
self._execution_engine_config | = {
"class_name": "SqlAlchemyExecutionEngine",
"connection_string": connection_string,
"url": url,
"credentials": credentials,
"engine": engine,
}
self._execution_engine_config.update(**kwargs)
super().__init__(name=name, execution_e... |
leppa/home-assistant | homeassistant/components/hp_ilo/sensor.py | Python | apache-2.0 | 6,330 | 0.000316 | """Support for information from HP iLO sensors."""
from datetime import timedelta
import logging
import hpilo
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST,
CONF_MONITORED_VARIABLES,
CONF_NAME,
CONF_PASSWORD,
CONF_P... | ": ["Server FQDN", "get_server_fqdn"],
"server_host_data": ["Server Host Data", "get_host_data"],
"server_oa_info": ["Server Onboard Administrator Info", "get_oa_info"],
"server_power_status": ["Server Power state", "get_host_power_status"],
"server_power_readings": ["Server Power readings", "get_power_... | _tag"],
"server_uid_status": ["Server UID light", "get_uid_status"],
"server_health": ["Server Health", "get_embedded_health"],
"network_settings": ["Network Settings", "get_network_settings"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Require... |
Tooblippe/pandapower_gui | resources/ui/builder.py | Python | bsd-3-clause | 35,136 | 0.00296 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'builder.ui'
#
# Created: Mon May 22 10:30:45 2017
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_pandapower(object):
def setupUi(s... | w, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 170, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
bru | sh = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.In... |
astroML/astroML | astroML/datasets/moving_objects.py | Python | bsd-2-clause | 4,948 | 0 | import os
from gzip import GzipFile
from io import BytesIO
import numpy as np
from .tools import download_with_progress_bar
from . import get_data_home
DATA_URL = ('https://github.com/astroML/astroML-data/raw/main/datasets/'
'ADR3.dat.gz')
ARCHIVE_FILE = 'moving_objects.npy'
ADR4_dtype = [('moID', 'a6')... | sed in
Parker et al. 2008
Returns
-------
data : recarray, shape = (??,)
record array containing 60 values for each item
Notes
-----
See http://www.astro.washington.edu/users/ivezic/sdssmoc/sdssmoc3.html
Columns 0, 3 | 5, 45, and 56 are left out of the fetch: they are string
parameters. Only columns with known orbital parameters are saved.
Examples
--------
>>> from astroML.datasets import fetch_moving_objects
>>> data = fetch_moving_objects() # doctest: +IGNORE_OUTPUT +REMOTE_DATA
>>> # number of objects
... |
diegoguimaraes/django | tests/utils_tests/test_dateparse.py | Python | bsd-3-clause | 2,232 | 0.003584 | from __future__ import unicode_literals
from datetime import date, time, datetime
import unittest
from django.utils.dateparse import parse_date, parse_time, parse_datetime
from django.utils.timezone import get_fixed_timezone
class DateParseTests(unittest.TestCase):
def test_parse_date(self):
# Valid in... | al(parse_datetime('20120423091500'), None) |
self.assertRaises(ValueError, parse_datetime, '2012-04-56T09:15:90')
|
carojasq/Evaluaciones-bases-de-datos-2 | models/administrador.py | Python | mit | 3,310 | 0.038671 | from config import Config
from models.usuario import Usuario
class Administrador:
tabla = "administradores"
def __init__(self, identificador):
self.id = identificador
self.privilegios = Usuario.getTipo(self.id)
'''
#actualizar (se puede actualizar un administrador actualizando como usuario)
def save(self):
... | r_ciudad_id =%s WHERE id=%s" % (Usuario.tabla, self.nombre_completo, self.usuario, self.contrasena,self.e_mail,self.dr_ciudad_id,self.id)
cursor = Config.getCursor()
try:
cursor.execute(query)
except Exception, e:
print e
print "No es posible actualizar el registro"
return None
return self
'''
... | ficador) == None :
print "El usuario no existe, no se puede crear el administrador"
return None;
else:
query = " INSERT INTO %s (id) VALUES (%s) RETURNING id " % (Administrador.tabla, str(int(identificador)))
cursor = Config.getCursor()
try:
cursor.execute(query)
except Exception, e:
print... |
v-iam/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/subnet_association.py | Python | mit | 1,260 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Micr | osoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# ----------------------------------... | nd its custom security rules.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Subnet ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules: list of :class:`SecurityRule
<azure.mgmt.network.v2... |
SamuelTM/univapi | stm/univapi/modelos/boleto.py | Python | mit | 357 | 0.002801 | class Boleto:
def __init__ | (self, ano_mes, vencimento, mensalidade, dependencia, desconto, liquido, situacao):
self.ano_mes = ano_mes
self.vencimento = vencimento
self.mensalidade = | mensalidade
self.dependencia = dependencia
self.desconto = desconto
self.liquido = liquido
self.situacao = situacao
|
wrouesnel/ansible | lib/ansible/modules/cloud/ovirt/ovirt_hosts.py | Python | gpl-3.0 | 22,692 | 0.001719 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | ent', 'absent', 'maintenance', 'upgraded', 'started',
'restarted', 'stopped', 'reinstalled', 'iscsidiscover', 'iscsilogin'
| ]
default: present
comment:
description:
- "Description of the host."
cluster:
description:
- "Name of the cluster, where host should be created."
address:
description:
- "Host address. It can be either FQDN (preferred) or IP address."
... |
google/brax | brax/envs/env.py | Python | apache-2.0 | 2,766 | 0.011931 | # Copyright 2022 The Brax Authors.
#
# 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 wri... | nvironment for training and inference."""
import abc
from typing import Any, Dict, Optional
import brax
from brax import jumpy as jp
from flax import struct
from google.protobuf import text_format
@struct.dataclass
class State:
"""Environment state for training and inference."""
qp: brax.QP
obs: jp.ndarray
... | t_factory=dict)
class Env(abc.ABC):
"""API for driving a brax system for training and inference."""
def __init__(self, config: Optional[str]):
if config:
config = text_format.Parse(config, brax.Config())
self.sys = brax.System(config)
@abc.abstractmethod
def reset(self, rng: jp.ndarray) -> S... |
JDSchmitzMedia/pydev | pysrc/tests_python/test_debugger.py | Python | epl-1.0 | 30,357 | 0.013605 | '''
The idea is that we record the commands sent to the debugger and reproduce them from this script
(so, this works as the client, which spawns the debugger as a separate process and communicates
to it as if it was run from the outside)
Note that it's a python script but it'll spawn a process to r... | ceived.split('"')
threadId = splitted[1]
frameId = splitted[5]
| if get_line:
return threadId, frameId, int(splitted[11])
return threadId, frameId
def WaitForVars(self, expected):
i = 0
#wait for hit breakpoint
while not expected in self.readerThread.lastReceived:
i += 1
time.sleep(1)
... |
JulyKikuAkita/PythonPrac | cs15211/VerifyPreorderSequenceinBinarySearchTree.py | Python | apache-2.0 | 4,042 | 0.003711 | __source__ = 'https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/description/'
# http | s://github.co | m/kamyu104/LeetCode/blob/master/Python/verify-preorder-sequence-in-binary-search-tree.py
# Time: O(n)
# Space: O(1)]
# Stack
#
# Description: Leetcode # 255. Verify Preorder Sequence in Binary Search Tree
#
# Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tre... |
redox-alpha/omorfi | src/python/generate-lexcs.py | Python | gpl-3.0 | 14,293 | 0.00063 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
This script generates Finnish omorfi database to lexc format, given that
they contain at least following information for each word:
* the word lemma or the dictionary form
* the word inflection classification in one of the known format.
Additional data may be av... | ("--none-lemmas", action="store_true", default=False,
help="include lemmas in raw analyses")
ap.add_argument("--none-segments", action="store_true", default=False,
help="include segments in raw analyses")
args = ap.parse_args()
formatter = None
if args.format == ... | atter(args.verbose, new_para=args.omor_new_para,
allo=args.omor_allo, props=args.omor_props, sem=args.omor_sem)
elif args.format == 'ftb3':
formatter = Ftb3Formatter(args.verbose)
elif args.format == 'apertium':
formatter = ApertiumFormatter(args.verbose)
el... |
cgcgbcbc/django-xadmin | xadmin/views/base.py | Python | bsd-3-clause | 20,760 | 0.001541 | import sys
import copy
import functools
import datetime
import decimal
from functools import update_wrapper
from inspect import getargspec
from django import forms
from django.utils.encoding import force_unicode
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import Val... | rse(
'%s:%s_%s_%s' % (self.admin_site.app_name, model._meta.app_label,
model._meta.module_name, name),
args=args, kwargs=kwargs, current_app=self.admin_site.name)
def get_model_perm(self, model, name):
return '%s.%s_%s' % (model._meta.app_label, name, mo... | eturn user.has_perm(self.get_model_perm(model, name)) or (name == 'view' and self.has_model_perm(model, 'change', user))
def get_query_string(self, new_params=None, remove=None):
if new_params is None:
new_params = {}
if remove is None:
remove = []
p = dict(self.requ... |
cloud-io/CloudUp | tests/test_my_views.py | Python | mit | 8,048 | 0.003106 | from test_utils import testCaseSetUp
from test_utils import testCaseTearDown
from test_utils import getUnitTestUserEmail
from src.models import Host
from src.models import Link
from src.models import UserHasLink
from src.memcache_utils import MemCacheKeyGen
from src.error_message import ErrorMessages
import urllib2
i... | Link(id=linkUrl, parent=ndb.Key('Host', self.hostName)).put()
params = {
'url': linkUrl,
'host': self.hostNameB,
}
query = urllib.urlencode(params)
response = self.testapp.get('/my/link/add?' + query)
# Checks return page.
self.assertEqual(response.status_int, 302)
self.assertE... | 'Host', self.hostNameB, 'Link', linkUrl).get()
self.assertIsNotNone(link)
def testAddLinkShouldInvalidateCacheForLinksOfGiveHostAndAllLinks(self):
memcache.set(MemCacheKeyGen.getLinksKey(self.hostName), [])
memcache.set(MemCacheKeyGen.getAllLinksKey(), [])
linkUrl = 'http://heroku-on.appspot.com'
... |
mabuchilab/Instrumental | instrumental/drivers/motion/_kinesis/common.py | Python | gpl-3.0 | 2,398 | 0.002085 | from enum import Enum
# Message Enums
#
class MessageType(Enum):
GenericDevice = 0
GenericPiezo = 1
GenericMotor = 2
GenericDCMotor = 3
GenericSimpleMotor = 4
RackDevice = 5
Laser = 6
TECCtlr = 7
Quad = 8
NanoTrak = 9
Specialized = 10
Solenoid = 11
class GenericDevice... | d = 3
class GenericDCMotor(Enum):
Error = 0
Status = 1
MessageIDs = {
MessageType.GenericDevice: GenericDevice,
MessageType.GenericMotor: GenericMotor,
MessageType.GenericDCMotor: GenericDCMotor
}
class KinesisError(Exception):
messages = {
0: 'Success',
1: 'The FTDI functi... | ',
2: 'The device could not be found. Make sure to call TLI_BuildDeviceList().',
3: 'The device must be opened before it can be accessed',
4: 'An I/O Error has occured in the FTDI chip',
5: 'There are insufficient resources to run this application',
6: 'An invalid parameter has b... |
ghchinoy/tensorflow | tensorflow/contrib/learn/python/learn/datasets/base.py | Python | apache-2.0 | 8,304 | 0.006142 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | h is None:
module_path = path.dirname(__file__)
data_path = path.join(module_path, 'data', 'boston_house_prices.csv')
return load_csv_with_header(
data_path, target_dtype=np.float, features_dtype=np.float)
@deprecated(None, 'Use the retry module or similar alternatives.')
def retry(initial_delay,
... | 0.25,
is_retriable=None):
"""Simple decorator for wrapping retriable functions.
Args:
initial_delay: the initial delay.
max_delay: the maximum delay allowed (actual max is
max_delay * (1 + jitter).
factor: each subsequent retry, the delay is multiplied by this value.
(must be ... |
wangyifan1985/sampan | sampan/properties.py | Python | mit | 5,148 | 0.00136 | #!/usr/bin/env python
# coding: utf-8
import re
import sys
import typing
import time
from collections import OrderedDict, abc
""" A Python implementation for java.util.Properties """
__all__ = ['Properties']
# Constants ###################################################################
###########################... | default properties type: {type(defaults)}')
| def __setitem__(self, key, value):
self.setProperty(key, value)
def __getitem__(self, key):
return self.getProperty(key)
def __getattr__(self, name):
try:
return self.__dict__[name]
except KeyError:
if hasattr(self._props, name):
retur... |
javierrodriguezcuevas/git-cola | test/models_selection_test.py | Python | gpl-2.0 | 515 | 0 | from __future__ import absolute_import, division, unicode_literals
import unittest
import mock
from cola.models import selection
class SelectionTestCase(unittest.TestCase):
def test_union(self):
t = mock.Mock()
t.staged = ['a']
t.unmerged = ['a', 'b']
t.modified = ['b', 'a', 'c'... |
if __name__ == | '__main__':
unittest.main()
|
thedod/redwind | migrations/20141017-permalinks.py | Python | bsd-2-clause | 531 | 0 | from redwind import app, db, util
from redwind.models import Post
import itertools
db.engine.execute('alter table post add column historic_path varchar(256)')
db.engine. | execute('update post set historic_path = path')
for post in Post.query.all():
print(post.historic_path)
if | not post.slug:
post.slug = post.generate_slug()
post.path = '{}/{:02d}/{}'.format(post.published.year,
post.published.month,
post.slug)
db.session.commit()
|
ACJTeam/enigma2 | e2reactor.py | Python | gpl-2.0 | 5,223 | 0.036378 | # enigma2 reactor: based on pollreactor, which is
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Maintainer: U{Felix Domke<mailto:tmbinc@elitedvb.net>}
"""
# System imports
import select, errno, sys
# Twisted imports
from twisted.python import log, failure
from twisted.interne... | se fileno() may disappear at any
# moment, thanks to python's underlying sockets impl
for fd, fdes in selectables.items():
if selectable is fdes:
break
else:
# Hmm, maybe not the right course of action? This method can't
# fail, because it happens inside error detection...
return
if fd ... | ef addReader(self, reader):
"""Add a FileDescriptor for notification of data available to read.
"""
fd = reader.fileno()
if fd not in reads:
selectables[fd] = reader
reads[fd] = 1
self._updateRegistration(fd)
def addWriter(self, writer, writes=writes, selectables=selectables):
"""Add a FileDescrip... |
jamesbdunlop/tk-jbd-submit-mayaplayblast | python/lib/renderGlobals.py | Python | apache-2.0 | 197 | 0.010152 | import maya.cmds as | cmds
def setRenderGlobals():
" | ""
Sets the base defaults for the renderglobals for playblasting.
"""
print 'Set your custom renderglobals here for playblasting.' |
jcsp/manila | manila/api/openstack/wsgi.py | Python | apache-2.0 | 44,832 | 0.000022 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | """Determine content type of the request body.
Does not do any body introspection, only checks header.
"""
if "Content-Type" not in self.headers:
return None
allowed_types = SUPPORTED_CONTENT_TYPES
content_type = self.content_type
| if content_type not in allowed_types:
raise exception.InvalidContentType(content_type=content_type)
return content_type
def set_api_version_request(self):
"""Set API version request based on the request header information.
Microversions starts with /v2, so if a client sends... |
vinc3nt/freepto-web | manage.py | Python | gpl-2.0 | 842 | 0.002375 | #!/usr/bin/env python
from flask.ext.script import Manager
from flask_frozen import Freezer
import discovery
import logging
out = logging.StreamHandler()
out.set | Formatter(logging.Formatter())
out.setLevel(logging.DEBUG)
logging.getLogger('freepto-web').setLevel(logging.INFO)
logging.getLogger('freepto-web').addHandler(out)
from app import app
manager = Manager(app)
freezer = Freezer(app)
@freezer.register_generator
def index():
yield {}
@freezer.register_generator
d... | in discovery.lang_dirs:
yield {'lang': lang}
@freezer.register_generator
def page():
for lang in discovery.lang_dirs:
for title in discovery.find_pages(lang):
yield {'lang': lang, 'title': title}
@manager.command
def freeze():
freezer.freeze()
if __name__ == "__main__":
mana... |
andymccurdy/tested-transcoder | transcoder.py | Python | mit | 12,971 | 0.000463 | #!/usr/bin/python
import logging
import os
import re
import shlex
import shutil
import signal
import subprocess
import sys
import time
def non_zero_min(values):
"Return the min value but always prefer non-zero values if they exist"
if len(values) == 0:
raise TypeError('non_zero_min expected 1 argumen... | return
# move the completed output to the output directory
self. | logger.info('Moving completed work output %s to output directory',
os.path.basename(work_path))
output_path = os.path.join(self.OUTPUT_DIRECTORY,
os.path.basename(work_path))
shutil.move(work_path, output_path)
shutil.move(work_path + '... |
dpattiso/igraph | lama/translate/translate_old.py | Python | gpl-2.0 | 31,909 | 0.007083 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
from collections import defaultdict
from copy import deepcopy
import axiom_rules
import fact_groups
import instantiate
import pddl
import sas_tasks
import simplify
import timers
# TODO: The translator may generate trivial derived v... | e to weaker relevance analysis (see issue7).
ADD_IMPLIED_PRECONDITIONS = False
removed_implied_effect_counter = 0
simplified_effect_condition_counter = 0
added_implied_precondition_counter = 0
def strips_to_sas_dictionary(groups, assert_partial):
dictionary = {}
for var_no, group in enumerate(groups):
... | for sas_pairs in dictionary.itervalues())
return [len(group) + 1 for group in groups], dictionary
def translate_strips_conditions_aux(conditions, dictionary, ranges):
condition = {}
for fact in conditions:
if fact.negated:
# we handle negative conditions later, because then we
... |
f4ble/Arkon | configs/tasks_default.py | Python | apache-2.0 | 707 | 0.007072 | from ark.tasks.task_check_for_update import Task_CheckForUpdates
from ark.tasks.task_list_players import Task_ListPlayers
from ark.tasks.task_get_chat import Task_Get | Chat
from ark.tasks.task_daily_restart import Task_DailyRestart
from ark.tasks.task_daily_restart import Task_DailyRestartRepopulate
from ark.tasks.task_sql_keep_alive import Task_SQL_keep_alive
def init():
#Part of Core Features:
Task_ListPlayers.run_interval(8,immediately=True)
Task_GetChat.run_interva... | :
Task_CheckForUpdates.run_interval(1800)
Task_DailyRestart.run_daily('15:00:00')
Task_DailyRestartRepopulate.run_daily('06:00:00')
|
asears/bloppit | gethot.py | Python | mit | 547 | 0.02925 | import sys
import praw
import unicodedata
user_agent='bloppit_app'
if len(sys.argv) == 2:
script, filename, subreddit = argv
else:
subreddit = "opensource"
filename = subreddit + ".txt"
r = praw.Reddit(user | _agent)
submissions = r.get_subreddit(subreddit).get_hot(limi | t=100)
target = open(filename, 'w')
for x in submissions:
line = (str(x.fullname) + ", " + str(x.title.encode("cp437","ignore"))[1:] + " , " + str(x.url.encode("cp437","ignore"))[1:].strip('"\''))
print(line)
target.write(line)
target.write("\n")
target.close()
|
JakeShulman/G-Neat | Connection.py | Python | apache-2.0 | 1,393 | 0.045226 | '''
Created on Feb 4, 2017
@author: Jake
'''
import numpy as np
import random
import Population
class Connection(object):
inNeuron = None
outNeuron = None
weight = None
enabled = None
ID = None
def __init__(self,ID,inNeuron,outNeuron,weight,enabled = True):
self.inNeuron = inNeuron... | lf.weight - Population.MUTATION_VALUE
def mutateEnable(self):
#switch the | enabled status of the connection
#WORRY ABOUT LATER CAN CAUSE BACK PROP PROBLEMS
self.enabled = not self.enabled
def copy(self):
return Connection(self.ID, self.inNeuron, self.outNeuron, self.weight)
def __eq__(self, other):
# if self.inNeuron != other.inNeuron: return False
# if self.outNeuron... |
sassoftware/mirrorball | updatebot/artifactory.py | Python | apache-2.0 | 11,601 | 0.000603 | #
# Copyright (c) SAS Institute, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License | for the specific language governing permissions and
# limitations under the License.
#
"""
Module for finding artifactory packages and updating them
"""
from collections import deque
import logging
import time
from conary import conarycfg
from rmake.build import buildcfg
from rmake.cmdline import helper
from . impo... |
marinkaz/orange3 | Orange/widgets/utils/__init__.py | Python | bsd-2-clause | 811 | 0.004932 | from functools import reduce
def vartype(var):
| if var.is_discrete:
return 1
elif var.is_con | tinuous:
return 2
elif var.is_string:
return 3
else:
return 0
def progress_bar_milestones(count, iterations=100):
return set([int(i*count/float(iterations)) for i in range(iterations)])
def getdeepattr(obj, attr, *arg, **kwarg):
if isinstance(obj, dict):
return obj.ge... |
ygol/odoo | addons/website_event_track_online/models/event_type.py | Python | agpl-3.0 | 551 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class EventType(models.Model):
_inherit = "event.type"
community_menu = fields.Boolean(
"Community Menu", compute= | "_compute_community_menu",
readonly=False, store=True,
help="Display community tab on website")
@api.depends('website_menu')
def _compute_community_menu(self):
for event_type in self:
event_type.community_menu = event_type.web | site_menu
|
StellarCN/py-stellar-base | stellar_sdk/xdr/ledger_close_meta_v0.py | Python | apache-2.0 | 5,160 | 0.000581 | # This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from typing import List
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .ledger_header_history_entry import LedgerHeaderHistoryEntry
from .scp_history_entry import SCPHistoryEntry
... | LedgerHeaderHistoryEntry ledgerHeader;
// NB: txSet is sorted in "Hash order"
TransactionSet txSet;
// NB: transactions are sorted in apply order here
// fees for all transactions are processed first
// followed by applying transactions
Trans... | information attached to the ledger close
SCPHistoryEntry scpInfo<>;
};
"""
def __init__(
self,
ledger_header: LedgerHeaderHistoryEntry,
tx_set: TransactionSet,
tx_processing: List[TransactionResultMeta],
upgrades_processing: List[UpgradeEntryMeta],
... |
jirikuncar/invenio-ext | tests/test_ext_registry.py | Python | gpl-2.0 | 2,613 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... | CULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc., |
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Test unit for the miscutil/mailutils module.
"""
from invenio_ext.registry import DictModuleAutoDiscoverySubRegistry
from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
from flask_registry import ImportPathRegistry, RegistryErro... |
CIGNo-project/CIGNo | cigno/mdtools/forms.py | Python | gpl-3.0 | 173 | 0.00578 | from models import Connection
from django import forms |
class ConnectionForm(forms.ModelForm):
class Meta:
model = Con | nection
exclude = ('d_object_id',)
|
e0ne/cinder | cinder/api/contrib/volume_transfer.py | Python | apache-2.0 | 8,571 | 0 | # Copyright 2011 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... | ]
| try:
accept = body['accept']
auth_key = accept['auth_key']
except KeyError:
msg = _("Incorrect request body format")
raise exc.HTTPBadRequest(explanation=msg)
LOG.info(_("Accepting transfer %s"), transfer_id,
context=context)
... |
Sinar/popit_ng | popit/tests/test_person_misc_api.py | Python | agpl-3.0 | 32,087 | 0.002961 | __author__ = 'sweemeng'
from rest_framework import status
from popit.signals.handlers import *
from popit.models import *
from popit.tests.base_testcase import BasePopitAPITestCase
class PersonLinkAPITestCase(BasePopitAPITestCase):
def test_view_person_link_list_unauthorized(self):
| response = self.client.get("/en/persons/ab1a5788e5bae95 | 5c048748fa6af0e97/links/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_view_person_link_list_authorized(self):
token = Token.objects.get(user__username="admin")
self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
response = self.client.get("/en/p... |
ParrotPrediction/pyalcs | lcs/strategies/anticipatory_learning_process.py | Python | mit | 1,363 | 0 | from lcs.strategies.subsumption import does_subsume
def add_classifier(child, population, new_list, theta_exp: int) -> None:
"" | "
Looks for subsuming / similar classifiers in the population of classifiers
and those created in the current ALP | run (`new_list`).
If a similar classifier was found it's quality is increased,
otherwise `child_cl` is added to `new_list`.
Parameters
----------
child:
New classifier to examine
population:
list of classifiers
new_list:
A list of newly created classifiers in this A... |
shastah/spacewalk | spacewalk/certs-tools/rhn_bootstrap_strings.py | Python | gpl-2.0 | 16,095 | 0.001864 | #
# Copyright (c) 2008--2020 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | certificate is
# configured properly in the post section of your kickstart profiles (the
# Red Hat Satellite or hosted web user interface).
# UP2DATE/RHN_REGISTER VERSIONING NOTE:
# This script will not work with very old versions of up2date and |
# rhn_register.
echo
echo
echo "MINOR MANUAL EDITING OF THIS FILE MAY BE REQUIRED!"
echo
echo "If this bootstrap script was created during the initial installation"
echo "of a Red Hat Satellite, the ACTIVATION_KEYS, and ORG_GPG_KEY values will"
echo "probably *not* be set (see below). If this is the case, please d... |
tjcsl/cslbot | bot.py | Python | gpl-2.0 | 1,125 | 0.001778 | #!/usr/bin/env python3
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson
#
# 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 Softwa... | URPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import sys
import warnings
from os.path i... | re # noqa
if __name__ == '__main__':
core.init(dirname(abspath(__file__)))
|
horacioMartinez/dakara-client | tools/misc/traductor de indices y mapas/mapas/extra_data_generator/lluvia_extra_data_generator.py | Python | mit | 601 | 0.028286 | import json
import struct
import os
origen = open("./FK.ind", "rb")
destino = open("./extra_ | data","w")
origen.read(256 + 7) # saco header
cantidad_mapas = struct.unpack('<H', (origen.read(2)))[0] # l1
x = 1
while (x < cantidad_mapas +1):
# numero X = numero de mapa
lluvia = | struct.unpack('<B', (origen.read(1)))[0]
if (lluvia > 0):
lluvia = 1
destino.write(str(x)+"="+'"outdoor"'+":"+str(lluvia)+"\n")
x = x +1
#hay menos mapas aca que en la otra carpeta..
extra = 100
while (x < cantidad_mapas + 1 +extra):
destino.write(str(x)+"="+'"outdoor"'+":"+"0"+"\n")
x = x +1
destino.close() |
dimV36/webtests | run.py | Python | gpl-2.0 | 141 | 0.007092 | #!/u | sr/bin/env venv/bin/python
__author__ = 'dimv36'
from webtests | import app
if __name__ == "__main__":
app.debug = True
app.run() |
JensTimmerman/radical.pilot | src/radical/pilot/scheduler/interface.py | Python | mit | 2,025 | 0.014321 | #pylint: disable=C0301, C0103, W0212
"""
.. module:: radical.pilot.scheduler.Interface
:platform: Unix
:synopsis: The abstract interface class for all schedulers.
.. moduleauthor:: Ole Weidner <ole.weidner@rutgers.edu>
"""
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
... | -------------------------------------------------------------------------
#
def schedule (self, units) :
"""Schedules one or more ComputeUnits"""
raise RuntimeError ("scheduler %s does not implement 'pilot_removed()'" % self.name)
# --------------------------------------------------------... | ("scheduler %s does not implement 'unschedule()'" % self.name)
# -------------------------------------------------------------------------
#
@property
def name(self):
"""The name of the scheduler"""
return self.__class__.__name__
|
mrquim/repository.mrquim | script.module.pycryptodome/lib/Crypto/Hash/SHA1.py | Python | gpl-2.0 | 3,063 | 0.003265 | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... | ryptographic hash algorithm.
SHA-1_ produces the 160 bit digest of a message.
>>> from Crypto.Hash import SHA1
>>>
>>> h = SHA1.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Se | cure Hash Algorithm.
This algorithm is not considered secure. Do not use it for new designs.
.. _SHA-1: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
"""
__all__ = ['new', 'block_size', 'digest_size']
from Crypto.Util.py3compat import *
def __make_constructor():
try:
# The sha module i... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/sklearn/utils/_scipy_sparse_lsqr_backport.py | Python | mit | 18,021 | 0.000388 | """Sparse Equations and Least Squares.
The original Fortran code was written by C. C. Paige and M. A. Saunders as
described in
C. C. Paige and M. A. Saunders, LSQR: An algorithm for sparse linear
equations and sparse least squares, TOMS 8(1), 43--71 (1982).
C. C. Paige and M. A. Saunders, Algorithm 583; LSQR: Sparse... | p*I]]``.
acond : float
Estimate of ``cond(Abar | )``.
arnorm : float
Estimate of ``norm(A'*r - damp^2*x)``.
xnorm : float
``norm(x)``
var : ndarray of float
If ``calc_var`` is True, estimates all diagonals of
``(A'A)^{-1}`` (if ``damp == 0``) or more generally ``(A'A +
damp^2*I)^{-1}``. This is well defined if A ha... |
kingvuplus/ops | lib/python/Plugins/Extensions/PicturePlayer/ui.py | Python | gpl-2.0 | 22,711 | 0.027211 | from enigma import ePicLoad, eTimer, getDesktop, gMainDC, eSize
from Screens.Screen import Screen
from Tools.Directories import resolveFilename, pathExists, SCOPE_MEDIA, SCOPE_CURRENT_SKIN
from Components.Pixmap import Pixmap, MovingPixmap
from Components.ActionMap import ActionMap, NumberActionMap
from Components.So... | .KeyExit,
"red": self.KeyExit,
"green": self.KeyGreen,
"yellow": self.KeyYellow,
"menu": self.KeyMenu,
"ok": sel | f.KeyOk
}, -1)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Thumbnails"))
self["key_yellow"] = StaticText("")
self["label"] = StaticText("")
self["thn"] = Pixmap()
currDir = config.pic.lastDir.value
if not pathExists(currDir):
currDir = "/"
self.oldService = self.se... |
neithere/pyrant | pyrant/exceptions.py | Python | apache-2.0 | 1,671 | 0.007181 | # -*- coding: utf-8 -*-
"""
If you know error code, use `get_for_code(code)` to retrieve exception instance.
"""
__all__ = ['Success', 'InvalidOperation', 'HostNotFound', 'ConnectionRefused',
'SendError', 'ReceiveError', 'RecordExists', 'RecordNotFound',
'MiscellaneousError', 'get_for_code']
c... | eration,
2: HostNotFound,
3: ConnectionRefused,
4: SendError,
5: ReceiveError,
6: RecordExists,
7: RecordNotFound,
9999: MiscellaneousError,
}
def get_for_code(error_code, message=None):
try:
int(error_code)
except ValueError:
raise TypeError(u'Could not map error c... | xception class: expected '
'a number, got "%s"' % error_code)
else:
try:
cls = ERROR_CODE_TO_CLASS[error_code]
except KeyError:
raise ValueError('Unknown error code "%d"' % error_code)
else:
return cls(message) if message else cls(... |
vanceeasleaf/aces | aces/materials/MoN2_alpha_rect.py | Python | gpl-2.0 | 1,320 | 0.036364 | from aces.materials.POSCAR import structure as Material
class structure(Material):
def getPOSCAR(self):
return self.getMinimized()
def csetup(self):
from ase.dft.kp | oints import ibz_points
#self.bandpoints=ibz_points['hexagonal']
import numpy as np
x=0.5*np.cos(np.arange(8)/8.0*2.0*np.pi)
y=0.5*np.sin(np.arange(8)/8.0*2.0*np.pi)
self.bandpath=['Gamma']
for i in range(8):
if(np.abs(x[i])>0.2):x[i]/=np.abs(x[i])*2.0
if(np.abs(y[i])>0.2):y[i]/=np.abs(y[i... | end('X'+str(i))
self.bandpath.append('Gamma')
#self.bandpath=['Gamma',"X2"]
def getMinimized(self):
return """Mo N
1.0000000000000000
2.9916000366000000 0.0000000000000000 0.0000000000000000
0.0000000000000000 5.1814560994168932 0.0000000000000000
0.0000000000000000 0.0... |
almarklein/bokeh | bokeh/server/views/statics.py | Python | bsd-3-clause | 844 | 0.004739 |
import flask
| from ..app import bokeh_app
## This URL heirarchy is important, because of the way we build bokehjs
## the source mappings list the source file as being inside ../../src
| @bokeh_app.route('/bokehjs/static/<path:filename>')
def bokehjs_file(filename):
""" Return a specific BokehJS deployment file
:param filename: name of the file to retrieve
:status 200: file is found
:status 404: file is not found
"""
return flask.send_from_directory(bokeh_app.bokehjsdir, file... |
KenKundert/avendesora | avendesora/command.py | Python | gpl-3.0 | 59,621 | 0.001275 | # Commands
# License {{{1
# Copyright (C) 2016-2022 Kenneth S. Kundert
#
# 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... | turn '/commands.html#' + anchor
except (AttributeError, TypeError):
pass
# Add {{{1
class Add(Command):
| NAMES = 'add',
DESCRIPTION = 'add a new account'
USAGE = dedent("""
Usage:
avendesora add [options] [<template>]
Options:
-f <file>, --file <file>
Add account to specified accounts file.
Creates a new account starting from ... |
edoburu/django-oscar-docdata | oscar_docdata/urls.py | Python | apache-2.0 | 281 | 0.003559 | from django.conf.urls import url
from . | views import OrderReturnView, StatusChangedNotificationView
urlpatterns = [
url(r'^return/$', OrderReturnView.as_view(), name='return_url'),
url(r'^upd | ate_order/$', StatusChangedNotificationView.as_view(), name='status_changed'),
]
|
ashutosh-mishra/youtube-dl | youtube_dl/extractor/traileraddict.py | Python | unlicense | 2,278 | 0.00878 | import re
from .common import InfoExtractor
class TrailerAddictIE(InfoExtractor):
_VALID_URL = r'(?:http://)?(?:www\.)?traileraddict\.com/(?:trailer|clip)/(?P<movie>.+?)/(?P<trailer_name>.+)'
_TEST = {
u'url': u | 'http://www.traileraddict.com/trailer/prince-avalanche/trailer',
u'file': u'76184.mp4',
u'md5': u'57e39dbcf4142ceb8e1f242ff423fd71',
u'info_dict': {
u"title": u"Prince Avalanche Trailer",
u"description": u"Trailer for Prince Avalanche.Two highway road workers spend the su... | r of 1988 away from their city lives. The isolated landscape becomes a place of misadventure as the men find themselves at odds with each other and the women they left behind."
}
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
name = mobj.group('movie') + '/' + mob... |
sysadminmatmoz/pmis | analytic_plan_analysis/__manifest__.py | Python | agpl-3.0 | 633 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
'name': 'Analytic Plan-Actual Analysis',
'version': '10.0.1.1.0',
'author': 'Eficent, Odoo Community Association (OCA),'
'Proje... | data': [
'security/ir.model.access. | csv',
'report/account_analytic_plan_actual_view.xml',
],
'installable': False,
}
|
mreider/multi-user-encryption | app.py | Python | mit | 1,685 | 0.020178 | # -*- coding: utf-8 -*-
from flask import Flask,req | uest, jsonify
from dbmanager import Database
db = Database()
db.start_engine()
app = Flask(__name__)
@app.route('/api/v1.0/data',methods=['GET','POST'])
def index():
if request.method == 'GET':
#F | etch data
username = request.args.get('user','')
password = request.args.get('password','')
print 'Username = %s, password = %s'%(username,password)
content = db.get_data(username,password)
return jsonify(data=content)
elif request.method == 'POST':
#Update dat... |
irvingprog/gmusic | manage.py | Python | lgpl-3.0 | 256 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE | ", "downloadmusic.settings")
f | rom django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
rohitranjan1991/home-assistant | homeassistant/components/sonarr/const.py | Python | mit | 436 | 0 | """Constants for Sonarr."""
DOMAIN = "sonarr"
# Config Keys
CONF_BASE_PATH = "base_path"
CONF_DAYS = "days"
CONF_INCLUDED | = "include_paths"
CONF_UNIT = "unit"
CONF_UPCOMING_DAYS = "upcoming_days"
CONF_WANTED_MAX_ITEMS = "wanted_max_items"
# Data
DATA_HOST_CONFIG = "host_config"
DATA_SONARR = "sonarr"
DATA_SYSTEM_STATUS = "system_status"
# Defaults
DEFAULT_UPCOMING_DAYS = 1
DEFAULT_VERIFY_SSL = False
| DEFAULT_WANTED_MAX_ITEMS = 50
|
spulec/moto | tests/test_timestreamwrite/test_server.py | Python | apache-2.0 | 514 | 0 | import json
import sure # noqa # | pylint: disable=unused-import
import moto.server as server
from moto import mock_times | treamwrite
@mock_timestreamwrite
def test_timestreamwrite_list():
backend = server.create_backend_app("timestream-write")
test_client = backend.test_client()
headers = {"X-Amz-Target": "Timestream_20181101.ListDatabases"}
resp = test_client.post("/", headers=headers, json={})
resp.status_code.sho... |
mutarock/python-utils | compress/__init__.py | Python | mit | 53 | 0 | from | core import ungzip
from core import ungzip_ | html
|
dmsimard/ara | ara/clients/offline.py | Python | gpl-3.0 | 3,306 | 0.00121 | # Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA: Ansible Run Analysis.
#
# ARA 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 l... | self.server_thread.is_ready.wa | it()
if self.server_thread.error:
raise self.server_thread.error
class ServerThread(threading.Thread):
def __init__(self, host, port=0):
self.host = host
self.port = port
self.is_ready = threading.Event()
self.error = None
super().__init__(daemon=True)
... |
yasharmaster/scancode-toolkit | src/packagedcode/pyrpm/rpm.py | Python | apache-2.0 | 10,566 | 0.001136 | # -*- coding: iso-8859-15 -*-
# -*- Mode: Python; py-ident-offset: 4 -*-
# vim:ts=4:sw=4:et
# Copyright (c) M�rio Morgado
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retai... | le 1:
match = regexp.search(string)
if match:
return data.tell() - 3
byte = data.read(1)
if not byte:
return None
else:
string += byte
class Entry(object):
''' RPM Header Entry
'''
def __init__(self, entry, store):
self.en... | efs.RPM_DATA_TYPE_CHAR: self.__readchar,
rpmdefs.RPM_DATA_TYPE_INT8: self.__readint8,
rpmdefs.RPM_DATA_TYPE_INT16: self.__readint16,
rpmdefs.RPM_DATA_TYPE_INT32: self.__readint32,
rpmdefs.RPM_DATA_TYPE_INT64: self.__read... |
thedrow/cyrapidjson | tests/test_benchmarks.py | Python | bsd-3-clause | 7,481 | 0.000544 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
import time
import pytest
try:
import yajl
except ImportError:
yajl = None
try:
import simplejson
except ImportError:
simplejson = None
try:
import json
except ImportError:
json = None
try:
import rapidjson
except I... | Array with 256 doubles:")
name = 'rapidjson (precise)'
serialize = rapidjson.dumps
deserialize = rapidjson.loads
ser | _data, des_data = benchmark(run_client_test,
name, serialize, deserialize,
data=doubles,
iterations=50000,
)
msg = "%-11s serialize: %0.3f deserialize: %0.3f total: %0.3f" % ... |
vhazali/cs5331 | assignment3/crawler/items.py | Python | mit | 747 | 0.002677 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in: |
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class URLItem(scrapy.Item):
url = scrapy.Field()
protocol = scrapy.Field()
domain = scrapy.Field()
path = s | crapy.Field()
page = scrapy.Field()
get_params = scrapy.Field()
class FormItem(scrapy.Item):
url = scrapy.Field()
id_attr = scrapy.Field()
# complete = scrapy.Field()
# name = scrapy.Field()
class InputItem(scrapy.Item):
url = scrapy.Field()
form_id = scrapy.Field()
complete = scra... |
majetideepak/arrow | dev/archery/archery/utils/command.py | Python | apache-2.0 | 2,217 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | y not in kwargs and ctx.quiet:
kwargs[key] = subprocess.PIPE
# Prefer safe by default
if "check" not in kwargs:
kwargs["check"] = True
logger.debug(f"Executing `{invocation}`")
return subprocess.run(invocation, **kwargs)
def __call__(self, *argv, **kwar... | self.run(*argv, **kwargs)
|
verdverm/pypge | pypge/benchmarks/yeast.py | Python | mit | 719 | 0.037552 | lol = []
vvs = []
with open("yeast2000.txt") as the_file:
first = True
idx = 0
cnt = 0
lcnt = 0
var = []
for line in the_file:
ll = [item.strip() for item in line.split()]
lcnt += 1
if first:
lol.append(ll[:l | en(ll)-2])
first = False
continue
var.append(ll)
cnt += 1
if cnt == 200:
cnt = 0
vv = [item for sublist in var for item in sublist]
vvs.a | ppend(vv)
var = []
print("flattening", lol[0][idx], idx, len(vv), lcnt)
if len(vvs) == 8:
break
idx += 1
for i in range(len(vvs[0])):
ll = [float(vvs[j][i]) for j in range(len(vvs))]
lol.append(ll)
import json
str_data = json.dumps(lol, indent=2)
with open('yeast.json', 'w') as the_file:
the_file.... |
chrisrossx/DotStar_Emulator | DotStar_Emulator/emulator/init/manage.py | Python | mit | 245 | 0 | """
DotStar_Emulator
config.py in current working directory will be automati | cally read and loaded.
Author: Christopher Ross
License: MIT Something Rather
"""
from DotStar_Emulator.manage import manage
if __name__ == "__main__":
manage | ()
|
butterworth1492/Visualizing-Cavity-Viruses | scurve/test/test_progress.py | Python | bsd-2-clause | 748 | 0.005348 | import scurve.progress as progress
import StringIO
class TestInplace:
def test_basic(self):
s = StringIO.StringIO()
c = progress.Inplace(stream=s)
assert s.getvalue() == ''
c.tick(10)
assert s.getvalue() == '\r10'
c.tick(10000)
assert s.getvalue() == '\r10... | ss(100, stream=s)
p.tick(25)
ass | ert p.prev == 0.25
p.tick(50)
assert p.prev == 0.5
p.full()
assert p.prev == 1.0
|
openstack/networking-plumgrid | networking_plumgrid/neutron/plugins/drivers/fake_plumlib.py | Python | apache-2.0 | 5,565 | 0 | # Copyright 2015 PLUMgrid, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | _password):
LOG.info(_LI('Fake Director: %s'),
director_plumgrid + ':' + str(director_port))
pass
def create_network(self, tenant_id, net_db, network, **kwargs):
net_db["network"] = {}
for key in (provider.NETWORK_TYPE,
provider.PHYSICAL_NETWORK,... | net_db["network"][key] = network["network"][key]
return net_db
def update_network(self, tenant_id, net_id, network, orig_net_db):
pass
def delete_network(self, net_db, net_id):
pass
def create_subnet(self, sub_db, net_db, ipnet):
pass
def update_subnet(self, ori... |
userzimmermann/zetup.py | setup.py | Python | lgpl-3.0 | 2,147 | 0.000466 | from __future__ import print_function
import sys
import os
# from setuptools import Distribution
from pkg_resources import get_distribution, working_set, VersionConflict
def samefile(path, other):
"""
Workaround for missing ``os.path.samefile`` in Windows Python 2.7.
"""
return os.path.normcase(os.p... | s[name]
# sys.path.insert(0, Distribution().fetch_build_egg(setup_req))
zfg = Zetup()
zetup.requires.Require | ments('setuptools >= 36.2', zfg=zfg).check()
setup = zfg.setup
setup['package_data']['zetup.commands.make'] = [
'templates/*.jinja',
'templates/package/*.jinja',
]
setup()
|
starbops/OpenADM | core/src/floodlight_modules/uipusher.py | Python | gpl-2.0 | 6,838 | 0.041533 | import logging
from pymongo import MongoClient
import json
from bson import js | on_util
import time
import datetime
logger = logging.getLogger(__name__)
class UIPusher:
def __init__(self,core,parm):
# register event handler
core.registerEventHandler("controlleradapter", self.controllerHandler)
| # register websocket api
core.registerURLApi("info/topology", self.topologyHandler)
core.registerURLApi("stat", self.statisticHandler)
# save core for ipc use
self.core = core
self.intervalList=['hourly','daily','weekly','monthly','annually']
self.intervalList[0] = 'hourly'+str(datetime.datetime.today().s... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/oneconf/packagesethandler.py | Python | gpl-3.0 | 6,034 | 0.008452 | # Copyright (C) 2010 Canonical
#
# Authors:
# Didier Roche <didrocks@ubuntu.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; version 3.
#
# This program is distributed in the hope that it... | e=None, only_manual=False):
'''get all installed packages from the storage'''
hostid = self.hosts.get_hostid_from_context(hostid, hostname)
LOG.debug ("Request for package list for %s with only manual packages reduced scope to: %s", hostid, only_manual)
package_list = se... | anual:
package_list = [package_elem for package_elem in package_list if package_list[package_elem]["auto"] == False]
return package_list
def _get_installed_packages(self, hostid):
'''get installed packages from the storage or cache
Return: uptodate package_... |
network-box/uptrack | uptrack/resources.py | Python | agpl-3.0 | 1,492 | 0 | from pyramid.security import ALL_PERMISSIONS, Allow, Authenticated
from .models import DBSession, Distro, Package, Upstream, User
from uptrack.sch | emas import DistroSchema, UpstreamSchema, UserSchema
resources = {}
class RootFactory(object):
__name__ = 'RootFactory'
__parent__ = None
__acl__ = [(Allow, Authenticated, ALL_PERMISSIONS)]
def __init__(self, request):
pass
def __getitem__(self, name):
r = resources[name]()
... | bject):
__name__ = None
__parent__ = None
def __getitem__(self, id):
o = DBSession.query(self.__model__).get(id)
if o:
o.__parent__ = self
o.__name__ = id
return o
else:
raise KeyError(id)
class DistroResource(BaseResource):
__m... |
cloudzfy/euler | src/11.py | Python | mit | 3,512 | 0.004841 | # In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
# 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
# 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
# 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 | 49 13 36 65
# 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
# 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
# 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
# 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
# 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 ... | 5
# 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
# 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
# 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
# 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
# 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
# 88 36 ... |
team-ferret/pip-in-toto | pip/toto/ssl_crypto/formats.py | Python | mit | 25,848 | 0.013966 | #!/usr/bin/env python
"""
<Program Name>
formats.py
<Author>
Geremy Condra
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
Refactored April 30, 2012. -vladimir.v.diaz
<Copyright>
See LICENSE for licensing information.
<Purpose>
A central location for all format-related checking of TUF objects.
No... | hexadecimal value identifying an RSA key).
KEYID_SCHEMA = HASH_SCHEM | A
# A list of KEYID_ssl_commons__schema.
KEYIDS_SCHEMA = ssl_commons__schema.ListOf(KEYID_SCHEMA)
# The method used for a generated signature (e.g., 'RSASSA-PSS').
SIG_METHOD_SCHEMA = ssl_commons__schema.AnyString()
# A relative file path (e.g., 'metadata/root/').
RELPATH_SCHEMA = ssl_commons__schema.AnyString()
REL... |
ad-lebedev/django-todo-rest | todo-project/todo_api/serializers.py | Python | mit | 359 | 0 | # coding=utf-8
from | __future__ import unicode_literals
from django.contrib.auth.models import User
from rest_framework import serializers
__author__ = 'ad'
__date__ = '20/08/16'
class SignInSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password')
read_only = ('user | name', 'password')
|
elpaso/django-simplemenu | simplemenu/pages.py | Python | bsd-3-clause | 2,730 | 0.003663 | import copy
import types
from django.core.urlresolvers import reverse
from django.db.models.query import QuerySet
registry = []
def register(*args):
"""
Register urls, views, model instances and QuerySets to be potential
pages for menu items.
Example::
import simplemenu
simpleme... | name.replace("_", " ").capitalize()
return name
def url(self):
if self.urlobj:
url = self.urlobj.get_absolute_url()
elif "/" in self.urlstr:
url = self.urlstr
else:
| url = reverse(self.urlstr)
return url
def strkey(self):
"""
Generates somewhat unique string id of the wrappee.
"""
if self.urlobj:
return "%s.%s.pk%s" % (self.urlobj.__module__,
self.urlobj.__class__.__name__,
... |
mtils/ems | ems/qt4/location/landmarks/landmarkfetchrequest.py | Python | mit | 4,739 | 0.009074 | '''
Created on 24.10.2011
@author: michi
'''
from PyQt4.QtCore import QObject, QMutexLocker
from landmarkabstractrequest import LandmarkAbstractRequest #@UnresolvedImport
from landmarkfilter import LandmarkFilter #@UnresolvedImport
class LandmarkFetchRequest(LandmarkAbstractRequest):
'''
The QLandmarkFetchR... | ef setSort | ing(self, sorting):
'''
Sets the sort ordering of the request to \a sorting. This
function will only have an effect on the results if invoked
prior to calling \l QLandmarkAbstractRequest::start().
@param sorting: The sorting as a list
@type sorting: list
... |
itucsdb1509/itucsdb1509 | server.py | Python | gpl-3.0 | 27,509 | 0.00927 | import datetime
import time
import os
import json
import re
import psycopg2 as dbapi2
from flask import Flask
from flask import redirect
from flask import request
from flask import render_template
from flask.helpers import url_for
from store import Store
from fixture import *
from sponsors import *
from championship i... | print(e.pgerror)
finally:
| cursor.close()
###########
except dbapi2.Error as e:
print(e.pgerror)
connection.rollback()
finally:
connection.commit()
connection.close()
return redirect(url_for('home_page'))
@app.route('/championships', methods=['GET', 'POST'])
def championships_page():
conn... |
mmpi/SvgPresenter | qt/movie/MovieData.py | Python | gpl-3.0 | 1,178 | 0.011036 | import os.path
from PyQt4 import QtCore, QtGui
import vlc.vlc as vlc
class MovieData:
libvlc = vlc.Instance(["--no-audio","--no-xlib"])
def __init__(self, basePath, dict):
self.basePath = basePath
self.data = dict
# load poster pixmap
PngBase64 = "data:image/png;base64... | 4(imageData[len(PngBase64):])
self.pixmap = QtGui.QPixmap()
self.pixmap.loadFromData(byteArray)
# load medium
path = self.data["path"]
head, tail = os.path.split(path)
if head=="":
path = os.path.join(self.basePath, tail)
self.media = ... | a_new(unicode(path))
if self.data["loop"]:
self.media.add_option("input-repeat=-1") # repeat
def scaledRectangle(self, factor):
return QtCore.QRect(factor*self.data["x"], factor*self.data["y"], factor*self.data["width"], factor*self.data["height"])
def aspectRatio(self)... |
nicole-a-tesla/meetup.pizza | pizzaplace/tests/test_pizza_place.py | Python | mit | 1,885 | 0.008488 | from django.test import TestCase
from django.db import DataError
from django.db import IntegrityError
from pizzaplace.models import PizzaPlace
class TestPizzaPlace(TestCase):
def setUp(self):
self.prince_street_pizza_url = 'https://www.yelp.com/biz/prince-st-pizza-new-york'
self.pizza_name1 = 'Such Pizza'... | alid_if_over_500_char(self):
name = "x" * 501
place = PizzaPlace(name=name, yelp_url=self.prince_street_pizza_url)
self.assertRaises(DataError, place.save)
def test_raises_error_if_name_is_blank(self):
place = PizzaPlace(yelp_url=self.prince_street_pizza_url)
self.assertRaises(IntegrityError, pla... | = PizzaPlace(name=self.pizza_name1)
self.assertRaises(IntegrityError, place.save)
|
adrienpacifico/openfisca-france-data | openfisca_france_data/tests/test_yaml.py | Python | agpl-3.0 | 14,154 | 0.01194 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... | or (abs(target_value - value / 12) <= abs(relative_error_margin * target_value)).all(), \
'{}{} differs from {} with a relative margin {} > {}'.format(message, value, target_value,
abs(target_value - value), abs(relative_error_margin * target_value))
else:
if absolute... | or abs(target_value - value / 12) <= absolute_error_margin, \
'{}{} differs from {} with an absolute margin {} > {}'.format(message, value, target_value,
abs(target_value - value), absolute_error_margin)
if relative_error_margin is not None:
assert abs(target_val... |
swails/mdtraj | mdtraj/tests/test_xyz.py | Python | lgpl-2.1 | 3,492 | 0.002577 | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
# Authors: Christoph Klein
# Contributors:
#
# MDTraj is free software: yo... | ense for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with | MDTraj. If not, see <http://www.gnu.org/licenses/>.
##############################################################################
import tempfile, os
import numpy as np
import mdtraj as md
from mdtraj.formats import XYZTrajectoryFile
from mdtraj.testing import get_fn, eq
fd, temp = tempfile.mkstemp(suffix='.xyz')... |
Architektor/PySnip | contrib/scripts/timedmute.py | Python | gpl-3.0 | 1,733 | 0.021927 | # Timed mute: !tm <player> <seconds> <reason>
# default time 5 minutes, default reason None
# by topologist June 30th 2012
from scheduler import Scheduler
from commands import add, admin, get_player, join_arguments, name
@name('tm')
@admin
def timed_mute(connection, *args):
protocol = connection.protocol
... | player.protocol.send_chat('%s was muted indefinitely (Reason: %s)' % (
player.name, reason), irc = True)
return
schedule = Scheduler(player.protocol)
schedule.call_later(time, self.end)
player.mute_schedule = schedule
player.protocol.send_chat('%s was muted for %s seconds (Reason... | False
message = '%s was unmuted after %s seconds' % (self.player.name, self.time)
self.player.protocol.send_chat(message, irc = True)
def apply_script(protocol, connection, config):
class TimedMuteConnection(connection):
mute_schedule = None
def on_disconnect(self):
if self.mute_sch... |
michaelneuder/image_quality_analysis | bin/nets/old/pixel_diff_conv_net_automated.py | Python | mit | 5,287 | 0.015131 | #!/usr/bin/env python3
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import numpy as np
np.set_printoptions(threshold=np.nan)
import tensorflow as tf
import time
# seeding for debug purposes --- dont forget to remove
SEED = 12345
np.random.seed(SEED)
tf.set_random_seed(SEED)
def convolve_inner_layers(x, W, b):
... | n(optimizer, feed_dict={x : x_data_train, y : y_data_train})
loss = sess.run(cost, feed_dict={x : x_data_train, y : y_data_train})
| epoch_count+=1
print(' optimization finished!')
score = sess.run(cost, feed_dict={x: test_data, y: target_data_test})
print(' score : {} '.format(score))
return (image_dim, initializer_scale, learning_rate), (loss, score)
def main():
results = {}
image_dims = [1,2,3,4... |
tensor-tang/Paddle | python/paddle/fluid/tests/unittests/test_parallel_executor_seresnext_base_cpu.py | Python | apache-2.0 | 1,446 | 0 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import seresnext_net
from seresnext_test_base import TestResnetBase
from functools import partial
class TestResnetCPU(TestResnetBase):
def test_seresnext_with_learning_rate_decay(self):
# NOTE(zcd): Th... | o the two ops should be removed
# from the model.
check_func = partial(
self.check_network_convergence,
optimizer=seresnext_net.optimizer,
use_parallel_executor=False)
self._compare_result_with_origin_model(
check_func, use_cuda=False, compare_sepe... |
satterly/alerta5 | alerta/app/views/__init__.py | Python | apache-2.0 | 939 | 0.007455 |
from flask import Blueprint, request, jsonify, current_app
from alerta.app.utils.api import absolute_url
from alerta.app.exceptions import ApiError
api = Blueprint('api', __name__)
from . import alerts, blackouts, customers, heartbeats, keys, permissions, users, oembed
@api. | before_request
def only_json():
if request.method in ['POST', 'PUT'] and not request.is_json:
raise ApiError("POST and PUT requests must set 'Content-t | ype' to 'application/json'", 415)
@api.route('/', methods=['OPTIONS', 'GET'])
def index():
links = []
for rule in current_app.url_map.iter_rules():
links.append({
"rel": rule.endpoint,
"href": absolute_url(rule.rule) ,
"method": ','.join([m for m in rule.methods if ... |
eduNEXT/edx-platform | openedx/core/djangoapps/discussions/urls.py | Python | agpl-3.0 | 752 | 0.00133 | """
Configure URL endpoints for the djangoapp
"""
from django.urls import re_path
from django.conf import settings
from .views import CombinedDiscussionsConfigurationView, DiscussionsConfigurationSettingsView, DiscussionsProvidersView
urlpatterns = [
re_path(
fr'^v0/{settings.COURSE_KEY_PATTERN}$',
... |
DiscussionsProvidersView.as_view(),
name='di | scussions-providers',
),
]
|
VoIP-co-uk/sftf | UserAgentBasicTestSuite/case202.py | Python | gpl-2.0 | 4,465 | 0.018365 | #
# Copyright (C) 2004 SIPfoundry Inc.
# Licensed by SIPfoundry under the GPL license.
#
# Copyright (C) 2004 SIP Forum
# Licensed to SIPfoundry under a Contributor Agreement.
#
#
# This file is part of SIP Forum User Agent Basic Test Suite which
# belongs to the SIP Forum Test Framework.
#
# SIP Forum User Agent Basic... | ite 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 Foun | dation; either
# version 2 of the License, or (at your option) any later version.
#
# SIP Forum User Agent Basic Test Suite 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... |
commonsmachinery/rdf_metadata | src/RDFMetadata/test/__init__.py | Python | gpl-2.0 | 14 | 0 |
__al | l__ = [] | |
sentriz/steely | steely/plugins/train.py | Python | gpl-3.0 | 2,407 | 0.001248 | #!/usr/bin/env python3
'''
.train <train station>
get irish rail train state times
'''
import requests
import re
from operator import itemgetter
from xml.etree import ElementTree
from formatting import *
__author__ = 'izaakf'
COMMAND = 'train'
NAMESPACES = {'realtime': 'http://api.irishrail.ie/realtime/'}
REALTIME... | olumn_widths(times):
for column in zip(* | times):
print(column)
yield len_longest_string_of(column)
def gen_reply_string(times, widths):
_, max_origin, max_destin, max_time = widths
yield f" {'from':<{max_origin}} to"
for direction, origin, destin, time in times:
yield f"{direction} {origin:<{max_origin}} {destin:<{max_de... |
MikhailMS/Final_Project | download_music/__init__.py | Python | bsd-2-clause | 79 | 0 | # W | hat should be exported from module
from download_music import run_midi | _load
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.