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 |
|---|---|---|---|---|---|---|---|---|
mmottahedi/neuralnilm_prototype | scripts/e572.py | Python | mit | 15,490 | 0.003938 | from __future__ import print_function, division
import matplotlib
import logging
from sys import stdout
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import (Net, RealApplianceSource)
from neuralnilm.source import (standardise, discretize, fdiff, power_and_fdiff,
... | ngularOutputPlotter, StartEndMeanPlotter
from neuralnilm.updates import clipped_nesterov_momentum
from neuralnilm.rectangulariser import rectangularise
from lasagne.nonlinearities import (sigmoid, rectify, tanh, identity, softmax)
from lasagne.objectives import s | quared_error, binary_crossentropy
from lasagne.init import Uniform, Normal
from lasagne.layers import (DenseLayer, Conv1DLayer,
ReshapeLayer, FeaturePoolLayer,
DimshuffleLayer, DropoutLayer, ConcatLayer, PadLayer)
from lasagne.updates import nesterov_momentum, mom... |
kangsanChang/mjutt | timetable/models.py | Python | apache-2.0 | 1,169 | 0.005133 | from django.db import models
from .switcher import switch_to_deptname
# Create your models here.
class | Classitem(models.Model):
grade = models.CharField(max_length=10, blank=True, null=True)
classname = models.CharField(max_length=50, blank=True, null=True)
krcode = models.CharField(max_length=10, blank=True, null=True)
| credit = models.CharField(max_length=5, blank=True, null=True)
timeperweek = models.CharField(max_length=5, blank=True, null=True)
prof = models.CharField(max_length=30, blank=True, null=True)
classcode = models.CharField(max_length=10, blank=True, null=True)
limitstud = models.CharField(max_length=10... |
Team395/headlights | VisionScripts/TestPallate.py | Python | mit | 314 | 0.019108 | import cv2
import numpy as np
low = np.array([[[20,40,30]]*100]*100, np.uint8)
high = np.array([[[20,255,255]]*100]*100, np.uint8)
#low = cv2.cvtColor(low, cv2.COLOR_HSV2BGR)
#high = cv2.cvt | Color(high, cv2. | COLOR_HSV2BGR)
cv2.imshow('low', low)
cv2.imshow('high', high)
cv2.waitKey(10000)
cv2.destroyAllWindows()
|
brokendata/bigmler | bigmler/tests/test_05_evaluation.py | Python | apache-2.0 | 14,252 | 0.00407 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2015 BigML
#
# 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... | reated
And I check that the model has been created
And I check that the evaluation has been created
Then the evaluation file is like "<json_evaluation_file>"
Examples:
| data | output | | json_evaluation_file |
| ../data/iris.csv | ./scenario_e1/evaluation | ./check_files/evaluation_iris.json |
"""
print self.setup_scenario1.__doc__
examples = [
['data/iris.csv', 'scenario_e1/evaluation', 'check_files/evaluation_iris.json']]
... |
dremdem/maykor_python_learn | Lesson16/mysite/flask_app.py | Python | mit | 843 | 0.006173 | #-*- coding: utf-8 -*-
# A very simple Flask Hello World app for you to get started with...
from flask import Flask, render_template, redirect, url_for
from forms import TestForm
app = Flask(__name__, template_folder='/home/dremdem/mysite/templates')
app.secret_key = 's3cr3t'
class NobodyCare(object):
def __in... | st_b = 'BBBBBBBBB'
self.just_123 = '123'
self.people = [u'Иванов', u'Петров', u'Сидоров']
@app.route('/test', methods=['GET', 'POST'])
def test():
t1 = u'Еще не запускали!'
form = TestForm()
if form.validate_on_submit():
t1 = form.test1.data
| return render_template('test.html', form=form, t1=t1)
@app.route('/')
def hello_world():
return render_template('hello.html', a='100')
|
nemesisdesign/django | tests/middleware/tests.py | Python | bsd-3-clause | 42,600 | 0.001855 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import gzip
import random
import re
from io import BytesIO
from unittest import skipIf
from django.conf import settings
from django.core import mail
from django.core.exceptions import PermissionDenied
from django.http import (
FileResponse, HttpReque... | questFactory, SimpleTestCase, ignore_warnings, override_settings,
)
from django.utils import six
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_str
from django.utils.six.moves import range
from django.utils.six.moves.url | lib.parse import quote
@override_settings(ROOT_URLCONF='middleware.urls')
class CommonMiddlewareTest(SimpleTestCase):
rf = RequestFactory()
@override_settings(APPEND_SLASH=True)
def test_append_slash_have_slash(self):
"""
URLs with slashes should go unmolested.
"""
reques... |
django-leonardo/horizon | horizon/workflows/views.py | Python | apache-2.0 | 9,305 | 0 | # Copyright 2012 Nebula, 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 agree... | orkflowView(hz_views.ModalBackdropM | ixin, generic.TemplateView):
"""A generic class-based view which handles the intricacies of workflow
processing with minimal user configuration.
.. attribute:: workflow_class
The :class:`~horizon.workflows.Workflow` class which this view handles.
Required.
.. attribute:: template_nam... |
eudemonia-research/mincoin | rpc.py | Python | gpl-3.0 | 712 | 0.002809 | import requests
import json
call_id = 0
class RPC:
def __getattr__(self, name):
def func(*args):
global call_id
url = "http://localhost:12344/jsonrpc"
headers = {'content-type': 'application/json'}
| payload = {
"method": name,
"params": args,
"jsonrpc": "2.0",
"id": call_id,
}
response = requests.post(url, data=json.dumps(payload), headers=headers).json()
assert response['id'] == call_id
call_id += ... | urn response['result']
return func
|
wenhulove333/ScutServer | Sample/Doudizhu/Server/src/ZyGames.Doudizhu.HostServer/bin/Debug/Script/PyScript/Action/Action2005.py | Python | mit | 2,064 | 0.004873 | """2005_叫地主接口"""
import clr, sys
from action import *
from lang import Lang
clr.AddReference('ZyGames.Framework.Game')
clr.AddReference('ZyGames.Doudizhu.Lang')
clr.AddReference('ZyGames.Doudizhu.Model')
clr.AddReference('ZyGames.Doudizhu.Bll')
from ZyGames.Framework.Game.Service import *
from ZyGames.Doudizh... | GameTable.Current.GetUserPosition(user, table)
if not position:
parent.ErrorCode = Lang.getLang("ErrorCode")
parent.ErrorInfo = Lang.getLang("LoadError")
actionResult.Result = False
return actionResult
if position.IsAI:
position.IsAI = False
G | ameTable.Current.NotifyAutoAiUser(user.UserId, False)
isCall = urlParam.op == 1 and True or False
GameTable.Current.CallCard(user.Property.PositionId, table, isCall)
GameTable.Current.ReStarTableTimer(table)
return actionResult
def buildPacket(writer, urlParam, actionResult):
return True |
schlos/OIPA-V2.1 | OIPA/api/v3/resources/activity_list_resources.py | Python | agpl-3.0 | 4,609 | 0.007377 | # Django specific
from django.db.models import Q
# Tastypie specific
from tastypie import fields
from tastypie.constants import ALL
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
# Data specific
from iati.models import Activity
from api.v3.resources.helper_resources import Ti... | e, attribute='default_currency', full=True, null=True)
class Meta:
queryset = Activity.objects.all()
resource_name = 'activity-list'
max_limit = 100
serializer = Serializer(formats=['xml', 'json'])
excludes = ['date_created']
ordering = ['start_actual', 'start_plann... | ': ALL,
'start_actual': ALL,
'end_planned' : ALL,
'end_actual' : ALL,
'total_budget': ALL,
'sectors' : ('exact', 'in'),
'regions': ('exact', 'in'),
'countries': ('exact', 'in'),
'reporting_organisation': ('exact', 'in')
... |
mbohlool/client-python | kubernetes/client/models/v1_storage_class_list.py | Python | apache-2.0 | 6,537 | 0.001836 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | def metadata(self, metadata):
"""
Sets the metadata of this V1StorageClassList.
Standard list metadata More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
:param metadata: The metadata of this V1StorageClassList.
:type: V1ListMeta
| """
self._metadata = metadata
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = ... |
PowerOfJusam/JusamMud | mudserver.py | Python | mit | 15,734 | 0.008262 | #testing
"""
Basic MUD server module for creating text-based Multi-User Dungeon (MUD) games.
Contains one class, MudServer, which can be instantiated to start a server running
then used to send and receive messages from players.
author: Mark Frimston - mfrimston@gmail.com
"""
import socket
import select
import time... | close the socket, disconnecting the client
cl.socket.shutdown()
cl.socket.close()
# stop listening for new clients
self._listen_socket.close()
def _attempt_send(self,clid,data):
# python 2/3 compatability fix - convert non-unicode string to unicode
| if sys.version < '3' and type(data)!=unicode: data = unicode(data,"latin1")
try:
# look up the client in the client map and use 'sendall' to send
# the message string on the socket. 'sendall' ensures that all of
# the data is sent in one go
self._clients[clid].... |
kdart/bpython | doc/sphinx/source/conf.py | Python | mit | 7,072 | 0.00608 | # -*- coding: utf-8 -*-
#
# bpython documentation build configuration file, created by
# sphinx-quickstart on Mon Jun 8 11:58:16 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | path.dirname(os.path.abspath(__file__)),
'../../../bpython/_version.py')
with open(version_file) as vf:
version = vf.read().strip().split('=')[-1].replace('\'', '')
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. ... | ation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included ... |
naparuba/shinken | test/test_end_parsing_types.py | Python | agpl-3.0 | 6,105 | 0.002293 | #!/usr/bin/env python
# Copyright (C) 2009-2015:
# Coavoux Sebastien <s.coavoux@free.fr>
#
# This file is part of Shinken.
#
# Shinken 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 3... | for contact in self.conf.contacts:
for prop in ["notificationways", "host_notification_commands", "service_no | tification_commands"]:
if hasattr(contact, prop):
value = getattr(contact, prop)
# We should get ride of None, maybe use the "neutral" value for type
if value is not None:
print("TESTING %s with value %s" % (prop, value)... |
stalker314314/MissPopularStackOverflow | load_to_mongo_from_dump.py | Python | gpl-3.0 | 2,043 | 0.008321 | import logging.handlers
import time
import dateutil.parser
from pymongo.mongo_client import MongoClient
import xml.etree.ElementTree as etree
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.handlers.TimedRotatingFileHandler(filename='load_to_mongo_from_dump.log', when='mi... | (ch)
INTEGER_KEYS = ('Id', 'ParentId', 'LastEditor | UserId', 'OwnerUserId', 'PostTypeId', 'ViewCount', 'Score', 'AcceptedAnswerId', 'AnswerCount', 'CommentCount', 'FavoriteCount')
STRING_KEYS = ('Title', 'LastEditorDisplayName', 'Body', 'OwnerDisplayName')
DATE_KEYS = ('CommunityOwnedDate', 'LastActivityDate', 'LastEditDate', 'CreationDate', 'ClosedDate')
LIST_KEYS =... |
ph4m/eand | eand/demo/monodiff_demo.py | Python | gpl-3.0 | 3,605 | 0.006657 | '''
eand package (Easy Algebraic Numerical Differentiation)
Copyright (C) 2013 Tu-Hoa Pham
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 lat... | ; # initial observation time
T1 = 5.; # final observation time
Ts = 1./200.; # sampling period
SNR = 25.; # signal to noise ratio
t = np.arange(T0,T1+Ts,Ts); # observation time
Ns = len(t); # total number of samp... | signal
x = np.array([0.]*Ns)
xp = np.array([0.]*Ns)
xpp = np.array([0.]*Ns)
for i in range(Ns):
x[i] = tanh(t[i]-1.) + exp(-t[i]/1.2)*sin(6.*t[i]+pi)
xp[i] = -6.*exp(-5./6.*t[i])*cos(6.*t[i]) + 1./(cosh(1.-t[i])**2.) + 5./6.*exp(-5./6.*t[i])*sin(6.*t[i]);
xpp[i] = 10.*exp(-5.*t[i]/6.)*cos(6.*t[i]) + 1271./3... |
buguelos/odoo | addons/web_notification/__init__.py | Python | agpl-3.0 | 64 | 0.015625 | #f | lake8: noqa
#
import notifications
import base
import se | tting
|
matthewayne/evernote-sdk-python | sample/all_methods/listSearches.py | Python | bsd-3-clause | 670 | 0.008955 | # Import the Evernote client
from evernote.api.client import EvernoteClient
# Define access token either:
# D | eveloper Tokens (https://dev.evernote.com/doc/articles/dev_tokens.php)
# or OAuth (https://dev.evernote.com/doc/articles/authentication.php)
access | _token = "insert dev or oauth token here"
# Setup the client
client = EvernoteClient(token = access_token, sandbox = True)
# Get note store object
note_store = client.get_note_store()
# Returns the current state of the search with the provided GUID.
saved_searches = note_store.listSearches()
print "Found %s saved s... |
DistrictDataLabs/minimum-entropy | fugato/serializers.py | Python | apache-2.0 | 4,013 | 0.004236 | # fugato.serializers
# JSON Serializers for the Fugato app
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Thu Oct 23 15:03:36 2014 -0400
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: serializers.py [8eae6c4] benjamin@bengfort.com $
"""
JSON S... | ######################################################################
## Serializer Methods
######################################################################
def get_page_url(self, obj):
| """
Returns the models' detail absolute url.
"""
return obj.get_absolute_url()
#####################################################################
## Override create and update for API
######################################################################
def create(self, v... |
NikolaYolov/invenio_backup | modules/bibauthorid/lib/bibauthorid_config.py | Python | gpl-2.0 | 10,357 | 0.003862 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2011 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) a... | MP_LIST_MIN_TRSH_P_N:
PERSONID_MAX_COMP_LIST_MIN_TRSH_P_N = CFG_BIBAUTHORID_PERSONID_MAX_COMP_LIST_MIN_TRSH_P_N
else:
PERSONID_MAX_COMP_LIST_MIN_TRSH_P_N = 0.5
#Create_new_person flags thresholds
PERSONID_CNP_FLAG_1 | = 0.75
PERSONID_CNP_FLAG_MINUS1 = 0.5
# update_personid_from_algorithm person_paper_list for get_person_ra call
# minimum flag
PERSONID_UPFA_PPLMF = -1
#Tables Utils debug output
TABLES_UTILS_DEBUG = False
# Is the authorid algorithm allowed to attach a virtual author to multiple
# real authors in the last run of... |
jongha/thunderfs | src/web/application/libs/shorten.py | Python | agpl-3.0 | 301 | 0.0299 | #!/usr/ | bin/env python3
# -*- coding: utf-8 -*-
import os
import codecs
import json
from application.libs import bitly
def get(url):
api = bitly.Api(login='o_1gc6gttus8', apikey='R_a6ce0adb432e4e42b48c7635cc62571a')
shorten_url = api.shorten(url,{'history':1})
return shorten_ur | l |
NikolaiT/proxy.py | setup.py | Python | bsd-3-clause | 1,527 | 0.024885 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
HTTP Proxy Server in Python with explicit WebSocket support.
:copyright: (c) 2013 by Abhinav Singh.
:license: BSD, see LICENSE for more details.
Added WebSocket support to modify and change WebSocket messages on Summer 2015.
The original s... | icense',
'Operating System :: MacOS',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: Microsoft',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: Proxy Servers',
'Topic :: Internet :: WWW/HTTP :: HTTP Serv... | on__,
description = proxy.__description__,
long_description = open('README.md').read().strip(),
author = proxy.__author__,
author_email = proxy.__author_email__,
url = proxy.__homepage__,
license = proxy.__license__,
py_modules ... |
bmmalone/as-auto-sklearn | as_auto_sklearn/train_as_auto_sklearn.py | Python | mit | 10,979 | 0.005192 | #! /usr/bin/env python3
import argparse
import ctypes
import itertools
import joblib
import numpy as np
import os
import pandas as pd
import shlex
import string
import sys
import yaml
import sklearn.pipeline
import sklearn.preprocessing
from aslib_scenario.aslib_scenario import ASlibScenari | o
import misc.automl_utils as automl_utils
import misc.math_utils as math_utils
import misc.parallel as parallel
import misc.shell_utils as shell_utils
import misc.utils as utils
from misc.column_selector import ColumnSelector
from misc.column_selector import ColumnTransformer
import logging
import misc.logging_util... | er = logging.getLogger(__name__)
default_num_cpus = 1
default_num_blas_cpus = 1
def _get_pipeline(args, config, scenario):
""" Create the pipeline which will later be trained to predict runtimes.
Parameters
----------
args: argparse.Namespace
The options for training the autosklearn regressor... |
fernandezcuesta/ansible | lib/ansible/modules/identity/ipa/ipa_group.py | Python | gpl-3.0 | 9,300 | 0.001935 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
... | p
def get_group_diff(client, ipa_group, module_group):
| data = []
# With group_add attribute nonposix is passed, whereas with group_mod only posix can be passed.
if 'nonposix' in module_group:
# Only non-posix groups can be changed to posix
if not module_group['nonposix'] and ipa_group.get('nonposix'):
module_group['posix'] = True
... |
sejimhp/BulletReflector | BulletManager.py | Python | mit | 999 | 0.003083 | from Common import *
class BulletManager:
def __init__(self):
self. | bullets = []
def add(self, x, y, r, rad, bullet_type):
if bullet_type == 1:
self.bullets.append(MyBullet(x, y, r, rad))
elif bullet_type == 2:
self.bullets.append(EnemyBullet(x, y, r + random.randint(1, 3), rad))
elif bullet_type == 3:
self.bullets... | elif bullet_type == 4:
self.bullets.append(EnemyLaser(x, y, r, rad))
elif bullet_type == 5:
self.bullets.append(PlayerLaser(x, y, r, rad))
def update(self, stage, player):
# 弾が画面外に行った場合削除
for bullet in self.bullets:
bullet.update(player)
... |
rsalmei/clearly | clearly/server/__init__.py | Python | mit | 34 | 0 | f | rom .server import ClearlyServ | er
|
rallylee/gem5 | src/mem/ruby/structures/DirectoryMemory.py | Python | bsd-3-clause | 2,558 | 0.000391 | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POS... | *
from m5.SimObject import SimObject
class RubyDirectoryMemory(SimObject):
type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory responds to")
|
sprockets/sprockets.clients.postgresql | sprockets/clients/postgresql/__init__.py | Python | bsd-3-clause | 5,585 | 0.003581 | """
PostgreSQL Session API
======================
The Session classes wrap the Queries :py:class:`Session <queries.Session>` and
:py:class:`TornadoSession <queries.tornado_session.TornadoSession>` classes
providing environment variable based configuration.
Environment variables should be s | et using the ``PGSQL[_DBNAME]`` format
where the value is a PostgreSQL URI.
For PostgreSQL URI format, see:
http://www.postgresql.org/docs/9 | .3/static/libpq-connect.html#LIBPQ-CONNSTRING
As example, given the environment variable:
.. code:: python
PGSQL_FOO = 'postgresql://bar:baz@foohost:6000/foo'
and code for creating a :py:class:`Session` instance for the database name
``foo``:
.. code:: python
session = sprockets.postgresql.Session('foo')
... |
efce/voltPy | manager/helpers/html.py | Python | gpl-3.0 | 458 | 0.008734 | from django.utils.safestring import mark_safe
from django.contrib.staticfiles.templatetags.staticfiles import static
def locked():
return mark_safe('<img src="%s" alt="locked" style="border:0px; margin: 0px; padding: 0px"/>' % (
static('manager/padlock_close.png')
) | )
def unlocked():
return mark_safe('<img | src="%s" alt="locked" style="border:0px; margin: 0px; padding: 0px"/>' % (
static('manager/padlock_open.png')
))
|
google/mipnerf | internal/vis.py | Python | apache-2.0 | 5,130 | 0.009747 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ignore_frac=0,
curve_fn=lambda x: -jnp.log(x + jnp.finfo(jnp.float32).eps),
modulus=0,
colormap=None):
"""Visualize a depth map.
Args:
depth: A depth map.
acc: An accumulation map, in [0, 1].
near: The depth of the near plane, if None the... | use the max().
ignore_frac: What fraction of the depth map to ignore when automatically
generating `near` and `far`. Depends on `acc` as well as `depth'.
curve_fn: A curve function that gets applied to `depth`, `near`, and `far`
before the rest of visualization. Good choices: x, 1/(x+eps), log(x+ep... |
astorfi/speech_feature_extraction | example/test_local.py | Python | apache-2.0 | 2,213 | 0.009489 | """
This example is provided to test the package locally.
There is no need to installing the package using pip.
Only forking the project repository is required.
"""
import scipy.io.wavfile as wav
import numpy as np
import os
import sys
lib_path = os.path.abspath(os.path.join('..'))
print(lib_path)
sys.path.append(lib... | eature_cube = feature.extract_derivative_feature(mfcc)
print('mfcc feature cube shape=', mfcc_feature_cube.shape)
############# Extract logenergy features #############
logenergy = feature.lmfe(signal, sampling_frequency=fs,
frame_length=0.020, frame_stride=0.01,
... | nt('logenergy features=', logenergy.shape)
|
dana-i2cat/felix | optin_manager/src/python/openflow/optin_manager/sfa/drivers/OFShell.py | Python | apache-2.0 | 8,320 | 0.023918 | import threading
import time
import re
from openflow.optin_manager.sfa.openflow_utils.CreateOFSliver import CreateOFSliver
from openflow.optin_manager.sfa.openflow_utils.sliver_status import get_sliver_status
from openflow.optin_manager.sfa.openflow_utils.delete_slice import delete_slice
from openflow.optin_manager.sfa... | iver['datapath_id']) == str(switch[0]): #Avoiding Unicodes
found = True
break
if found == False:
return False
return True
def get_raw_switches(self):
try:
| #raise Exception("")
fv = FVServerProxy.objects.all()[0]
switches = fv.get_switches()
except Exception as e:
switches = test_switches
#raise e
return switches
def get_raw_links(self):
try:
... |
nicolacimmino/LoP-RAN | LoPAccessPoint/icmp_packet.py | Python | gpl-3.0 | 6,510 | 0.008295 |
"""
A pure Python "ping" implementation, based on a rewrite by Johannes Meyer,
of a script originally by Matthew Dixon Cowles. Which in turn was derived
from "ping.c", distributed in Linux's netkit. The version this was forked
out of can be found here: https://gist.github.com/pklaus/856268
I've rewritten nearly eve... | ort select
import random
from time import time
ICMP_ECHO_REQUEST = 8
ICMP_ECHO_RESPONSE = 0
ICMP_CODE = socket.getprotobyname('icmp')
ERROR_DESCR = {
1: 'ERROR: ICMP messages can only be sent from processes running as root.', |
10013: 'ERROR: ICMP messages can only be sent by users or processes with administrator rights.'
}
__all__ = ['create_packet', 'echo', 'recursive']
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = ord(source_str... |
bluetiki/pylab | telnet.py | Python | bsd-2-clause | 1,063 | 0.007526 | #!/usr/bin/env python
import telnetli | b
import time
import sys
import socket
TEL_PORT = 23
TEL_TO = 3
def write_cmd(cmd, conn):
cmd = cmd.rstrip()
conn.wri | te(cmd + '\n')
time.sleep(1)
return conn.read_very_eager()
def telnet_conn(ip, port, timeout):
try:
conn = telnetlib.Telnet(ip, port, timeout)
except socket.timeout:
sys.exit("connection timed out")
return conn
def login(user, passwd, conn):
output = conn.read_until("serna... |
danialbehzadi/Nokia-RM-1013-2.0.0.11 | webkit/Tools/wx/build/build_utils.py | Python | gpl-3.0 | 6,778 | 0.006639 | # Copyright (C) 2009 Kevin Ollivier All rights reserved.
#
# 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 retain the above copyright
# notice, this list of conditions and th... | urlretrieve(url, destfile, download_callback)
print ''
return destfile
return None
def update_wx_deps(conf, wk_root, msvc_version='msvc2008'):
"""
Download and update tools needed to build the wx port.
"""
import Logs
Logs.info('Ensuring wxWebKit dependencies are up-to-... | ity.com/downloads/deps/waf', os.path.join(wk_root, 'Tools', 'wx'))
if waf:
# TODO: Make the build restart itself after an update.
Logs.warn('Build system updated, please restart build.')
sys.exit(1)
# since this module is still experimental
wxpy_dir = os.path.join(wk_root, 'Source',... |
PMEAL/OpenPNM | openpnm/models/network/__init__.py | Python | mit | 158 | 0 | r"""
Network
=======
This submo | dule contains models for calculating topological properties of
networks
"""
|
from ._topology import *
from ._health import *
|
truedays/sandbox | python/pretty.py | Python | gpl-3.0 | 3,498 | 0.023156 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# CTA API CLI YAH
import requests
#from bs4 import BeautifulSoup
from xmltodict import parse
from time import gmtime, strftime
# enable debugging
import cgitb
cgitb.enable()
# get API key from file
f = open('./.cta-api.key', 'r')
APIKEY = "?key=" + f.read(25)
f.close()
URL =... | ']['prd'], list):
for x in range(0,len(out[ | 'bustime-response']['prd'])):
if out['bustime-response']['prd'][x]:
hourNow=int(out['bustime-response']['prd'][x]['tmstmp'][9:11])
minNow=int(out['bustime-response']['prd'][x]['tmstmp'][12:14])
hourPred=int(out['bustime-response']['prd'][x]['prdtm'][9:11])
minPred=int(out['bustime-response']['prd'][x... |
alexcc4/flask_restful_backend | app/libs/error.py | Python | mit | 412 | 0 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from webargs.flaskparser import (parser, abort)
@parser.error_ha | ndler
def handler_request_parsing_error(e):
error({}, 400, err | ors=e.messages)
def error(params=None, code=422, message='不合法的请求', errors=None):
params['message'] = message
params['errcode'] = code
if errors:
params['errors'] = errors
abort(code, **params)
|
cyli/volatility | volatility/plugins/mac/adiummsgs.py | Python | gpl-2.0 | 5,115 | 0.011144 | # Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 o... | roc_maps():
if map.get_perms() != "rw-" or map.get_path() != "":
continue
buffer = proc_as.zread(map.start.v(), map.end.v() - map.start.v())
if not buffe | r:
continue
msg_search = self._make_uni('<span class="x-message"')
time_search = self._make_uni('<span class="x-ltime"')
send_search = self._make_uni('<span class="x-sender"')
end_search = self._make_uni('</span>')
i... |
clips/pattern | pattern/text/en/inflect.py | Python | bsd-3-clause | 36,230 | 0.024924 | #### PATT | ERN | EN | INFLECT ######################################################################## |
# -*- coding: utf-8 -*-
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
####################################################################################################
# Regular expressions-based rules for English word in... |
nuclear-wizard/moose | python/chigger/tests/geometric/line_source/line_source_data_tube.py | Python | lgpl-2.1 | 710 | 0.021127 | #!/usr/bin/env python3
#pylint: disable=missing-docstring
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, | please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html |
import chigger
tube = chigger.filters.TubeFilter(radius=1)
cyl0 = chigger.geometric.LineSource(point1=[0,0,0], point2=[0,1,0], data=[1, 2, 4, 8, 16], cmap='viridis')
cyls = chigger.base.ChiggerResult(cyl0, filters=[tube])
window = chigger.RenderWindow(cyls, size=[300,300], test=True)
window.write('line_source_data_t... |
oukiar/qreader | parsetest.py | Python | mit | 443 | 0.006772 |
from parse_rest.conn | ection import register
from parse_rest.datatypes import Object
class GameScore(Object):
pass
register("XEPryFHrd5Tztu45du5Z3kpqxDsweaP1Q0lt8JOb", "PE8FNw0hDdlvcHYYgxEnbUyxPkP9TAsPqKvdB4L0")
myClassName = "GameScore"
myClass = Object.factory(myClassName)
print myClass
gameScore = GameScore(score=1337, player_n... | level = 2
gameScore.save()
|
cpcloud/arrow | python/pyarrow/util.py | Python | apache-2.0 | 5,001 | 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... | le from python 3.6, so pathlib
# doesn't implement __fspath__ for earlier versions
return (isinstance(path, str) or
hasattr(path, '__fspath__') or
isinstance(path, pathlib.Path))
def _stringify_path(path):
"""
Convert *path* to a string | or unicode path if possible.
"""
if isinstance(path, str):
return path
# checking whether path implements the filesystem protocol
try:
return path.__fspath__() # new in python 3.6
except AttributeError:
# fallback pathlib ckeck for earlier python versions than 3.6
... |
crepererum/invenio | invenio/ext/legacy/layout.py | Python | gpl-2.0 | 9,951 | 0.002311 | # -*- coding: utf-8 -*-
# This file is part of Invenio.
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 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... |
""" The global URL layout is composed of the search API plus all
the other modules."""
_exports = WebInterfaceSearchInterfacePages._exports + \
[
| 'youraccount',
'youralerts',
'yourbaskets',
'yourmessages',
'yourloans',
'yourcomments',
'ill',
'yourgroups',
'yourtickets',
'comments',
... |
Iconoclasteinc/tgit | cute/rect.py | Python | gpl-3.0 | 473 | 0.002114 | f | rom PyQt5.QtCore import QPoint, QMargins
def center_right(rect):
return QPoint(rect.right(), rect.center().y())
def center_left(rect):
return QPoint(rect.left(), rect.center().y())
def top_center(rect):
return QPoint(rect.center().x(), rect.top())
def bottom_center(rect):
return QPoint(rect.cent... | )) |
shiny-fortnight/auto_id | whitepages_api.py | Python | apache-2.0 | 1,774 | 0.003382 | #!/usr/bin/env python
import requests as r
import sys, json, re
import StringIO as StringIO
API_KEY = 'ea04b1f16b56a1b1a21b0159b8b1990e'
def _getPhoneNumber(inPhone):
re.sub("\D", "", inPhone)
inPhone = inPhone.replace('-', '')
if inPhone[0] == '1':
inPhone = inPhone[1:]
assert len(inPhone) =... | += nameValues['names'][name] if nameValues['names'][name] else ''
else:
fname = None
locationValues = asDict['results'][0]['best_location']
carrier = asDict['results'][0]['carrier']
phoneType = asDict['results'][0]['line_type']
locKeys = ['standard_address_line1', 'standard_address_line2',... | in locKeys:
streetAddr += locationValues[name]+' ' if locationValues[name] else ''
return [fname, streetAddr, carrier, phoneType, cleaned]
|
dileep-kishore/microbial-ai | tests/regulation/test_memory.py | Python | mit | 1,304 | 0 | # @Author: dileep
# @Last Modified by: dileep
import random
import pytest
from microbial_ai.regulation import Event, Action, Memory
@pytest.fixture
def random_action():
return Action(type='fixed', phi={'rxn1': (random.random(), '+')})
@pytest.fixture
def random_event(random_action):
return Event(state=ra... | int(0, 100), action=random_action,
next_state=random.randint(0, 100), reward=random.random())
@pytest.mark.usefixtures("random_event")
class TestMemory:
"""
Tests for the Memory class
"""
def test_initialization(self):
memory = Memory(1000)
assert memory.capacity =... | 0)
memory.add_event(random_event)
assert len(memory.memory) == 1
assert memory.idx == 1
for _ in range(1500):
memory.add_event(random_event)
assert len(memory.memory) == memory.capacity
assert memory.idx == (1000 - 500 + 1)
def test_sample(self, random_ev... |
Kromey/roglick | roglick/components/attributes.py | Python | mit | 157 | 0.006369 | from r | oglick.engine.ecs import ComponentBase
class AttributesComponent(ComponentBase):
_properties = (('st', 10), ('dx', 10), ('iq', 10), ('pe', 10)) | |
h4/fuit-webdev | examples/lesson5/pandora_data.py | Python | mit | 335 | 0 | from box.models import *
gold = ThingsType(title="Золото", kind=2, color="Жёлтый")
gold.save()
ferrum = ThingsType(title="Железо", kind=2, color="Чёрный")
ferrum.save()
ring = Thing(title="Кольцо", things_type=gold)
ring.save()
hammer = Thing(title="Молоток", th | ings_type=ferrum)
hammer.save()
| |
lamby/buildinfo.debian.net | bidb/keys/models.py | Python | agpl-3.0 | 744 | 0 | import datetime
from | django.db import models, transaction
class Key(models.Model):
uid = models.CharField(max_length=255, unique=True)
name = models.TextField()
created = models.DateTimeField(default=datetime.datetime.utcnow)
class Meta:
ordering = ('-created',)
get_latest_by = 'created'
def __unic... | ):
return u"pk=%d uid=%r name=%r" % (
self.pk,
self.uid,
self.name,
)
def save(self, *args, **kwargs):
created = not self.pk
super(Key, self).save(*args, **kwargs)
if created:
from .tasks import update_or_create_key
... |
cneill/designate-testing | designate/exceptions.py | Python | apache-2.0 | 8,130 | 0 | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... | = 'no_servers_configured'
c | lass NoPoolTargetsConfigured(ConfigurationError):
error_code = 500
error_type = 'no_pool_targets_configured'
class OverQuota(Base):
error_code = 413
error_type = 'over_quota'
class QuotaResourceUnknown(Base):
error_type = 'quota_resource_unknown'
class InvalidObject(Base):
error_code = 400... |
sanjuro/RCJK | vendor/django/db/backends/__init__.py | Python | apache-2.0 | 20,370 | 0.001669 | try:
# Only exists in Python 2.4+
from threading import local
except ImportError:
# Import copy of _thread_local.py from Python 2.4
from django.utils._threading_local import local
try:
set
except NameError:
# Python 2.3 compat
from sets import Set as set
try:
import decimal
except Impor... | trings_as_nulls = False
can_use_chunked_reads = True
can_return_id_from_insert = False
uses_autocommit = False
uses_savepoints = False
# If True, don't use integer foreign keys referring to, e.g., positive
# integer primary keys.
related_fields_match_type = False
allow_sliced_subqueries ... | lates the ID of a recently-inserted
row.
"""
def autoinc_sql(self, table, column):
"""
Returns any SQL needed to support auto-incrementing primary keys, or
None if no SQL is necessary.
This SQL is executed when a table is created.
"""
return None
def dat... |
botswana-harvard/edc-calendar | edc_calendar/models/update_or_create_event_model_mixin.py | Python | gpl-2.0 | 2,108 | 0.002846 | from django.apps import apps as django_apps
from django.db import models
from .event import Event
class UpdatesOrCreatesCalenderEventModelError(Exception):
pass
class UpdatesOrCreatesCalenderEventModelMixin(models.Model):
"""A model mixin that creates or updates a calendar event
on post_save signal.
| """
def create_or_update_calendar_event(self):
"""Creates or Updates the event model with attributes
f | rom this instance.
Called from the signal
"""
if not getattr(self, self.identifier_field) and not getattr(self, self.title_field):
raise UpdatesOrCreatesCalenderEventModelError(
f'Cannot update or create Calender Event. '
f'Field value for \'{self.iden... |
trungnt13/BAY2-uef17 | utils.py | Python | gpl-3.0 | 7,061 | 0.000142 | # ===========================================================================
# This file contain some utilities for the course
# ===========================================================================
from __future__ import print_function, division, absolute_import
import os
import sys
import time
import shutil
f... | een_so_far + n, values)
def get_file(fname, origin, untar=False, datadir=None):
'''
This function is adpated from: https://github.com/fchollet/keras
Original work Copyright ( | c) 2014-2015 keras contributors
Modified work Copyright 2016-2017 TrungNT
Return
------
file path of the downloaded file
'''
# ====== check valid datadir ====== #
if datadir is None:
datadir = os.path.join(os.path.expanduser('~'), '.bay2')
if not os.path.exists(datadir):
... |
vlegoff/tsunami | src/primaires/salle/types/combustible.py | Python | bsd-3-clause | 3,785 | 0.003975 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 NOEL-BARON Léo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#... | "Fichier contenant le type combustible."""
from primaires.interpreteur.editeur.entier import Entier
from primaires.interpreteur.editeur.selection import Selection
from primaires.objet.types.base import BaseType
class Combustible(BaseType):
"""Type d'objet: combustible.
|
"""
nom_type = "combustible"
def __init__(self, cle=""):
"""Constructeur de l'objet"""
BaseType.__init__(self, cle)
self.terrains = []
self.rarete = 1
self.qualite = 2
# Editeurs
self.etendre_editeur("t", "terrains", Selection, self... |
pmisik/buildbot | master/buildbot/test/unit/reporters/test_generators_utils.py | Python | gpl-2.0 | 13,510 | 0.002665 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | , results, **kwargs):
build = yield self.insert_build_finished(results, **kwargs)
yield utils.getDetailsForBuild(self.master, build, want_properties=True)
return build
def create_generator(self, mode=("failing", "passing", "warnings"),
| tags=None, builders=None, schedulers=None, branches=None,
subject="Some subject", add_logs=False, add_patch=False):
return BuildStatusGeneratorMixin(mode, tags, builders, schedulers, branches, subject,
add_logs, add_patch)
def test_genera... |
chrisdickinson/tweezers | projects/views/private.py | Python | mit | 9,684 | 0.002891 | import simplejson
import os
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.markup.templatetags.markup import restructuredtext
from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponseRedi... | project = form.save()
project_manage = reverse('projects_manage', args=[project.slug])
return HttpResponseRedirect(project_ | manage)
return render_to_response(
'projects/project_create.html',
{'form': form},
context_instance=RequestContext(request)
)
@login_required
def project_edit(request, project_slug):
"""
Edit an existing project - depending on what type of project is being
edited (created o... |
plotly/python-api | packages/python/plotly/plotly/validators/layout/yaxis/_showticklabels.py | Python | mit | 484 | 0.002066 | imp | ort _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="showticklabels", parent_name="layout.yaxis", **kwargs
):
super(ShowticklabelsValidator, self).__init__(
plotly_name=plotly_name,
... | |
kanafghan/fiziq-backend | src/models/factories.py | Python | gpl-2.0 | 2,302 | 0.002606 | '''
Created on 22/02/2015
@author: Ismail Faizi
'''
import models
class ModelFactory(object):
"""
Factory for creating entities of models
"""
@classmethod
def create_user(cls, name, email, training_journal):
"""
Factory method for creating User entity.
NOTE: you must ex... | kout_set.workout = work | out.key
return workout_set
@classmethod
def create_workout(cls, muscle_group, names=[], description='', images=[]):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout = models.Workout(parent=models.WO... |
mtlchun/edx | lms/djangoapps/django_comment_client/tests/mock_cs_server/test_mock_cs_server.py | Python | agpl-3.0 | 2,252 | 0.000888 | import unittest
import threading
import json
import urllib2
from mock_cs_server import MockCommentServiceServer
from nose.plugins.skip import SkipTest
class MockCommentServiceServerTest(unittest.TestCase):
'''
A mock version of the Comment Service server that listens on a local
port and responds with pre-... | # You should have received the response specified in the setup above
| self.assertEqual(response_dict, self.expected_response)
|
relekang/photos | photos/gallery/views.py | Python | mit | 2,650 | 0.001132 | # -*- coding: utf-8 -*-
import logging
from django.core.urlresolvers import reverse
from django.http.response import Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from photos.gallery.seri... | t.filter(user__domain=self.request.get_host())
elif username is not None:
queryset = queryset.filter(user__username=username)
| return queryset
class PhotoDetailView(PhotoViewMixin, DetailView):
def get_object(self, queryset=None, **kwargs):
queryset = queryset or self.get_queryset()
slug = self.kwargs.get(self.slug_url_kwarg, None)
if slug is None:
return queryset.last()
return get_object_o... |
melviso/phycpp | beatle/app/cxxtypes.py | Python | gpl-2.0 | 96 | 0 | # -*- cod | ing: utf-8 -*-
"""
Created on Tue Dec 17 | 00:25:59 2013
@author: mel
"""
_types = [
]
|
Parallel-in-Time/pySDC | pySDC/projects/Hamiltonian/fput.py | Python | bsd-2-clause | 8,363 | 0.002511 | import os
from collections import defaultdict
import dill
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import filter_stats, sort_stats
from pySDC.implementations.collocation_classes.gauss_lobatto import CollGaussLobatto
from pySDC.implementations.controller_classes... | .89)
# Rearrange data for easy plotting
nparts = len(result[0][1])
nsteps = len(result)
pos = np.zeros((nparts, nsteps))
time = np.zeros(nsteps)
for | idx, item in enumerate(result):
time[idx] = item[0]
for n in range(nparts):
pos[n, idx] = item[1][n]
for n in range(min(nparts, 16)):
plt_helper.plt.plot(time, pos[n, :])
fname = 'data/fput_positions'
plt_helper.savefig(fname)
assert os.path.isfile(fname + '.pdf')... |
zuun77/givemegoogletshirts | leetcode/python/792_number-of-matching-subsequences.py | Python | apache-2.0 | 716 | 0.006983 | import bisect
class Solution:
def numMatchingSubseq(self, S: str, words):
d = {}
for i, x in | enumerate(S):
if x not in d: d[x] = [i]
else: d[x].append(i)
ans = []
for w in words:
i = -1
result = True
for x in w:
if x not in d:
| result = False
break
idx = bisect.bisect_left(d[x], i+1)
if idx >= len(d[x]):
result = False
break
i = d[x][idx]
if result: ans.append(w)
return len(ans)
print(Solution().numMatchin... |
lvuotto/so-tps | tp3/bin/csv_loader.py | Python | mit | 1,092 | 0.020147 | #!/usr/bin/env python
from pymongo.connection import MongoClient
import csv
import json
""" Script para re-importar los posts a la base de datos """
reader = csv.DictReader(open('data/redit.csv'),
fieldnames=('image_id','unixtime','rawtime','title','total_votes',
'reddit_id','number_of_upvotes','... | 'number_of_downvotes'] = int(it['number_of_downvotes'] )
it['score'] = int(it['score'] )
it['number_of_comments'] = int(it['number_of_comments'] )
db.posts.insert(it)
except Exception as e:
print e, "while inserting", it
print "Inserted %d records" % d | b.posts.count()
assert db.posts.count() == 269689, "Missing records on DB, inserted: %d" % db.posts.count()
|
ismailakbudak/election-algorithm-on-graph | test/node_test.py | Python | mit | 1,091 | 0.03758 | # -*- coding: utf-8 -*-
# Test file for node class
# Develope | r
# Ismail AKBUDAK
# ismailakbudak.com
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from graph import Node
def log(message):
print("TEST:: %s"%(message))
def log_nei | ghbours(node):
log("%s neighbours : %s "%(node, str(node.neighbours)) )
n1=Node(1,1)
n2=Node(2,2)
n3=Node(3,3)
n4=Node(4,4)
n5=Node(5,5)
n6=Node(6,6)
n1.addNeighbour(n2)
n1.addNeighbour(n3)
n1.addNeighbour(n3)
n1.addNeighbour(n5)
n1.addNeighbour(n6)
n3.addNeighbour(n2)
n4.addNeighbour(n2)
log_neighbours(n1)
... |
gawbul/ReproPhyloVagrant | reprophylo/reprophylo.py | Python | mit | 281,160 | 0.011737 | reprophyloversion="99c16963"
############################################################################################
if False:
"""
ReproPhylo version 1
General purpose phylogenetics package for reproducible and experimental analysis
Amir Szitenebrg
A.Szitenberg@Hull.ac.uk
Szitenb... |
>>> ssu = Locus('dna', 'rRNA', '18S', ['18S rRNA','SSU rRNA'])
>>> bssu = Locus('dna', 'rRNA', '16S', ['16S rRNA'])
>>> lsu = Locus('dna', 'rRNA', '28S', ['28S rRNA' | , 'LSU rRNA'])
>>> alg11 = Locus('dna', 'CDS', 'ALG11', ['ALG11'])
>>> loci = [coi, ssu, bssu, lsu, alg11]
>>> concatenation = Concatenation(name='combined', loci=loci,
... otu_meta='OTU_name',
... otu_must_have_all_of=['coi'],
... ... |
thaim/ansible | lib/ansible/modules/cloud/ovirt/ovirt_storage_template_info.py | Python | mit | 5,147 | 0.003109 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 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
#... | not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_storage_template_info
short_description: Retrieve information about one or more oVirt/RHV templat... | a storage domain.
author: "Maor Lipchuk (@machacekondra)"
version_added: "2.4"
description:
- "Retrieve information about one or more oVirt/RHV templates relate to a storage domain."
- This module was called C(ovirt_storage_template_facts) before Ansible 2.9, returning C(ansible_facts).
Note that the M(ov... |
joakim-hove/ert | ert_gui/plottery/plots/history.py | Python | gpl-3.0 | 771 | 0 | def plotHistory(plot_context, axes):
"""
@type axes: matplotlib.axes.Axes
@type plot_config: PlotConfig
"""
plot_config = plot_context.plotConfig()
if (
not plot_config.isHistoryEnabled()
or plot_context.history_data is None
or plot_context.history_data.empty
):
... | 0 and style.isVisible():
plot_config.addLegendItem("History", line | s[0])
|
mathLab/RBniCS | rbnics/backends/online/numpy/linear_solver.py | Python | lgpl-3.0 | 1,491 | 0.004024 | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from numpy.linalg import solve
from rbnics.backends.abstract import LinearProblemWrapper
from rbnics.backends.online.basic import LinearSolver as BasicLinearSolver
from rbnics.backends.online... | rbnics.backends.online.numpy.transpose import DelayedTransposeWithArithmetic
from | rbnics.backends.online.numpy.vector import Vector
from rbnics.utils.decorators import BackendFor, DictOfThetaType, ModuleWrapper, ThetaType
backend = ModuleWrapper(Function, Matrix, Vector)
wrapping = ModuleWrapper(DelayedTransposeWithArithmetic=DelayedTransposeWithArithmetic)
LinearSolver_Base = BasicLinearSolver(bac... |
jongiddy/jute | compare/python_abc.py | Python | mit | 1,481 | 0 | from time import time
import abc
# Create an interface IFoo
# Create a sub-interface IFooBar
# Create a class FooBarBaz implementing IFooBar
# Repeatedly create an instance of FooBarBaz and pass it to a function
# that wants an IFoo
# Call foo
# Time all the above
# Create a single instance of FooBarBaz. Confirm wheth... | "
@property
@abc.abstractmethod
def bar():
"""An attrib | ute"""
class IncrementingInteger(IncrementsBar):
"""Increment an integer when increment is called."""
bar = 2
def increment(self):
self.bar += 1
def f(incrementer):
incrementer.increment()
def test_time():
start = time()
for i in range(1000000):
inc = IncrementingInteger... |
jamescarignan/Flask-User | example_apps/invite_app.py | Python | bsd-2-clause | 6,755 | 0.004737 | import os
from flask import Flask, redirect, render_template_string, request, url_for
from flask_babel import Babel
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_user import confirm_email_required, current_user, login_required, \
UserManager, UserMixin, SQLAlchem... | <a href="{{ url_for('home_page') }}">
{%trans%}Home Page{%endtrans%}</a></p>
<p> <a href="{{ url_for('user.change_username') }}">
{%trans%}Change username{%endtrans%}</a></p>
<p> <a href="{{ url_for('user.change_password | ') }}">
{%trans%}Change password{%endtrans%}</a></p>
<p> <a href="{{ url_for('user.invite') }}">
{%trans%}Invite User{%endtrans%}</a></p>
<p> <a href="{{ url_for('user.logout') }}">
{%trans%}Sign out{%endtrans%}</a></p>
... |
UManPychron/pychron | pychron/extraction_line/switch_manager.py | Python | apache-2.0 | 40,032 | 0.001274 | # ===============================================================================
# Copyright 2011 Jake Ross
#
# 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... | n.core.helpers.strtools import to_bool
from pychron.core.yaml import yload
from pychron.extraction_line import VERBOSE_DEBUG, VERBOSE
from pychron.extraction_line.pipettes.tracking import PipetteTracker
from pychron.globals import globalv
from pychron.hardware.core.checksum_helper import computeCRC
from pychron.hardwar... | m pychron.hardware.switch import Switch, ManualSwitch
from pychron.hardware.valve import HardwareValve
from pychron.managers.manager import Manager
from pychron.paths import paths
from pychron.pychron_constants import NULL_STR
from .switch_parser import SwitchParser
def parse_interlocks(vobj, tag):
vs = []
if... |
pikulak/pywdbms | api/app.py | Python | apache-2.0 | 16,191 | 0.003768 | import sys
import os
from flask import render_template, make_response, request, Blueprint, redirect, url_for, flash
from sqlalchemy import select
from collections import defaultdict
from sqlalchemy.exc import OperationalError
from pywdbms.db.file import load_databases_from_file as load
from pywdbms.db.file import upda... | t,
| drivername=_driver))
for drivername, databases in sorted_by_drivers.items():
for database in databases:
for shortname, db_properties in database.items():
if shortname in _BINDS:
connection = _BINDS[shortname][0] #connection
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/numpy/oldnumeric/arrayfns.py | Python | agpl-3.0 | 2,532 | 0.011848 | """Backward compatible with arrayfns from Numeric
"""
__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask',
| 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span',
'to_corners', 'zmin_zmax']
import numpy as np
from numpy import asarray
class error(Exception):
pass
def array_set(vals1, indices, vals2):
indices = asarray(indices)
if indices.ndim != 1:
raise ValueError, "index arr... | "vals1 must be an ndarray"
vals1 = asarray(vals1)
vals2 = asarray(vals2)
if vals1.ndim != vals2.ndim or vals1.ndim < 1:
raise error, "vals1 and vals2 must have same number of dimensions (>=1)"
vals1[indices] = vals2
from numpy import digitize
from numpy import bincount as histogram
def index_... |
mfraezz/osf.io | osf/utils/migrations.py | Python | apache-2.0 | 23,271 | 0.003051 | from past.builtins import basestring
import os
import itertools
import builtins
import json
import logging
import warnings
from math import ceil
from contextlib import contextmanager
from django.apps import apps
from django.db import connection
from django.db.migrations.operations.base import Operation
from osf.mode... | elect-input',
| ('text', 'string'): 'short-text-input',
('textarea', 'osf-author-import'): 'contributors-input',
('textarea', None): 'long-text-input',
('textarea', 'string'): 'long-text-input',
('textarea-lg', None): 'long-text-input',
('textarea-lg', 'string'): 'long-text-input',
('textarea-xl', 'string'): ... |
Somsubhra/Simplify | src/enrich/__init__.py | Python | mit | 63 | 0.015873 | __author__ = 's7a'
# All impo | rts
from enricher import | Enricher |
jorik041/plaso | tests/parsers/winreg_plugins/outlook.py | Python | apache-2.0 | 3,175 | 0.00126 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Outlook Windows Registry plugins."""
import unittest
# pylint: disable=unused-import
from plaso.formatters import winreg as winreg_formatter
from plaso.parsers.winreg_plugins import outlook
from tests.parsers.winreg_plugins import test_lib
from tests.winregi... | earch'
values = []
values.append(winreg_test_lib.TestRegValue(
(u'C:\\Users\\username\\AppData\\Loc | al\\Microsoft\\Outlook\\'
u'username@example.com.ost'), b'\xcf\x2b\x37\x00',
winreg_test_lib.TestRegValue.REG_DWORD, offset=1892))
winreg_key = winreg_test_lib.TestRegKey(
key_path, 1346145829002031, values, 1456)
event_queue_consumer = self._ParseKeyWithPlugin(self._plugin, winreg_ke... |
kumoru/torment | test_torment/test_unit/test_fixtures/__init__.py | Python | apache-2.0 | 15,613 | 0.005519 | # Copyright 2015 Alex Brandt
#
# 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, ... |
class ErrorFixturesRunTest(unittest.TestCase):
def test_error_fixture_run(self) -> None:
| '''torment.fixtures.ErrorFixture(context).run()'''
class fixture(fixtures.Fixture):
def run(self):
raise RuntimeError('failure')
class error_fixture(fixtures.ErrorFixture, fixture):
def __init__(self, *args, **kwargs) -> None:
super().__init_... |
jsteilen/FlopPyImg | funktionen.py | Python | gpl-3.0 | 6,553 | 0.03145 | import platform
import os
import shutil
import time
import hashlib
import xml.dom.minidom
import xml.etree.ElementTree
import re
def nameCount(name, targetPath):
pathXmlFile = targetPath + os.sep + 'info.xml'
if os.path.exists(pathXmlFile):
f = open(pathXmlFile, 'r')
xmlFileData = f.read()
f.clos... |
dom4 = xml.dom.minidom.parseString(xmlFileData)
volumeIdPosition = dom4.getElementsByTagName('count')
volumeId = str(int(volumeIdPosition[0].firstChild.nodeValue) + 1)
file | Name = 'disk' + volumeId + name
return fileName
## Liste mit Dateien und Ordnern
def contentList(path, listFileName, targetPath):
content = os.listdir(path) # in die Klammer den gewünschten Pfad einfügen
content.sort() # sortiert Liste alphabetisch!
openLstFile = targetPath + os.sep + listFileName
f = op... |
tony/libvcs | libvcs/__about__.py | Python | mit | 440 | 0 | __title__ = 'libvcs | '
__package_name__ = 'libvcs'
__description__ = 'vcs abstraction layer'
__version__ = '0.10.1'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/libvcs'
__docs__ = 'https://libvcs.git-pull.com'
__tracker__ = 'https://github.com/vcs-python/libvcs/issues'
__pypi__ = 'https://pypi.org/project/libvcs/... | rlock'
|
rocity/dj-instagram | djinstagram/instaapp/apps.py | Python | apache-2.0 | 91 | 0 | from djan | go.apps import AppConfig
class InstaappConfig(AppConfig):
name = ' | instaapp'
|
bthirion/nipy | nipy/algorithms/statistics/tests/test_mixed_effects.py | Python | bsd-3-clause | 5,555 | 0.00486 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Testing the glm module
"""
import numpy as np
from numpy.testing import (assert_almost_equal,
assert_array_almost_equal,
assert_raises)
from nose.t... | mple_ttest, one_sample_ftest, two_sample_ttest, two_sample_ftest,
generate_data, t_stat, mfx_stat)
from ..bayesian_mixed_effects import two_level_glm
def test_mfx():
""" Test the generic mixed-effects model"""
n_samples, n_tests = 20, 100
np.random.seed(1)
# generate some data
V1 = np.ra... | amples, n_tests)
Y = generate_data(np.ones((n_samples, 1)), 0, 1, V1)
X = np.random.randn(20, 3)
# compute the test statistics
t1, = mfx_stat(Y, V1, X, 1,return_t=True,
return_f=False, return_effect=False,
return_var=False)
assert_true(t1.shape == (n_tests,))... |
google/gif-for-cli | gif_for_cli/__main__.py | Python | apache-2.0 | 755 | 0 | """
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... | e.
"""
import os
import sys
from .execute import execute
def main(): # pragma: no cover
execute(os.environ, sys.argv[1:], sys.stdout)
if __name__ == '__main__': # pragma: no cover
main() | |
ThomasTheSpaceFox/SBTCVM-Mark-2 | SBTCVM-asm2.py | Python | gpl-3.0 | 33,216 | 0.048862 | #!/usr/bin/env python
import VMSYSTEM.libSBTCVM as libSBTCVM
import VMSYSTEM.libbaltcalc as libbaltcalc
import sys
import os
assmoverrun=19683
instcnt=0
txtblk=0
VMSYSROMS=os.path.join("VMSYSTEM", "ROMS")
critcomperr=0
compvers="v2.2.0"
outfile="assmout.trom"
#define IOmaps
IOmapread={"random": "--0------"}
IOmapwr... | : " + qarg
argisfile=1
if argisfile==1:
if qlowarg.endswith(".tasm") an | d os.path.isfile(qarg):
print "tasm source found."
arg=qarg
argistasm=1
break
else:
print "Not valid."
argisfile=0
if argisfile==0 or argistasm==0:
#print "ERROR: file not found, or is not a tasm file STOP"
sys.exit("ERROR: SBTCVM assembler was unable to load the specified filename. ... |
NiklasRosenstein/localimport | tests/test_localimport.py | Python | mit | 1,885 | 0.013793 |
from nose.tools import *
from localimport import localimport
import os
import sys
modules_dir = os.path.join(os.path.dirname(__file__), 'modules')
def test_localimport_with_autodisable():
sys.path.append(modules_dir)
import another_module as mod_a
try:
with localimport('modules') as _imp:
import som... | h localimport('.') as _imp:
assert_equals(sorted( | x.name for x in _imp.discover()), ['another_module', 'some_module', 'test_localimport'])
with localimport('modules') as _imp:
assert_equals(sorted(x.name for x in _imp.discover()), ['another_module', 'some_module'])
|
coUrbanize/rest_framework_ember | example/tests/test_model_viewsets.py | Python | bsd-2-clause | 5,527 | 0.001628 | import json
from example.tests import TestBase
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.conf import settings
class ModelViewSetTests(TestBase):
"""
Test usage with ModelViewSets, also tests pluralization, camelization,
and underscore.
[... | 'total'), 2)
self.ass | ertEquals(meta.get('count', 0),
get_user_model().objects.count())
self.assertEquals(meta.get('next'), 2)
self.assertEqual(u'http://testserver/identities?page=2',
meta.get('next_link'))
self.assertEqual(meta.get('page'), 1)
def test_page_two_in_list_result(self):
... |
philipforget/django-oauth-plus | oauth_provider/runtests/runtests.py | Python | bsd-3-clause | 1,167 | 0.005141 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://github.com/swistakm/django-rest-framework/blob/master/rest_framework/runtests/runtests.py
import os
import sys
# fix sys path so we don't need to setup PYTHONPATH
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
os.environ['DJANGO_SETTINGS_MODUL... | ef main():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=2)
if len(sys.argv) == 2:
test_case = '.' + sys.argv[1]
elif len(sys.argv) == 1:
test_case = ''
else:
print(usage())
sys.exit(1)
patch_for_test_db_setup()
failures = test_runner.... | ain__':
main()
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractWinterTranslates.py | Python | bsd-3-clause | 598 | 0.036789 | def extractWinterTranslates(item):
"""
'Winter | Translates'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['ti | tle'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Summaries' in item['tags']:
return None
tagmap = [
('Villain Rehab Plan', 'Transmigrating into a Mob Character to Rehabilitate the Villain Plan', 'translated'),
]
for tagname, name, tl_type in tagmap:
if ... |
cnsoft/kbengine-cocos2dx | kbe/src/lib/python/Lib/test/test_generators.py | Python | lgpl-3.0 | 50,722 | 0.000434 | tutorial_tests = """
Let's try a simple generator:
>>> def f():
... yield 1
... yield 2
>>> for i in f():
... print(i)
1
2
>>> g = f()
>>> next(g)
1
>>> next(g)
2
"Falling off the end" stops the generator:
>>> next(g)
Traceback (most recent call last... | or:
>>> def f():
... yield 1
... return
... yield 2 # never reached
...
>>> g = f()
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in f
StopIteration
>>> next(g) # once stopped, ca... | in ?
StopIteration
"raise StopIteration" stops the generator too:
>>> def f():
... yield 1
... raise StopIteration
... yield 2 # never reached
...
>>> g = f()
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
St... |
shoopio/shoop | shuup/campaigns/migrations/0013_hourconfition_fix.py | Python | agpl-3.0 | 1,527 | 0.00131 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-11 22:27
from __future__ import unicode_literals
import django
import django.core.validators
import re
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0012_basket_campaign_und... | Field(
verbose_name='days',
max_length=255,
validators=[
django.core.validators.RegexValidator(
re.compile('^[\\d,]+\\Z' if django.VERSION < (1, 9) else '^\\d+(?:\\,\\d+)*\\Z', 32),
code='invalid',
... | commas.'
)
]
),
),
]
|
FilipeMaia/afnumpy | afnumpy/indexing.py | Python | bsd-2-clause | 10,029 | 0.00349 | import arrayfire
import sys
import afnumpy
from . import private_utils as pu
import numbers
import numpy
import math
def __slice_len__(idx, shape, axis):
maxlen = shape[axis]
# Out of bounds slices should be converted to None
if(idx.stop is not None and idx.stop >= maxlen):
idx.stop = None
if(i... | ers.Number)):
if idx < 0:
idx = maxlen + idx
if(idx >= maxlen):
raise IndexError('index %d is out of bounds for axis %d with size %d' % (idx, axis, maxlen))
return idx
if(is | instance(idx, afnumpy.ndarray)):
return idx.d_array
if not isinstance(idx, slice):
return afnumpy.array(idx).d_array
if idx.step is None:
step = 1
else:
step = idx.step
if idx.start is None:
if step < 0:
start = maxlen-1
else:
sta... |
soulmachine/scikit-learn | sklearn/linear_model/logistic.py | Python | bsd-3-clause | 38,054 | 0.000053 | """
Logistic Regression
"""
# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
# Fabian Pedregosa <f@bianp.net>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Manoj Kumar <manojkumarsivaraj334@gmail.com>
import numbers
import warnings
import numpy as np
from scipy impo... | .
If None, then it is assumed that the given problem is binary.
fit_intercept : bool
Whether to fit an intercept for the model. In this case the shape of
the returned array is (n_cs, n_features + 1).
max_iter : int
Maximum number of iterations for the solv | er.
tol : float
Stopping criterion. For the newton-cg and lbfgs solvers, the iteration
will stop when ``max{|g_i | i = 1, ..., n} <= tol``
where ``g_i`` is the i-t |
dbishai/DeepRGB | python/caffe/draw.py | Python | mit | 7,604 | 0.000395 | """
Caffe network visualization: draw the NetParameter protobuffer.
.. note::
This requires pydot>=1.0.2, which is not included in requirements.txt since
it requires graphviz and other prerequisites outside the scope of the
Caffe.
"""
from caffe.proto import caffe_pb2
"""
pydot is not supported under p... | layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label
def choose_color_by_layertype(layertype):
"""Define colors for nodes based on the layer ... | '#FF5050'
elif layertype == 'Pooling':
color = '#FF9900'
elif layertype == 'InnerProduct':
color = '#CC33FF'
return color
def get_pydot_graph(caffe_net, rankdir, label_edges=True):
"""Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_ne... |
yongshengwang/builthue | desktop/libs/hadoop/src/hadoop/fs/__init__.py | Python | apache-2.0 | 8,724 | 0.010087 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | tp://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,
# WITH | OUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Interfaces and abstractions for filesystem access.
We should be agnostic whether we're using a "temporary" file
system, rooted in a local tmp d... |
Andrew-McNab-UK/DIRAC | AccountingSystem/Agent/test/Test_NetworkAgent.py | Python | gpl-3.0 | 3,707 | 0.021581 | """ Contains unit tests of NetworkAgent module
"""
import DIRAC.AccountingSystem.Agent.NetworkAgent as module
import unittest
from mock.mock import MagicMock
__RCSID__ = "$Id$"
MQURI1 = 'mq.dirac.net::Topic::perfsonar.summary.packet-loss-rate'
MQURI2 = 'mq.dirac.net::Queue::perfsonar.summary.histogram-owdelay'
ROO... | SITE2 )
self.agent.updateNameDictionary()
self.assertEqual( self.agent.nameDictionary[SITE1_HOST1], SITE1 )
self.assertEqual( self.agent.nameDictionary[SITE3_HOST1], SITE3 )
# check if hosts were removed form dictionary
self.assertRaises( KeyError, lambda: self.agent.nameDictionary[SITE1_HOST2] )
... |
def test_agentExecute( self ):
module.NetworkAgent.am_getOption.return_value = '%s, %s' % ( MQURI1, MQURI2 )
module.gConfig.getConfigurationTree.return_value = {'OK': True, 'Value': INITIAL_CONFIG }
# first run
result = self.agent.execute()
self.assertTrue( result['OK'] )
# second run (sim... |
LLNL/spack | var/spack/repos/builtin/packages/folly/package.py | Python | lgpl-2.1 | 1,952 | 0.001537 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Folly(CMakePackage):
"""Folly (acronymed loosely after Facebook Open Source Library) is a... | ding.')
depends_on('boost+context+container cxxstd=14', when='cxxstd=14')
depends_on('boost+context+container cxxstd=17', when='cxxstd=17')
# required d | ependencies
depends_on('gflags')
depends_on('glog')
depends_on('double-conversion')
depends_on('libevent')
depends_on('fmt')
# optional dependencies
variant('libdwarf', default=False, description="Optional Dependency")
variant('elfutils', default=False, description="Optional Dependency"... |
ebressert/ScipyNumpy_book_examples | python_examples/scipy_36_ex2.py | Python | mit | 1,073 | 0.001864 | import numpy as np
from scipy.misc import imread, imsave
from glob import glob
# This function allows us to place in the
# brightest pixels per x and y position between
# two images. It is similar to PIL's
# ImageChop.Lighter function.
def chop_lighter(image1, image2):
s1 = np.sum(image1, axis=2)
s2 = np.sum(i... | float32)
# Same before
im1 += im
# im2 image shows star trails bette | r
im2 = chop_lighter(im2, im)
# Saving image with slight tweaking on the combination
# of the two images to show star trails with the
# co-added image.
imsave('scipy_36_ex2.jpg', im1 / im1.max() + im2 / im2.max() * 0.2)
|
jesopo/bitbot | src/IRCBuffer.py | Python | gpl-2.0 | 3,891 | 0.005911 | import collections, dataclasses, datetime, re, typing, uuid
from src import IRCBot, IRCServer, utils
MAX_LINES = 2**10
@dataclasses.dataclass
class BufferLine(object):
sender: str
message: str
action: bool
tags: dict
from_self: bool
method: str
deleted: bool=False
notes: typing.Dict[... | maxlen=MAX_LINES)
def __len__(self) -> int:
return len( | self._lines)
def add(self, line: BufferLine):
self._lines.appendleft(line)
def get(self, index: int=0, from_self=True, deleted=False
) -> typing.Optional[BufferLine]:
for line in self._lines:
if line.from_self and not from_self:
continue
if l... |
telefonicaid/murano | murano/openstack/common/policy.py | Python | apache-2.0 | 29,785 | 0.000034 | # Copyright (c) 2012 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... | efault dictionary / Rules to use. It will be
considered just in the first instantiation. If
`load_rules(True)`, `clear()` or `set_rules(True)`
is called this will be overwritten.
:param default_rule: Default rule to use, CONF.default_rule will
... | ther to load rules from cache or config file.
:param overwrite: Whether to overwrite existing rules when reload rules
from config file.
"""
def __init__(self, policy_file=None, rules=None,
default_rule=None, use_conf=True, overwrite=True):
self.default_rule = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.