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 |
|---|---|---|---|---|---|---|---|---|
FluidityStokes/fluidity | tests/shocktube_1d/plot.py | Python | lgpl-2.1 | 1,182 | 0.052453 | import pylab
import numpy
import shocktube
import vtktools
folders=['.']
filename='shocktube_50.vtu'
for folder in folders:
vt=vtktools.vtu(folder + '/' + filename)
t=vt.GetScalarField('Time')[0]
xyz=vt.GetLocations()
x=xyz[:,0]
p=vt.GetScala | rField('Pressure')
uvw=vt.GetVectorField('Velocity')
u=uvw[:,0]
rho=vt.GetScalarField('Density')
ie=vt.GetScalarField('InternalEnergy')
pylab.figure(1)
pylab.plot( x, p,'.', label=folder)
pylab.figure(2)
pylab.plot( x, u,'.', label=folder)
pylab.figure(3)
pylab.plot( x, rho,'.', label=folde... | sol[:,2]
ie=p/rho/(shocktube.gamma-1.0)
pylab.figure(1)
pylab.plot( x, p,'-', label='analytical')
pylab.title('Pressure')
pylab.legend()
pylab.figure(2)
pylab.plot( x, u,'-', label='analytical')
pylab.title('Velocity')
pylab.legend()
pylab.figure(3)
pylab.plot( x, rho,'-', label='analytical')
pylab.title('Densit... |
javierip/parallel-code-examples | 03-multi-core-processors/02-python-multiprocessing/multiprocessing-example.py | Python | apache-2.0 | 892 | 0 | from multiprocessing import Pool
from time import time
# Import the same addNumbers function we use for the serial example.
from serie import addNumbe | rs
# map requires a function to handle a single argument
def addNumConverter((low, high)):
return addNumbers(low, high)
def splitRange(low, high):
# take sub-groups of 1e4 numbers
STEP = int(1e4)
r = range(low - 1, | high + 1, STEP)
return zip([x+1 for x in r], r[1:])
if __name__ == '__main__':
# Use 4 processes.
pool = Pool(4)
initialTime = time()
# We're gonna split the entire range [1, 10^9] into sub groups that can be
# individually processed.
subGroups = splitRange(1, 10**9)
result = sum(poo... |
leigh123linux/cinnamon-screensaver | src/widgets/framedImage.py | Python | gpl-2.0 | 4,227 | 0.003549 | #!/usr/bin/python3
# coding: utf-8
import gi
gi.require_version('CinnamonDesktop', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gio, GLib, GObject, Gdk
from util import utils, trackers
MAX_IMAGE_SIZE = 320
MAX_IMAGE_SIZE_LOW_RES = 200
class FramedImage(Gtk.Image):
"""
Widget to hold the user face image... | .path = None
if self.get_realized():
s | elf.generate_image()
def set_image_internal(self, path):
pixbuf = None
scaled_max_size = self.max_size * self.get_scale_factor()
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
except GLib.Error as e:
message = "Could not load pixbuf from '%s' for FramedI... |
sburnett/seattle | softwareupdater/generatekeys.py | Python | mit | 603 | 0.00995 | import repyhelper
# simple keypair creator...
import sys
import random
repyhelper.translate_and_import("rsa.repy")
# need to support random number generation
randomfloat = random.random
pubfn = sys.argv[1]+'.publickey'
privfn = sys.argv[1]+'.privatekey'
if len(sys.argv) == 3:
keylength = int(sys.argv[2])
else:
... | ngth)+"."
print "Thi | s may take a moment..."
keys = rsa_gen_pubpriv_keys(keylength)
rsa_publickey_to_file(keys[0],pubfn)
rsa_privatekey_to_file(keys[1],privfn)
print "Success!"
|
veltzer/demos-python | src/examples/short/multi_core/number_of_cores.py | Python | gpl-3.0 | 417 | 0.002398 | #!/usr/bin/env python
"""
Getting the number of cores via python
Two ways to do it:
- the 'multiprocessing' module.
- the 'os' module.
NOTES:
- in | python2 only 'os' module does not supply a 'cpu_count' function.
References:
- http://stackoverflow.com/questions/1006289/how-to-find-out-the-number-of-cpus-using-python
"""
import multiprocessing
imp | ort os
print(multiprocessing.cpu_count())
print(os.cpu_count())
|
aonotas/chainer | chainer/functions/array/permutate.py | Python | mit | 4,024 | 0 | import numpy
import six
import chainer
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
def _check_indices(indices):
if len(indices) == 0:
return
# TODO(unno): Check indices without cpu
indices = cuda.to_cpu(indices)
for i in indices:
... | ,
def backward(self, indexes, grad_outputs):
inds = self.input | s[1]
g, = grad_outputs
gx, = Permutate(self.axis, not self.inv).apply((g, inds.data))
return gx, None
def permutate(x, indices, axis=0, inv=False):
"""Permutates a given variable along an axis.
This function permutate ``x`` with given ``indices``.
That means ``y[i] = x[indices[i]]... |
keen99/SickRage | sickbeard/notifiers/__init__.py | Python | gpl-3.0 | 3,001 | 0.000333 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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,... | tifier,
trakt_notifier,
email_notifier,
]
def notify_download(ep | _name):
for n in notifiers:
n.notify_download(ep_name)
def notify_subtitle_download(ep_name, lang):
for n in notifiers:
n.notify_subtitle_download(ep_name, lang)
def notify_snatch(ep_name):
for n in notifiers:
n.notify_snatch(ep_name)
def notify_git_update(new_version=""):
... |
cwtaylor/viper | viper/common/abstracts.py | Python | bsd-3-clause | 1,812 | 0.002208 | # This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import argparse
imp | ort viper.common.out as out
from viper.core.config import console_output
class ArgumentErrorCallback(Exception):
def __init__(self, message, level=''):
self.message = message.strip() + '\n'
self.level = level.strip()
def __str__(self):
return '{}: {}'.format(self.level, self.message)
... | f.level, self.message
class ArgumentParser(argparse.ArgumentParser):
def print_usage(self):
raise ArgumentErrorCallback(self.format_usage())
def print_help(self):
raise ArgumentErrorCallback(self.format_help())
def error(self, message):
raise ArgumentErrorCallback(message, 'error'... |
NeuroRoboticTech/Jetduino | Software/Python/setup.py | Python | mit | 2,589 | 0.014677 | #!/usr/bin/python #!/usr/bin/env python
#
# Jetduino Python Setup
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Have a question about this example? Ask on the forums here: http://www.NeuroRoboticTech.com/Foru... | ell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this p | ermission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHO... |
gregelin/python-ideascaleapi | test_sunlightapi.py | Python | bsd-3-clause | 115 | 0 | import doctest
print 'Before | testing be sure to set your key | in README.txt..\n\n'
doctest.testfile('README.rst')
|
comprobo-final-project/comprobo_final_project | comprobo_final_project/scripts/simulator/pose.py | Python | mit | 241 | 0.004149 | """
Custom made pose attri | bute for simulation
"""
import math
from vector_3 import Vector3
from polar_vector import PolarVector
class Pose:
def __init__(sel | f):
self.position = Vector3()
self.velocity = PolarVector()
|
eirmag/weboob | modules/gazelle/test.py | Python | agpl-3.0 | 989 | 0.002022 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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 of the License, or
# (at your... | he implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from weboob.tools.test import Backend... |
if len(l) > 0:
self.backend.get_torrent_file(l[0].id)
|
openstack/keystone | keystone/tests/unit/test_sql_upgrade.py | Python | apache-2.0 | 22,985 | 0 | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | ',
],
'local_user': [
'id', 'user_id', 'domain_id', 'name', 'failed_auth_count',
'failed_auth_at',
],
'password': [
| 'id', 'local_user_id', 'created_at', 'expires_at',
'self_service', 'password_hash', 'created_at_int', 'expires_at_int',
],
'federated_user': [
'id', 'user_id', 'idp_id', 'protocol_id', 'unique_id', 'display_name',
],
'nonlocal_user': [
'domain_id', 'name', 'user_id',
],... |
mzsm/IkaLog | tools/IkaClips.py | Python | apache-2.0 | 6,531 | 0.001432 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA
#
# 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/l... | for clip in self.clips:
if last_clip and last_clip['end'] < clip['start']:
new_clips.append(last_clip)
last_clip = None
i | f last_clip is None:
last_clip = clip
continue
if clip['start'] < last_clip['end']:
last_clip['type'] = '%s+%s' % (last_clip['type'], clip['type'])
last_clip['end'] = clip['end']
if not last_clip is None:
new_clips.append(... |
rbdavid/MolecDynamics | Analysis/MSD/slope.py | Python | mit | 754 | 0.014589 | #!/Library/Frameworks/P | ython.framework/Versions/2.7/bin/python
import numpy as np
import sys
import scipy
from scipy import stats
data_file = sys.argv[1]
data = np.loadtxt(data_file)
slope, intercept, r_value, p_value, std_err = stats.linregress(data[499:2499,0], data[499:2499,1])
nf = open('linear_reg.dat', 'w')
nf.write("Linear Regre... | ps (frame: 499) and %5d ps (frame 2499) \n" %(data[499][0], data[2499][0]))
nf.write("slope: %10.5E Angstrom^2 ps^-1 \n" %(slope))
nf.write("intercept: %10.5E Angstrom^2\n" %(intercept))
nf.write("R^2: %10.5f \n" %(r_value**2))
nf.write('Diffusion coeff: %10.5E Angstrom^2 ps^-1$ \n' %(slope/6.0))
nf.write('Diffusion ... |
pombredanne/pymaven | testsuite.py | Python | apache-2.0 | 260,904 | 0.000034 | #! /usr/bin/env python
# Hi There!
# You may be wondering what this giant blob of binary data here is, you might
# even be worried that we're up to something nefarious (good for you for being
# paranoid!). This is a base64 encoding of a zip file, this zip file contains
# a fully functional basic pytest script.
#
# Pyt... | ErGISJu2xId
BslwAjt9hU0tSoLF49ae5y3SWyINJtF4Xs+WZVXgNo9Tn16oESOZVgfkKh8qCOkwrdIRULBx57hH
Zo0Yag/HrSpXxar2u5gvDqIH/Z79UZwR5HC41B86H29u1upoIMZyG+lH0d0GDoVGX5q6Bx4+N1Ow
z3nx | Xu9NDZylsTAtR8r0n3IT/MMGsSp2gcDpYgMNgrv/PfBhIKXuRgNb5925z7CQ6AROTg1kydG6
LlfMEeuorTfNvGCMJDBcAWwyh1PcaTCX5dl5RzOhftgJOe282+RVdQO7ULYEDCkgzTQN439rJjQc
O6vqeV4lCic2yRiM3wF+f3NaRIt6FXdIfjCZso3m58X8AobwSX+d0TeJR+R3om+//VYgIYzzvFnA
uavKC1xcEV0VZbPAi62ce/3KFTVoO7jccmwD/OgYKXSew0jZZr3IO/79BOZYtF86/XG1ofX5m7oe
2sTlpqp4P7ZvpRzd... |
luqmaan/sass_to_scss | test_sass_to_scss.py | Python | gpl-3.0 | 2,703 | 0.00074 | import logging
from unittest import TestCase
from sass_to_scss import SassToSCSS
class TestSassToSCSS(TestCase):
def setUp(self):
self.sassy = SassToSCSS(loglevel=logging.DEB | UG)
def trim_docstring(self, docstring):
return '\n'.join(docstring.split('\n')[1:-1])
def test_double_spaces(self):
self.sassy.spaces = 2
| sass = """
body
background: red
header
background: blue
"""
scss = """
body {
background: red;
header {
background: blue;
}
}
"""
actual = self.sassy.convert(self.trim_docstring(sass).split('\n'))
expected = self.trim_docstring(scss)
self.assertEquals(expected, actua... |
prashanthr/wakatime | wakatime/packages/pygments_py3/pygments/lexers/smalltalk.py | Python | bsd-3-clause | 7,215 | 0.000416 | # -*- coding: utf-8 -*-
"""
pygments.lexers.smalltalk
~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Smalltalk and related languages.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, include, bygroups, defa... | oken import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctua | tion
__all__ = ['SmalltalkLexer', 'NewspeakLexer']
class SmalltalkLexer(RegexLexer):
"""
For `Smalltalk <http://www.smalltalk.org/>`_ syntax.
Contributed by Stefan Matthias Aust.
Rewritten by Nils Winter.
.. versionadded:: 0.10
"""
name = 'Smalltalk'
filenames = ['*.st']
aliases ... |
bytedance/fedlearner | web_console_v2/api/test/fedlearner_webconsole/job/metrics_test.py | Python | apache-2.0 | 3,305 | 0.000303 | # Copyright 2021 The FedLearner 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... | m testing.common import BaseTestCase, TestAppProcess
from fedlearner_webconsole.proto import workflow_definition_pb2
from fedlearner_webconsole.db import db
from fedlearner_webconsole.workflow.models import Workflow
from fedlearner_webconsole.job.models import Job, JobType
from fedlearner_webconsole.job.metrics import... | est(BaseTestCase):
class Config(BaseTestCase.Config):
ES_HOST = ''
ES_PORT = 80
class FollowerConfig(Config):
GRPC_LISTEN_PORT = 4990
def test_data_join_metrics(self):
job = Job(
name='multi-indices-test27',
job_type=JobType.DATA_JOIN)
import... |
googlearchive/rgc-models | response_model/python/ASM/su_fit_nov/fit_fine.py | Python | apache-2.0 | 6,622 | 0.00891 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | its with localized sparsity prior."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import pickle
from absl import app
from absl import flags
import h5py
import numpy as np
from tensorflow.python.platform import gfile
from retina.response_mo... | ome/bhaishahster/pc2005_08_08_1',
'Where is the cell')
flags.DEFINE_integer('taskid', 0,
'Task Id')
flags.DEFINE_string('tmp_dir',
'/home/bhaishahster/'
'Downloads/pc2005_08_08_1',
'temporary folder on machine for bet... |
cpausmit/Kraken | pandaf/003/mc.py | Python | mit | 20,611 | 0.016545 | from FWCore.ParameterSet.VarParsing import VarParsing
options =VarParsing('analysis')
options.register('config', default = '', mult = VarParsing.multiplicity.singleton, mytype = VarParsing.varType.string, info = 'Single-switch config. Values: 03Feb2017, 23Sep2016, Spring16, Summer16')
options.register('globaltag', def... | e following module is supposed to be | removed from the sequence but is not
# The bug appears when we don't call the no-postfix version of runMetCor.. first
process.fullPatMetSequencePuppi.remove(process.selectedPatJetsForMetT1T2CorrPuppi)
metSequence = cms.Sequence(
process.fullPatMetSequencePuppi
)
if egFix:
### RE-EG-CORRECT METs
# First c... |
synox/telewall | telewall/telewall/web/__init__.py | Python | gpl-3.0 | 123 | 0.02439 | """ T | his Modules allows to manage the blocked callers as an web application that can be access u | sing the WSGI-Standard.
""" |
ibmspp/sppclient | samples/registerhypervisor.py | Python | apache-2.0 | 3,540 | 0.006215 | # Script to register a new hypervisor provider in SPP
# Use registerhypervisor.py -h for help
# Example:
# python registerhypervisor.py --host="https://172.20.49.49" --user="admin" --pass="spppass" --hvtype="hyperv" --hvhost="my.host.name" --hvuser="hvdomain\hvuser" --hvpass="hvpassword"
import json
import logging
fro... | E"):
hvinfo['sslConnection'] = True
else:
hvinfo['sslConnection'] = False
elif(hvinfo['type'] == "hyperv"):
hvinfo['sslConnection'] = False
else:
hvinfo['sslConnection'] = True
if(options.hvssc is not None):
hvinfo['opProperties'] = {'snapshotConcurre... | r_hypervisor(hvinfo):
try:
response = client.SppAPI(session, 'spphv').post(data=hvinfo)
print options.hvhost + " is registered"
except client.requests.exceptions.HTTPError as err:
errmsg = json.loads(err.response.content)
print errmsg['response']['description']
validate_input()
... |
interlegis/sigi | sigi/apps/home/templatetags/menus.py | Python | gpl-2.0 | 607 | 0 | from os.path import dirname
import yaml
from django import template
register = template.Library()
menus = yaml.load(open(dirname(__file__) + '/menu_conf.yaml', 'r'))
@register | .inclusion_tag('menus/menu.html', takes_context=True)
def show_menu(context, menu_id):
base_url = context['request'].build_absolute_uri('/') |
menus = yaml.load(open(dirname(__file__) + '/menu_conf.yaml', 'r'))
return dict(menu_items=menus[menu_id], base_url=base_url)
@register.inclusion_tag('menus/menu_item.html')
def show_menu_item(menu_item, base_url):
return dict(menu_item=menu_item, base_url=base_url)
|
hotpxl/mxnet | example/gluon/word_language_model/model.py | Python | apache-2.0 | 2,085 | 0.001918 | import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn, rnn
class RNNModel(gluon.Block):
"""A model with an encoder, recurrent layer, and a decoder."""
def __init__(self, mode, vocab_size, num_embed, num_hidden,
num_layers, dropout=0.5, tie_weights=False, **kwargs):
sup... | g(vocab_size, num_embed,
weight_initializer=mx.init.Uniform(0.1))
if mode == 'rnn_relu':
self.rnn = rnn.RNN(num_hidden, 'relu', num_layers, dropout=dropout,
input_size=num_embed)
elif mode == 'rnn_tanh':
... | rnn.LSTM(num_hidden, num_layers, dropout=dropout,
input_size=num_embed)
elif mode == 'gru':
self.rnn = rnn.GRU(num_hidden, num_layers, dropout=dropout,
input_size=num_embed)
else:
raise ValueE... |
mrslow/DeployToolKit | deploytoolkit/deploytoolkit.py | Python | gpl-3.0 | 4,885 | 0.000491 | # -*- coding: utf-8 -*-
import yaml
import os
from fabric.api import run, env, cd
class DeployToolKit(object):
"""
Класс реализует методы для управления проектом удаленном сервере:
создание и удаление директорий, установка зависимостей, публикация новых
изменений и откат к старым релизам.
"""
... | n("mkdir -p {path}".format(path=env.project_root))
def delete_dir(self):
"""Удаление папки проекта со всем содержимым"""
run("rm -rf {path}".format(path=env.project_root))
def pip_install_requirements(self, requirements=None):
"""Установка библиотек через pip"""
req_command =... | {requirements}"
if not requirements:
self.pip(req_command.format(requirements=env.requirements))
else:
self.pip(req_command.format(requirements=requirements))
def control_service(self, action="restart", service=None):
"""Метод для изменения состояния какого-либо серв... |
srinivasanmit/all-in-all | 1/ex2.py | Python | gpl-3.0 | 248 | 0.008065 | # A comment
# Anything after # is ignored by python
print "I could have code like this." # and the comment after is ignored
# You can also use a commen | t to "disable" or comment out a piece of code
# print "This won't run"
print | "This won't not run" |
videntity/django-fhir | fhir/views/oauth.py | Python | gpl-2.0 | 1,327 | 0.005275 |
from oauth2_provider.decorators import protected_resource
from django.views.decorators. | http import require_POST
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .create import create
from .update import update
from .delete import delete
from .read import read
@require_POST
@protected_resource()
def oauth_create(request, ... | ype):
if request.method == "POST":
return create(request, resource_type)
return HttpResponse(status=501)
@protected_resource()
def oauth_read_or_update_or_delete(request, resource_type, id):
"""Route to read, update, or delete based on HTTP method FHIR Interaction"""
if request.method =... |
youtube/cobalt | build/android/pylib/utils/maven_downloader.py | Python | bsd-3-clause | 4,864 | 0.007607 | #!/usr/bin/env vpython
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import errno
import logging
import os
import shutil
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
i... | arget_repo)
for artifact in artifacts]
if self._debug:
for downloader in downloaders:
downloader.Run(include_poms)
else:
parallelizer.SyncParallelizer(downloaders).Run(include_poms)
logging.info('%d artifacts installed to %s', len(artifacts), target_repo)
@property
... | return self._debug
class _SingleArtifactDownloader(object):
'''Handles downloading and installing a single Maven artifact.'''
_POM_FILE_TYPE = 'pom'
def __init__(self, download_manager, artifact, target_repo):
self._download_manager = download_manager
self._artifact = artifact
self._target_repo =... |
anonymous-ijcai/dsw-ont-ijcai | dswont/relation_type.py | Python | gpl-3.0 | 23,259 | 0.006793 | from collections import OrderedDict, defaultdict, Counter
from sklearn import cross_validation
from sklearn.dummy import DummyClassifier
from sklearn.base import BaseEstimator, clone
from sklearn.grid_search import GridSearchCV, BaseSearchCV
from sklearn.metrics.metrics import classification_report
from sklearn import ... | 'p': 'part', 'i': 'instance', 'r': 'related'})
def parse_line(line):
title_parent, title_child_label = line.split(' -> ')
title_child, label = title_child_label.strip().split()
topic_parent = tit | le_parent.replace('_', ' ')
topic_child = title_child.replace('_', ' ')
type_ = RelationType.by_name(translate_label[label]).name.capitalize()
return topic_parent, topic_child, type_
with open(filename, encoding='UTF-8', mode='r') as file:
data = []
for line in file.readline... |
kumar303/jstestnet | jstestnet/work/models.py | Python | apache-2.0 | 4,167 | 0.00096 | import logging
from django.db import models
from common.stdlib import json
from jstestnet.system.models import TestSuite
from jstestnet.system.useragent import parse_useragent
log = logging.getLogger('jstestnet')
class Worker(models.Model):
user_agent = models.CharField(max_length=255)
last_heartbeat = mo... | e do something here if a worker
# has died while running the test (i.e. it will never finish)
q = TestRunQueue.objects.filter(test_run=self,
work_queue__finished=False)
return q.count() == 0
class | WorkQueue(models.Model):
worker = models.ForeignKey(Worker)
# The cmds should match those in media/js/system/work.js
cmd = models.CharField(max_length=25,
choices=((f,f) for f in
['run_test','reload','change_rate']))
cmd_args = models.TextFi... |
gilramir/instmake | instmakelib/jsonconfig.py | Python | bsd-3-clause | 999 | 0.003003 | """
Read a dictionary from a JSON file,
and add its contents to a Python dictionary.
"""
import json
import types
from instmakelib import rtimport
INSTMAKE_SITE_DIR = "instmakesite"
# These are the supported field names
# ===================================
# The name of the plugin (without ".py") for logging
# usa... | normpath"
def update(caller_config, json_filename):
# This will throw errors
fh = open(json_filename)
file_config = json.load(fh)
fh.close()
assert type(file_config) == types.DictType
caller_config.update(file_config)
def load_site_plugin(name):
"""Import a plu | gin from the instmakesite directory.
The import can throw exceptions that the caller has to
catch."""
plugin_name = INSTMAKE_SITE_DIR + "." + name
return rtimport.rtimport(plugin_name)
|
anoidgit/padavan | tools/redirectOptimize.py | Python | gpl-3.0 | 1,408 | 0.057528 | #encoding: utf-8
import os
import sys
def getcmd(src):
ind = src.find("redirectOptimize.py")
ld=src[:lind]
t=src[lind:]
ind=t.find(";")
if ind==-1:
rd=""
core=t
else:
rd=t[ind:]
core=t[:ind]
return ld, core, rd
def gncore(tin, old, | new):
tmp=tin.split(" ")
tin[-1]=new
tin[-2]=old
return " ".join(tin)
def rebuildcmd(srcmd, ostr, nstr):
l, core, r = getcmd(srcmd)
return "".join((l, gncore(core, ostr, nstr), r,))
def rfile(fname, old, new):
cache = []
rwt = False
try:
with open(fname) as f:
for line in f:
tmp = line.strip("\r\n"... | tmp = tmp.decode("utf-8")
if tmp.find("redirectOptimize.py")!=-1:
tmp=rebuildcmd(tmp, old, new)
rwt=True
else:
if tmp.find(old)!=-1:
tmp = tmp.replace(old,new)
rwt = True
cache.append(tmp)
except:
rwt = False
if rwt:
while not cache[-1].strip():
del cache[-1]
cache.a... |
moto-timo/ironpython3 | Src/StdLib/Lib/subprocess.py | Python | apache-2.0 | 64,399 | 0.000916 | # subprocess - Subprocesses with accessible I/O streams
#
# For more information about this module, see PEP 324.
#
# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
#
# Licensed to PSF under a Contributor Agreement.
# See http://www.python.org/2.4/license for licensing details.
r"""subprocess - Subpr... | s not thread safe, using it in the presence of threads |
could lead to a deadlock in the child process before the new executable
is executed.
If close_fds is true, all file descriptors except 0, 1 and 2 will be
closed before the child process is executed. The default for close_fds
varies by platform: Always true on POSIX. True when stdin/stdout/stderr
are None on Window... |
GoogleCloudPlatform/datacatalog-connectors-rdbms | google-datacatalog-rdbms-connector/src/google/datacatalog_connectors/rdbms/prepare/datacatalog_entry_factory.py | Python | apache-2.0 | 7,500 | 0 | #!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (columns)
return entry_i | d, entry
@staticmethod
def __convert_date_value_to_epoch(date_value):
if pd.notnull(date_value):
return int(date_value.timestamp())
@staticmethod
def __convert_source_system_timestamp_fields(raw_create_time,
raw_update_time):
... |
ainur-fa/python_training_1 | test/test_del_group.py | Python | apache-2.0 | 946 | 0.006342 | # -*- coding: utf-8 -*-
from random import randrange
from model.group import Group
import random
import pytest
def test_delete_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app | .group.create(Group(name = "test"))
with pytest.allure.step("Given a group list"):
old_groups = db.get_group_list()
with pytest.allure.step("When get random group | "):
group = random.choice(old_groups)
with pytest.allure.step("When I delete %s" %group):
app.group.delete_group_by_id(group.id)
with pytest.allure.step("Then the new group list is equal to the old list with the deleted group"):
new_groups = db.get_group_list()
assert len(old_gro... |
alfredodeza/pacha | setup.py | Python | mit | 3,200 | 0.013438 | import distribute_setup
distribute_setup.use_setuptools()
from setuptools import setup
tests_require = ['pytest']
setup(
name = "pacha",
version = "0.3.0",
packages = ['pacha'],
install_requires = [
'supay==0.0.7',
'guachi==0.0.6',
'coima==0.0.2'],
entry_points = {
... | guration file to manage the package to be installed and one directory where you can place any number of executable shell scripts to extend and modify your deployment according to your needs.
Versioned Configurations
----------------------------
Keep track of any changes done to a configuration file and rollback easily... | Mercurial, GIT and SVN to version your configurations.
Light
---------
Deploy Pacha as a client, server, or standalone version. Either way, you get an extremely light, low memory tool that can communicate with your configuration files almost instantly.
Extend and Conquer
------------------------
Forget about the "but... |
Christewart/bitcoin | test/functional/test_framework/test_node.py | Python | mit | 17,404 | 0.00316 | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Class for bitcoind node under test"""
import contextlib |
import decimal
import errno
from enum import Enum
import http.client
import json
import logging
import os
import re
import subproc | ess
import tempfile
import time
import urllib.parse
import collections
from .authproxy import JSONRPCException
from .util import (
append_config,
delete_cookie_file,
get_rpc_proxy,
rpc_url,
wait_until,
p2p_port,
)
# For Python 3.4 compatibility
JSONDecodeError = getattr(json, "JSONDecodeError"... |
lstep/deblib | setup.py | Python | gpl-2.0 | 1,409 | 0.023421 | from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import deblib
setup(name="DebLib",
version=deblib.__version__,
author = "Adelux",
author_email = "luc stepniewski at adelux.fr",
download_url = "http://code.google.com/p/deblib",
license = "G... | ily access/search Debian packages",
long_description = """
deblib is a simple module for Python that allows you to look at the debian packa | ges database.
For example, it allows you to ask if a specific version of a package exist on the tested system.
deblib has been created to facilitate the development of the dsacheck project.""",
url = "http://code.google.com/p/deblib",
zip_safe = True,
packages = find_packages(exclude=['tests','ez_set... |
jalilag/apspir | objedit/gnosis/anon/encode_address.py | Python | lgpl-2.1 | 3,832 | 0.032098 | #!/home/gnosis/bin/python
#-- Let's define the en/decryption functions (crude for now)
def xor_key(key):
"Produce 100 bytes of key-based pseudo-random bits"
import sha
s = ""
for _ in range(5):
s += sha.sha(s+key).digest()
return s
def crypt(key, s, decrypt):
"""En/decrypt a string wi... | % ord(c) for c in s]:
for c in hexrep:
bits.extend(hex2bits[c])
return bits
def ascii_huffman_decode(enc, decmap, decrypt=lambda k,s:s, key=None):
"Restore an huffman encoded 7-bit string"
s = ("%s%s\n" % (enc,"="*(len(enc)%4))).decode('base64')
plain = decrypt(key, s)
bits = st... | ap[tuple(bits[head:pos])])
head = pos
return "".join(decoded)
#-- General utility functions
def address_like(s):
import re
return re.match(r'[\w_+./!-]+@([\w-]+\.)+[A-Za-z]{2,4}', s)
if __name__=='__main__':
import sys, os
key = open('ANONYM_PASSPHRASE').readlines()[0]
encmap, decm... |
barbarahui/harvester | test/test_dedupe_sourceresource.py | Python | bsd-3-clause | 2,267 | 0.004411 | from unittest import TestCase
import json
from test.utils import DIR_FIXTURES
from harvester.post_processing import dedupe_sourceresource
class DeduperTestCase(TestCase):
def setUp(self):
self.path_to_test_doc = DIR_FIXTURES+'/couchdb_doc_with_dups.json'
# reference to check against, as doc will b... | qual(self.reference_doc['isShownAt'],
new_doc['isShownAt'])
self.assertNotEqual(self.reference_doc['sourceResource'],
new_doc['sourceR | esource'])
self.assertEqual(len(new_doc['sourceResource']['relation']), 6)
self.assertEqual(new_doc['sourceResource']['relation'],
[u'http://www.oac.cdlib.org/findaid/ark:/13030/ft6k4007pc',
u'http://bancroft.berkeley.edu/collections/jarda.html',
u'hb158005k9... |
Delosari/dazer | bin/lib/ssp_functions/ssp_Hector_Fit3D_mix.py | Python | mit | 45,180 | 0.0278 | #-------------------------------------------------------------------------------------
from bin.dazer_methods import Dazer
from bin.lib.ssp_functions.ssp_synthesis_tools import ssp_fitter
#-------------------------------------------------------------------------------------
#!/usr/bin/python
import sys
import numpy ... | =float_(data[8])
MAX_W=float_(data[9])
if len(sys.argv) == 16:
min=float_(sys.argv[7])
max=float_(sys.argv[8])
min_wave=sys.argv[9]
max_wave=sys.argv[10]
elines_mask=sys.argv[11]
input_redshift=float_(sys.argv[12])
input_d_redshift=float_(sys.argv[13])
input_min_redshift=float_(sys.argv[... | min_redshift
max_redshift=input_max_redshift
deft=2
line=f.readline()
data=line.split(" ")
data=filter(None,data)
sigma=data[0]
d_sigma=data[1]
min_sigma=data[2]
max_sigma=data[3]
if len(sys.argv) == 20:
min=float_(sys.argv[7])
max=float_(sys.argv[8])
min_wave=sys.argv[9]
max_wave=sys.argv[10]
... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/desktop/libs/indexer/src/indexer/api.py | Python | gpl-2.0 | 9,276 | 0.00884 | #!/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... | .get_collections()
for collection in collections:
if collection.get('name') in solr_collections:
# Remove collection and instancedir
searcher.delete_collection(collection.get('name'), collection.get('isCoreOnly'))
response['status'] = 0
response['message'] = _('Collections removed!')... | llection):
if request.method != 'GET':
raise PopupException(_('GET request required.'))
response = {}
searcher = CollectionManagerController(request.user)
unique_key, fields = searcher.get_fields(collection)
response['status'] = 0
response['fields'] = [(field, fields[field]['type'], fields[field].get... |
aroth-arsoft/arsoft-python | python3/arsoft/m3u8/mixins.py | Python | gpl-3.0 | 1,360 | 0.000735 |
import os
from .parser import is_url
try:
import urlparse as url_parser
except ImportError:
import urllib.parse as url_parser
def _urijoin(base_uri, path):
if is_url(base_uri):
return url_parser.urljoin(base_uri, path)
else:
return os.path.normpath(os.path.join(base_uri, path.strip('... | ot self.base_path:
self.uri = "%s/%s" % (newbase_path, self.uri)
self.uri = self.uri.replace(self.base_path, newbase_path)
class GroupedBasePathMixin(object):
def _set_base_uri(self, new_base_uri):
for item in self:
item.base_uri = new_base_uri
base_uri = property(Non... | e_path = newbase_path
base_path = property(None, _set_base_path)
|
evernote/zing | pootle/migrations/0002_duedate_path_unique.py | Python | gpl-3.0 | 590 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
f | rom django.db import migrations, models
import pootle.models.duedate
class Migration(migrations.Migration):
dependencies = [
("pootle", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="duedate",
name="pootle_path",
field=models.Char... | dels.duedate.validate_pootle_path],
),
),
]
|
matejm/advent-of-code-2016 | day05.py | Python | mit | 704 | 0.00142 | import has | hlib
door_id = input()
password1 = []
password2 = list('________')
pass2_count = 0
for i in range(10**10):
s = door_id + str(i)
m = hashlib.md5()
m.update(s.encode('utf8'))
if m.hexdigest()[:5] == '00000':
print(s, m.hexdigest(), '{}%'.format((len(password1) + pass2_count) / 0.16))
d... | t(digit)] == '_':
password2[int(digit)] = m.hexdigest()[6]
pass2_count += 1
if len(password1) == 8 and pass2_count == 8:
break
print('#1', ''.join(password1))
print('#2', ''.join(password2))
|
chanceraine/nupic.research | tests/union_pooling/union_pooler_test.py | Python | agpl-3.0 | 4,882 | 0.003482 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | maxBoost=1.0,
seed=42,
spVerbosity=0,
wrapAround=True,
# union_pooler.py parameters
| activeOverlapWeight=1.0,
predictedActiveOverlapWeight=10.0,
maxUnionActivity=0.20,
exciteFunctionType='Fixed',
decayFunctionType='NoDecay')
def testDecay... |
diogocs1/comps | web/addons/mrp/wizard/mrp_workcenter_load.py | Python | apache-2.0 | 2,222 | 0.006751 | # -*- coding: utf-8 -*-
####################################################################### | #######
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Genera | l Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR ... |
fredzannarbor/pagekicker-community | scripts_python_3/bitcoin/fortune/pk21server.py | Python | apache-2.0 | 700 | 0.005714 | #!/usr/bin/env python3
import subprocess
from flask import Flask
from two1.wallet import Wallet
from two1.bitserv.flask import Pa | yment
app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)
# machine-payable endpoint that returns fortune if payment made
@app.route('/buy')
@payment.required(1000)
def buy_fortune():
fortune = subprocess.check_output(['fortune', 'potterfacts'])
return fortune
@app.route('/manifest')
... | as f:
manifest_yaml = yaml.load(f)
return json.dumps(manifest_yaml)
if __name__ == '__main__':
app.run(host='0.0.0.0')
|
edwardzhu/checkio-solution | EmpireOfCode/common/Adamantite Mines/strlen.py | Python | mit | 391 | 0.017903 | def str_length(line):
return len(line)
if __name__ == '__main__':
# These "asserts" using only f | or self-checking and not necessary for auto-testing
assert str_length("") == 0, "1st example";
assert str_length("mo") == 2, "2st example";
assert str_length("length") == 6, "3st example";
print("Code's finis | hed? Earn rewards by clicking 'Check' to review your tests!") |
wangtaoking1/found_website | 项目代码/Login.py | Python | gpl-2.0 | 2,910 | 0.009702 | # !/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import base64
import re
import json
import hashlib
'''该登录程序是参考网上写的'''
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.ins... | rlCallBack',
'returntype': 'META'
} |
def get_servertime():
url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=dW5kZWZpbmVk&client=ssologin.js(v1.3.18)&_=1329806375939'
data = urllib2.urlopen(url).read()
p = re.compile('\((.*)\)')
try:
json_data = p.search(data).group(1)
... |
etingof/pysnmp | examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py | Python | bsd-2-clause | 3,865 | 0.000776 | """
Bulk walk Agent MIB (SNMPv2c)
+++++++++++++++++++++++++++++
Perform SNMP GETBULK operation with the following options:
* with SNMPv2c, community 'public'
* over IPv4/UDP
* to an Agent at demo.snmplabs.com:161
* for OID in tuple form
* with non-repeaters=0 and max-repeaters=25
This script performs similar to the ... | transportDomain, transportAddress,
wholeMsg, reqPDU=reqPDU, headVars=headVars):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message())
rspPDU = v2c.apiMessage.getPDU(rspMsg)
# Match response to request
if v2c.apiBulkPDU.getRequestID(reqPD... | Check for SNMP errors reported
errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU)
if errorStatus and errorStatus != 2:
errorIndex = v2c.apiBulkPDU.getErrorIndex(rspPDU)
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex ... |
probml/pyprobml | scripts/healthy_levels_plot.py | Python | mit | 8,021 | 0.010348 | # Based on https://github.com/probml/pmtk3/blob/master/demos/healthyLevels.m
# Converted by John Fearns - jdf22@infradead.org
# Josh Tenenbaum's Healthy Levels game
import superimport
import numpy as np
import matplotlib.pyplot as plt
#from pyprobml_utils import save_fig
# Ensure stochastic reproducibility.
np.rando... | )
plt.xlim(0.2, 0.7)
plt.ylim(0.3, 0.8)
def plot_bayes(data):
top_n = [3, 12]
for i in range(len(top_n)):
plot_data = data[:top_n[i]]
plot_contour(plot_data, i == len(top_n)-1)
def pl | ot_contour(data, is_last_plot):
# Prepare plot x-y points in various shapes.
n = data.shape[0]
stepsize = 0.01
x = np.arange(0.00, 1.0, stepsize) + 0.01
y = x
xx, yy = np.meshgrid(x, y)
points = np.column_stack([xx.reshape(-1, 1), yy.reshape(-1, 1)])
# Predictive distribution: T... |
gaolichuang/py-task-framework | nova/utils.py | Python | apache-2.0 | 36,910 | 0.001355 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
#... | = [
cfg.BoolOpt('monkey_patch',
default=False,
help='Whether to log monkey patching'),
cfg.ListOpt('monkey_patch_modules',
default=[
'nova.api.ec2.cloud:%s' % (notify_dec | orator),
],
help='List of modules/decorators to monkey patch'),
]
utils_opts = [
cfg.IntOpt('password_length',
default=12,
help='Length of generated instance admin passwords'),
cfg.StrOpt('instance_usage_audit_period',
default='month... |
mtzirkel/leakyskiff | manage.py | Python | mit | 802 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "boat.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... | really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment v... | irtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
odtvince/APITaxi | APITaxi/documentation/index.py | Python | agpl-3.0 | 381 | 0.007874 | # -*- coding: utf-8 -*-
fr | om flask import Blueprint, render_template
from flask.ext.security import current_user
mod = Blueprint('documentation', __name__)
@mod.route('/documen | tation')
@mod.route('/documentation/index')
def doc_index():
return render_template('documentation/index.html',
apikey='token' if current_user.is_anonymous else current_user.apikey)
|
mikhaelharswanto/ryu | ryu/lib/xflow/sflow.py | Python | apache-2.0 | 15,509 | 0.000193 | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
#
# 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 applicab... | um = flow_records_num
self.flow_recor | ds = flow_records
@classmethod
def parser(cls, buf, offset):
(sequence_number, source_id, sampling_rate,
sample_pool, drops, input_if, output_if,
flow_records_num) = struct.unpack_from(cls._PACK_STR, buf, offset)
index_mask = 0xffffff
type_shiftbit = 24
sourc... |
acesonl/remotecare | remotecare/apps/report/__init__.py | Python | gpl-3.0 | 216 | 0 | # -*- codi | ng: utf-8 -*-
"""
Automatic generated reports can be edited by an healthprofessional during
handling filled in controls (questionnaires) by a patient. The report
can be exported in docX and PDF format | .
"""
|
pignacio/var-log-recetas | var_log_recetas/manage.py | Python | gpl-3.0 | 264 | 0.003788 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "var_log_recet | as.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.a | rgv)
|
frkwy/oozappa | sample/ops/staging/fabfile/__init__.py | Python | mit | 1,594 | 0.00941 | # -*- coding:utf8 -*-
from fabric.api | import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys |
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
pri... |
jmbeuken/abinit | doc/tutorial/lesson_spin/magnetization.py | Python | gpl-3.0 | 2,507 | 0.02872 | #!/usr/bin/env python
import os,string,sys,math
#CUT3D="../../../../src/98_main/cut3d"
CUT3D="cut3d"
#First find the coordinates of atoms
f=open('first_round','w')
f.write("tspin_2o_DEN\n")
f.write("1\n3\n0\n0\n")
f.close()
start_atomic=0
atomic_positions=[]
for line in os.popen(CUT3D+"< first_round").readlines():
... | x=x0+i*cube_step
y=y0+j*cube_step
z=z0+k*cube_step
#if((x-x0)**2+(y-y0)**2+(z-z0)**2<radius**2):
f.write('1'+"\n"+'1'+'\n'+'1'+'\n')
f.write(`x`+' '+`y`+' '+`z`... | sphere").readlines():
if string.find(line,"Spin difference")!=-1:
npts_integral=npts_integral+1
g.write(string.split(line)[4]+'\n')
sum=sum+string.atof(string.split(line)[4])
integral.append(sum/npts_integral)
#Compute magn... |
darren-rogan/CouchPotatoServer | libs/sqlalchemy/types.py | Python | gpl-3.0 | 81,874 | 0.004043 | # sqlalchemy/types.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""defines genericized SQL types, each represented by a subclass of
:class:`~sqlal... | send to the DB-API.
If processing is not necessary, the method should return ``None``.
:param dialect: Dialect instance in use.
"""
| return None
def result_processor(self, dialect, coltype):
"""Return a conversion function for processing result row values.
Returns a callable which will receive a result row column
value as the sole positional argument and will return a value
to return to the user.
I... |
donspaulding/adspygoogle | examples/adspygoogle/dfp/v201204/deactivate_labels.py | Python | apache-2.0 | 2,216 | 0.00361 | #!/usr/bin/python
#
# Copyright 2012 Google 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 b... | in labels:
print ('Label with id \'%s\' and name \'%s\' will be '
'deactivated.' % (label['id'], label['name']))
print 'Number of Labels to be deactivated: %s' % len(labels)
# Perform action.
result = label_service.PerformLabelAction({'type': 'DeactivateLabels'},
{... | ay results.
if result and int(result['numChanges']) > 0:
print 'Number of labels deactivated: %s' % result['numChanges']
else:
print 'No labels were deactivated.'
|
CyrilWaechter/pyRevitMEP | lib/pyrevitmep/parameter/managefamily.py | Python | gpl-3.0 | 8,098 | 0.001729 | # coding: utf8
import os
import re
import tempfile
from System.ComponentModel import ListSortDirection, SortDescription
from System.Collections.ObjectModel import ObservableCollection
from Autodesk.Revit.ApplicationServices import Application
from Autodesk.Revit.DB import Document
from Autodesk.Revit import Exception... | ically"""
column = datagrid.Columns[column_index]
| # Clear current sort descriptions
datagrid.Items.SortDescriptions.Clear()
# Add the new sort description
datagrid.Items.SortDescriptions.Add(SortDescription(column.SortMemberPath, list_sort_direction))
# Apply sort
for col in datagrid.Columns:
col.SortDirection =... |
bradsokol/PyLCP | setup.py | Python | bsd-3-clause | 2,835 | 0.001411 | # Necessary to supress on error in Python 2.7.3 at the completion of
# python setup.py test.
# See http://bugs.python.org/issue15881#msg170215
import multiprocessing # NOQA
import distutils.command.clean
import os
import pkg_resources
import setuptools
import subprocess
class Clean(distutils.command.c | lean.clean):
def run(self):
subprocess.call('find . -name *.pyc -delete'.split(' '))
subprocess.call('rm -rf *.egg/ test_results/ .coverage .noseids'.split(' '))
distutils.command.clean.clean.run(self)
def read_file(file_name):
"""Utility function to read a file."""
return open(os.... | e specified file."""
with open(os.path.join(os.path.dirname(__file__), file_name)) as f:
return f.readline().strip()
def read_requirements(file_path):
return [
i.strip()
for i in pkg_resources.resource_string(__name__, file_path).split()
if i.strip()[0:1] != '#' and i.strip()[0... |
Nic30/hwtLib | setup.py | Python | mit | 1,564 | 0.001918 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from os import path
from setuptools import setup, find_packages
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='hwtLib',
version='2.9',
... | ",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Scientific/Engineering :: Electronic Design Auto... | tion (EDA)",
"Topic :: System :: Hardware",
"Topic :: System :: Emulators",
"Topic :: Utilities"
],
install_requires=[
'hwt>=3.8',
],
license='MIT',
packages=find_packages(),
package_data={'hwtLib': ['*.vhd', '*.v', '*.png', "*.cpp"]},
include_pa... |
fxfitz/ansible | lib/ansible/modules/cloud/azure/azure_rm_storageaccount.py | Python | gpl-3.0 | 18,878 | 0.003337 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# 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
ANS... | resource_group = self.get_resource_group(self.resource_group)
if not self.location:
# Set default location
self.location = resource_group.location
if len(self.name) < 3 or len(self.name) > 24:
self.fail("Parameter error: name length must be between 3 and 24 chara... | ting custom_domain to have a name attribute of type string.")
if self.custom_domain.get('use_sub_domain', None) is None:
self.fail("Parameter error: expecting custom_domain to have a use_sub_domain "
"attribute of type boolean.")
self.account_dict = self.ge... |
wukong-m2m/NanoKong | master/wkpf/wkpfcomm.py | Python | gpl-2.0 | 15,103 | 0.017348 | import sys, time, copy
from wkpf.transport import *
from wkpf.locationTree import *
from wkpf.models import *
from wkpf.globals import *
from wkpf.configuration import *
# routing services here
class Communication:
_communication = None
@classmethod
def init(cls):
if not cls._communication:
c... | es = []
reply = reply.payload[3:]
print repr(reply)
while len(re | ply) > 1:
wuClassId = (reply[0] <<8) + reply[1]
isVirtual = True if reply[2] == 1 else False
wuclass = None
print 'begin wuclass_query'
wuclass_query = WuClass.where(node_id=destination, id=wuClassId)
print 'end wuclass_query', wuclass_query
if not wuclass_query:
... |
tiagolbiotech/BioCompass | BioCompass/tests/test_BioCompass.py | Python | bsd-3-clause | 1,027 | 0.006816 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from click.testing import C | liRunner
from BioCompass import cli
def test_importcli():
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
#assert 'BioCompass.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
#assert 'Usage: main... | ioCompass.BioCompass import find_category_from_product
def test_find_category_from_product():
df = pd.DataFrame(
{'product': ['permease', 'bla bla permease bla bla']})
out = find_category_from_product(df)
assert (out['category'] == 'transporter').all()
def test_find_category_from_product_hypoth... |
Ingesup-Lab-OS/OS-Lend-Frontend | lend_frontend/tests/api_mock.py | Python | apache-2.0 | 2,035 | 0 | import datetime
class FakeHeatTemplateManager(object):
def __init__(self):
self.templates = {
1: 'Dummy description #1.',
3: 'Dummy description #3.',
4: 'Dummy descr | iption #4.',
6: 'Dummy description #6.'}
def get_description(self, template_id):
return self.templates[template_id]
def list_templates(self):
return self.templates.keys()
class FakeNovaAPI(object):
def __init__(self):
self.flavors = {
1: {
... | return self.flavors.keys()
class FakeHeatAPI(object):
def __init__(self):
self.stacks = {
'stack1': {
'email': 'dummy1@localhost', },
'stack2': {
'email': 'dummy2@localhost', }}
self.expired_stacks = {
'stack3': {
... |
Aloomaio/googleads-python-lib | examples/adwords/v201809/basic_operations/update_expanded_text_ad.py | Python | apache-2.0 | 2,330 | 0.006438 | #!/usr/bin/env | python
#
# 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 Li | cense at
#
# https://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... |
robcarver17/pysystemtrade | sysdata/base_data.py | Python | gpl-3.0 | 1,868 | 0.002141 | from syslogdiag.log_to_screen import logtoscreen
class baseData(object):
"""
Core data object - Base class
simData objects are used to get data from a particular source, and give certain information about it
The baseData class is highly generic
Normally we'd inherit from this for specific imple... | : use a class where it has been overriden"
)
def keys(self):
"""
list of things in this data set (futures contracts, instruments...)
:returns: list of str |
>>> data=simData()
>>> data.keys()
[]
"""
raise Exception(
"keys() not defined for baseData class: use a class where it has been overriden"
)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
martinrusev/amonone | amon/apps/notifications/generator.py | Python | mit | 5,806 | 0.007751 | import logging
from amon.apps.alerts.models import alerts_model, alerts_history_model, alert_mute_servers_model
from amon.apps.servers.models import server_model
from amon.apps.processes.models import process_model
from amon.apps.plugins.models import plugin_model
from amon.apps.devices.models import volumes_model
fro... | trigger.get('volume')
metadata = volumes_model.get_by_id(volume_id)
if metric_type in ['network/inbound', 'network/outbound']:
interface_id = trigger.get('interface')
metadata = interfaces_model.get_by_id(interface_id)
if rule_type == 'process_... | d(server_id=server_id, name=process_name)
if rule_type == 'plugin_global':
gauge_name = alert.get('gauge')
plugin_name = alert.get('plugin')
result.plugin = plugin_model.get_by_name_and_server_id(server_id=server_id, name=plugin_name)
result.g... |
r0ro/tools | flv_dissector.py | Python | mit | 6,068 | 0.02439 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from struct import *
import hashlib
if len(sys.argv) != 2:
print("Usage " + sys.argv[0] + " input_file")
sys.exit(1)
in_name = sys.argv[1]
def dumpHeader(f):
# check for signature
sig = f.read(3)
if sig != b'FLV':
... | dataSize))
return False
lastTimestamp = t | imestamp
# dump payload
if tagType == 9:
# video
if not dumpVideoPayload(payload):
return False
elif tagType == 8:
if not dumpAudioPayload(payload):
return False
return True
with open(in_name, 'rb') as f:
try:
if not dumpHeader(f):
print("Invalid FLV header", file=sys.stde... |
cms-btv-pog/rootpy | rootpy/extern/progressbar/widgets.py | Python | gpl-3.0 | 11,900 | 0.000168 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# progressbar - Text progress bar library for Python.
# Copyright (c) 2005 Nilton Volpato
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; ei... | turn scaled, power
def update(self, pbar):
'Updates the widget with the current SI | prefixed speed.'
if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0
scaled = power = 0
else:
scaled, power = self._speed(pbar)
return self.format % (scaled, self.prefixes[power], self.unit)
class AdaptiveTransferSpeed(FileTransferSpeed):
'Widget for s... |
itmages/itmages-service | itmagesd/iomod.py | Python | gpl-2.0 | 10,896 | 0.005231 | #
# -*- coding: utf-8 -*-
#
# Copyright 2011 Voldemar Khramtsov <harestomper@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the L... | on = action
return True
else:
return False
def set_default(self, **kw):
self.useragent = kw.get('useragent') or USERAGENT
self.verbose = kw.get('verbose') in (True, 1)
self.activeurl = kw.get('url') or self.a | ctiveurl
filename = kw.get('filename')
self.addition = kw.get('addition') or filename
self.cookiedir = COOKIEDIR
self.proxyport = kw.get('proxyport')
self.proxynode = kw.get('proxynode')
self.proxyuser = kw.get('proxyuser')
self.proxypass = kw.get('proxypass')
... |
bioinformatics-ua/django-userena | userena/managers.py | Python | bsd-3-clause | 12,823 | 0.001716 | from django.db import models
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import get_user_model
from django.contrib.auth.models import UserManager, Permission, AnonymousUser
from django.contrib.contenttypes.models import ContentType
from django.utils.enco... | (('view_profile', 'Can view profile'),
('change_profile', 'Can change profile'),
('delete_profile', 'Can delete profile')),
'user':
(('change_use | r', 'Can change user'),
('delete_user', 'Can delete user'))
}
class UserenaManager(UserManager):
""" Extra functionality for the Userena model. """
def create_user(self, username, email, password, active=False,
send_email=True, pending_activation=False, first_name="", last_name="... |
jespino/urwintranet | tests/controllers/test_wiki_controller.py | Python | apache-2.0 | 258 | 0.003876 | from concurrent.futures import Future
from unittest import mock
from gm | ncurses.ui import signals, views
from gmncurses import controllers, config
from gmncurses.executor import Executor
from gmncurses.core import StateMachine
from tests import | factories
|
MediaSapiens/wavesf | apps/externals/gigyauth/models.py | Python | bsd-3-clause | 1,844 | 0.01898 | import django.db.models as models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class Profile(models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,pro... | arField(max_length=150)
timestamp | = models.DateTimeField(null=True,blank=True)
isLoggedIn = models.BooleanField(default=False)
birthday = models.DateField(null=True,blank=True)
city = models.CharField(max_length=150, null=True,blank=True)
state = models.CharField(max_length=150, null=True,b... |
cordis/pycloudia | pycloudia/packages/interfaces.py | Python | mit | 848 | 0 | from abc import ABCMeta, abstractmethod, abstractproperty
from collections import Hashable
class IPackage(Hashable):
__metaclass__ = ABCMeta
@abstractproperty
def content(self):
"""
:rtype: C{str}
"""
@abstractproperty
def headers(self):
"""
:rtype: C{dict... | ncoder(object):
__metaclass__ = ABCMeta
@abstractmethod
def encode(self, package):
"""
:type package: C{IPackage}
:rtype: C{str}
:raise: L{pycloudia.packages.exceptions.InvalidEncodingError}
"""
class IDecoder(object):
__metaclass__ = ABCMeta
@abstractmeth... | """
|
credp/lisa | tests/test_wlgen_rtapp.py | Python | apache-2.0 | 10,670 | 0.000375 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2017, ARM Limited and contributors.
#
# 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
#
# ... | # Heavy phase:
{
"loop": 1,
"run": 90000,
"timer": {
"period": 100000,
"ref": "unique"
}
}]
self._do_test(profile, exp_phases)
class TestRTACustom(RTABase):
__test__ = True
... | m' and checks that the json
roughly matches the file we provided. If we have root, attempts to run
the workload.
"""
json_path = os.path.join(ASSET_DIR, 'mp3-short.json')
with open(json_path, 'r') as fh:
str_conf = fh.read()
rtapp = RTA.from_str(
... |
hughperkins/coriander | test/test_local.py | Python | apache-2.0 | 1,738 | 0.001151 | # Copyright Hugh Perkins 2016
"""
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 "... | d.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
import pyopencl as cl
from test import test_common
from test.test_common import offset_type
import pytest
import os
@pytest.mark.skipif(os.environ.get('TRAVIS', None) == 'true', reason='fails o... |
h3ct0rjs/ProgrammingIVassignments | Lab5Sudoku/src/util.py | Python | mpl-2.0 | 671 | 0.0462 | from abc import ABCMeta, abstractmethod
class Observer(object):
__metaclass__ = ABCMeta
@abstractmethod
def update(self, *args, **kwargs):
pass
class Observable(object):
def __init__(self):
self.observers = []
def add_observer(s | elf, observer):
if not observer in self.observers:
self.observers.append(observer)
def delete_observer(self, observer):
| if observer in self.observers:
self.observers.remove(observer)
def delete_observers(self):
if self.observers:
del self.observers[:]
def notify_observers(self, *args, **kwargs):
for observer in self.observers:
observer.update(*args, **kwargs)
|
scienceopen/gpstk-examples-python | example2.py | Python | lgpl-3.0 | 1,119 | 0 | #!/usr/bin/env python
"""
A GPSTk examp | le with some simple time classes and functions.
This is a semi-port of the older C++ example2.cpp. The original
only imported and rewrote the same file. B | ut that would be
completely trivial for python.
Usage:
python example2.py
"""
from __future__ import print_function
import gpstk
# Read in the rinex data
# rfn = 'data/rinex3obs_data.txt'
rfn = gpstk.getPathData() + "/test_input_rinex2_obs_RinexObsFile.06o"
header, data = gpstk.readRinex3Obs(rfn, strict=True)
# Le... |
mccxj/leetcode | projecteuler/p0017_test.py | Python | apache-2.0 | 930 | 0.006452 | import unittest
class Test0017(unittest.TestCase):
def test_problem(self):
one_to_nine = [3, 3, 5, 4, 4, 3, 5, 5, 4]
ten_to_nineteen = [3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
twenty_to_ninety = [6, 6, 5, 5, 5, 7, 6, 6]
words_len = 0
sum_1_to_9 = sum(one_to_nine)
sum_10_to_1... | 1) * sum_20_to_90
#1~99
words_len += sum_1_to_99
#100~999, 'hundred and' => 10
| words_len += len(one_to_nine) * sum_1_to_99 + 100 * (
sum_1_to_9 + 10 * len(one_to_nine)) - 3 * len(one_to_nine)
#1000
words_len += 11
self.assertEqual(words_len, 21124) |
Q42/partyled | partyled.py | Python | mit | 6,344 | 0.003625 | #!/usr/bin/python
# coding=utf-8
import threading, time, math, sys, os, random
from flask import Flask, render_template, jsoni | fy
from functools import partial
from pluginbase import PluginBase
here | = os.path.abspath(os.path.dirname(__file__))
get_path = partial(os.path.join, here)
PWMAvailable = False
try:
sys.path.append(get_path('./drivers/'))
from Adafruit_PWM_Servo_Driver import PWM
PWMAvailable = True
except ImportError, e:
print "Cannot initialize PWM, if you're on a Mac, try using the sim... |
bstpierre/yendor | yendor/dice.py | Python | mit | 278 | 0 | #!/usr/bin/python
import random
de | f roll(qty, sides):
return sum(random.randrange(1, | sides + 1) for _ in range(qty))
def chances(qty, out_of):
"""'1 chance in 5' is chances(1, 5)"""
# Chance succeeds if roll is lower than max.
return roll(1, out_of) <= qty
|
dfroger/geomalgo | geomalgo/polar/__init__.py | Python | gpl-3.0 | 68 | 0 | from .polarpoint import | PolarPoint
__all__ = [
'Pola | rPoint',
]
|
ubear/Pyspider | pyspider/webui/login.py | Python | apache-2.0 | 1,443 | 0.000693 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<roy@binux.me>
# http://binux.me
# Created on 2014-12-10 20:36:27
import base64
from flask import Response
from flask.ext import login
from .app import app
login_manager = login.LoginManager()
login... | t('Authorization')
if api_key:
api_key = api_key.replace('Basic ', '', 1)
try:
api_key = base64.b64decode(api_key)
except TypeError:
pass
return User(*api_key.split(":", 1))
ret | urn None
app.login_response = Response(
"need auth.", 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}
)
@app.before_request
def before_request():
if app.config.get('need_auth', False):
if not login.current_user.is_active():
return app.login_response
|
brotchie/keepnote | keepnote/listening.py | Python | gpl-2.0 | 2,204 | 0.009074 | """
KeepNote
Listener (Observer) pattern
"""
#
# KeepNote
# Copyright (c) 2008-2009 Matt Rasmussen
# Author: Matt Rasmussen <rasmus@alum.mit.edu>
#
# 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 Softw... | f notify(self, *args, **kargs):
"""Notify listeners"""
for listener in self._listeners:
if self._suppress[listener] == 0:
listener(*args, * | *kargs)
def suppress(self, listener=None):
"""Suppress notification"""
if listener is not None:
self._suppress[listener] += 1
else:
for l in self._suppress:
self._suppress[l] += 1
def resume(self, listener=None):
"""Resume notif... |
perrygeo/Fiona | tests/test_geopackage.py | Python | bsd-3-clause | 2,690 | 0.003346 |
import logging
import os
import os.path
import shutil
import sys
import tempfile
import unittest
import pytest
import fiona
from fiona.collection import supported_drivers
from fiona.errors import FionaValueError, DriverError, SchemaError, CRSError
from fiona.ogrext import calc_gdal_version_num, get_gdal_version_num
... | path,
'w',
driver='GPKG',
schema=schema,
crs=crs)
else:
with fiona.open(path, 'w',
driver='GPKG',
schema=schema,
... | coordinates': [0.0, 0.0]},
'properties': {'title': 'One'}}])
c.writerecords([{
'geometry': {'type': 'Point', 'coordinates': [2.0, 3.0]},
'properties': {'title': 'Two'}}])
with fiona.open(path) as c:
self.assertEquals... |
reykjavik-university/2014-T-514-VEFT | Week10/examples/sqlalchemy-elasticsearch-example/db.py | Python | apache-2.0 | 258 | 0 | from sqlalchemy import create_en | gine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:////tmp/db.sqlite', echo=True)
Base = declarative_base()
Session = sessionmaker(bi | nd=engine)
|
danielballan/pims | pims/tests/test_display.py | Python | bsd-3-clause | 2,153 | 0.000929 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import nose
import numpy as np
from pims import plot_to_frame, plots_to_frame
from nose.tools import assert_true, assert_equal
import unittest
try:
import matplotlib.pyplot as plt
except ImportEr... | (figsize=(8, 6))
ax = fig.gca()
ax.plot(x, line)
self.figures.append(fig)
self.axes.append(ax)
self.expected_shape = (10, 384, 512, | 4)
def tearDown(self):
for fig in self.figures:
plt.close(fig)
def test_ax_to_frame(self):
frame = plot_to_frame(self.axes[0])
assert_equal(frame.shape, self.expected_shape[1:])
def test_plot_to_frame(self):
frame = plot_to_frame(self.figures[0])
asser... |
lmazuel/azure-sdk-for-python | azure-mgmt-monitor/azure/mgmt/monitor/models/autoscale_setting_resource_paged.py | Python | mit | 1,000 | 0.001 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft 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 ... | aged):
"""
A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object
"""
| _attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AutoscaleSettingResource]'}
}
def __init__(self, *args, **kwargs):
super(AutoscaleSettingResourcePaged, self).__init__(*args, **kwargs)
|
ESS-LLP/frappe | frappe/email/doctype/auto_email_report/test_auto_email_report.py | Python | mit | 1,091 | 0.021998 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest, json
# test_records = frappe.get_test_records('Auto Email Report')
class TestAutoEmailReport(unittest.TestCase):
def test_auto_email(self):
fr... | .get_repo | rt_content()
self.assertTrue('"Language","Core"' in data)
auto_email_report.format = 'XLSX'
data = auto_email_report.get_report_content()
|
pyrrho314/recipesystem | trunk/gempy/adlibrary/manipulate_ad.py | Python | mpl-2.0 | 3,293 | 0.004555 | # This module contains functions used to manipulate the AstroData object
import numpy as np
from astrodata import Errors
from astrodata.adutils import logutils
def remove_single_length_dimension(adinput=None):
"""
If there is only one single length dimension in the pixel data, the
remove_single_length_dim... | ion of the single length dimension in the
# tuple of array dimensions output by ext.data.shape
for i, data_length in enumerate(ext.data.shape):
| if ext.data.shape[i] == 1:
position = i
# numpy arrays use 0-based indexing and the axes are ordered from
# slow to fast. So, if the position of the single length dimension
# is located in e.g., ext.data.shape[0], the dimension number of
... |
dockerera/func | test/unittest/test_groups_api.py | Python | gpl-2.0 | 16,593 | 0.013741 | from func.overlord.groups import Groups,get_hosts_spec
from certmaster.config import read_config, CONFIG_FILE
from certmaster.commonconfig import CMConfig
import os
import fnmatch
from func.overlord.group.conf_backend import ConfBackend
from func.overlord.group.sqlite_backend import SqliteBackend
TEST_DB_FILE = "/tm... | uff
"""
self.clean_dummy_minions()
self.clean_t_files(T | EST_DB_FILE)
self.clean_t_files(TEST_CONF_FILE)
def test_add_group(self):
"""
adds a single group item
"""
for g in self.groups:
assert g.add_group("group1",save=True)[0]== True
g = self.refresh_backend(g)
assert g.add_group("group1")[0] =... |
Forage/Gramps | gramps/plugins/sidebar/dropdownsidebar.py | Python | gpl-2.0 | 7,650 | 0.002484 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2005-2007 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2009 Benny Malengier
# Copyright (C) 2010 Nick Hall
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute... |
def __make_category(self, grid, use_text, cat_num, cat_name, cat_icon):
"""
Create a row in the sidebar for a category.
"""
# create the button
button = Gtk.ToggleButton()
button.set_relief(Gtk.ReliefStyle.NONE)
button.set_alignment(0, 0.5)
self.butto... | = Gtk.Button()
dropdown.set_relief(Gtk.ReliefStyle.NONE)
dropdown.set_alignment(0.5, 0.5)
arrow = Gtk.Arrow(Gtk.ArrowType.DOWN, Gtk.ShadowType.NONE)
dropdown.add(arrow)
dropdown.connect('clicked', self.__view_clicked, cat_num)
dropdown.set_tooltip... |
ESOedX/edx-platform | common/test/acceptance/pages/lms/bookmarks.py | Python | agpl-3.0 | 2,207 | 0.001359 | """
Courseware Boomarks
"""
from __future__ import absolute_import
from common.test.acceptance.pages.common.paging import PaginatedUIMixin
from common.test.acceptance.pages.lms.course_page import CoursePage
class BookmarksPage(CoursePage, PaginatedUIMixin):
"""
Courseware Bookmarks Page.
"""
url_pat... | .q(css=self.BOOKMARKED_BREADCRUMBS).text
return [breadcrumb.replace('\n', '').split('-') for breadcrumb in breadcrumbs]
def click_bookmarked_block(self, index):
"""
Click on bookmarked block at index `index`
Argument | s:
index (int): bookmark index in the list
"""
self.q(css=self.BOOKMARKED_ITEMS_SELECTOR).nth(index).click()
|
audreyr/useful | text_to_speech.py | Python | bsd-3-clause | 1,232 | 0.003268 | #!/usr/bin/env python2.7 |
# -*- coding: utf-8 -*-
"""Asks for coffee using different Python text-to-speech modules.
"""
import pyttsx
def ask_for_coffee_mac():
"""
Use macspeechX to synthesize speech asking for coffee.
Note: sometimes doesn't work. It's a bit unpredictable.
Seems to work in the Python interactive shell only.
... | u're on a Mac but in a virtualenv without Foundation on your path.
* https://pypi.python.org/pypi/macspeechX/
* http://old.nabble.com/Re:-py-access-to-speech-synth--p18845607.html
"""
from macspeechX import SpeakString
SpeakString("Can you please make me some coffee, dearest?")
SpeakS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.