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 |
|---|---|---|---|---|---|---|---|---|
GFibrizo/TPS_7529 | TP1/Estadistico de orden K/k_heapsort.py | Python | apache-2.0 | 927 | 0.037756 | import heapq
def obtener_estadistico_orden_k(conjunto, k):
heap = conjunto[:]
heapq.heapify(heap)
elemento = None
for i in xrange(k+1):
elemento = heapq.heappop(heap)
return elemento
################################################################################
################... | adistico_orden_k([2,1], 1) == 2
print obtener_estadistico_orden_k([3,1,4,2,7], 3) == 4
print obtener_estadistico_o | rden_k([1,2,3,4,5,6,7,8], 0) == 1
print obtener_estadistico_orden_k([1,2,3,4,5,6,7,8], 7) == 8
print obtener_estadistico_orden_k([1,2,3,4,5,6,7,8], 4) == 5
################################################################################
##########################################################################... |
idan/oauthlib | tests/oauth2/rfc6749/clients/test_legacy_application.py | Python | bsd-3-clause | 6,427 | 0.002645 | # -*- coding: utf-8 -*-
import os
import urllib.parse as urlparse
from unittest.mock import patch
from oauthlib import signals
from oauthlib.oauth2 import LegacyApplicationClient
from tests.unittest import TestCase
@patch('time.time', new=lambda: 1000)
class LegacyApplicationClientTest(TestCase):
client_id = "... | r4_params = dict(urlparse.parse_qsl(r4, keep_blank_values=True))
self.assertEqual(len(r4_params.keys()), 5)
self.assertEqual(r4_params['grant_type'], 'password')
self.assertEqual(r4_params['username'], self.username)
self.assertEqual(r4_params['password'], self.password)
self.a... | uest_body(username=self.username, password=self.password, include_client_id=True, client_secret=None)
r4b_params = dict(urlparse.parse_qsl(r4b, keep_blank_values=True))
self.assertEqual(len(r4b_params.keys()), 4)
self.assertEqual(r4b_params['grant_type'], 'password')
self.assertEqual(r4b... |
Tatsh/libipa | setup.py | Python | mit | 555 | 0 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from setuptools import setup
setup(
name='libipa',
version='0.0.6',
author='Andrew Udvare',
autho | r_email='[email protected]',
packages=['ipa'],
scripts=['bin/ipa-unzip-bin', 'bin/ipa-dump-info'],
url='https://gith | ub.com/Tatsh/libipa',
license='LICENSE.txt',
description='Library to read IPA files (iOS application archives).',
test_suite='ipa.test',
long_description='No description.',
install_requires=[
'biplist>=0.7',
'six>=1.7.3',
],
)
|
aalitaiga/improved_wgan_training | gan_64x64.py | Python | mit | 23,661 | 0.009763 | import os, sys
sys.path.append(os.getcwd())
import time
import functools
import numpy as np
import tensorflow as tf
import sklearn.datasets
import tflib as lib
import tflib.ops.linear
import tflib.ops.conv2d
import tflib.ops.batchnorm
import tflib.ops.deconv2d
import tflib.save_images
import tflib.small_imagenet
imp... | enerator.BN3', [0,2,3], output)
output = nonlinearity(output)
output = lib.ops.deconv2d.Deconv2D('Generator.4', 2*dim, dim, 5, output)
if bn:
output = Batchnorm('Generator.BN4', [0,2,3], output)
output = nonlinearity(output)
output = lib.ops.deconv2d.Deconv2D('Generator.5', dim, 3, 5, outp... | lib.ops.deconv2d.unset_weights_stdev()
lib.ops.linear.unset_weights_stdev()
return tf.reshape(output, [-1, OUTPUT_DIM])
def WGANPaper_CrippledDCGANGenerator(n_samples, noise=None, dim=DIM):
if noise is None:
noise = tf.random_normal([n_samples, 128])
output = lib.ops.linear.Linear('Generato... |
krthkj/learningPython | readjson.py | Python | mit | 157 | 0.012739 | import json
from p | print import pprint
json_data=open('jsonFormated')
#json_data=open('jsonFile')
data = json.load(json_data)
pprint(data)
json_dat | a.close()
|
DiptoDas8/Biponi | lib/python2.7/site-packages/braintree/unknown_payment_method.py | Python | mit | 206 | 0.009709 | import braintree
from braintree.resource import Resour | ce
class UnknownPaymentMethod(Resource):
def image_url(self):
return "https://assets.braintreegateway.com/payment_metho | d_logo/unknown.png"
|
apache/incubator-airflow | airflow/www/forms.py | Python | apache-2.0 | 7,018 | 0.002566 | #
# 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... | e, datetime_format='%Y-%m-%d %H:%M:%S%Z', **kwargs):
super().__init__(label, validators, **kwargs)
self.format = datetime_fo | rmat
self.data = None
def _value(self):
if self.raw_data:
return ' '.join(self.raw_data)
if self.data:
return self.data.strftime(self.format)
return ''
def process_formdata(self, valuelist):
if not valuelist:
return
date_str =... |
compmem/ptsa | ptsa/data/rawbinwrapper.py | Python | gpl-3.0 | 9,972 | 0.005716 | #emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
#ex: set sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See the COPYING file distributed along with the PTSA package for the
# copyright and license terms.
#
### ### ### ### ### ### ### #... | params file
param_file = dataroot + '.params'
if not os.path.isfile(param_file):
# see if it's params.txt
param_file = os.path.join(os.path.dirname(dataroot), 'params.txt')
if not os.path.isfile(param_file):
raise IOError(
'No param... | 'or \"params.txt\".')
# we have a file, so open and process it
for line in open(param_file,'r').readlines():
# get the columns by splitting
cols = line.strip().split()
# set the params
params[cols[0]] = eval(string.join(cols[1:]))
if (not... |
dergraaf/xpcc | tools/device_files/parameters.py | Python | bsd-3-clause | 3,905 | 0.037132 | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Roboterclub Aachen e.V.
# All Rights Reserved.
#
# The file is part of the xpcc library and is released under the 3-clause BSD
# license. See the file `LICENSE` for the full license governing this code.
class ParameterDB:
""" Parameter Data Base
Manages Parameters
"""
... | s):
"""
Parses and adds items form [parameters] section in `project.cfg`
"""
if items is None:
return
for item in items:
p = UserParameter.fromUserConfigItem(item, self.log)
if p is not None:
self._parameters.append(p)
def addDriverParameter(self, param):
"""
"""
self.log.error("Ple | ase implement ParameterDB.addDriverParameter")
def getParametersForDriver(self, driver):
parameters = []
for param in self._parameters:
if param.driver_type == driver.type and param.driver_name == driver.name:
parameters.append({'name': param.name, 'value': param.value, 'instance': param.driver_instance})
... |
pli3/enigma2-pli | RecordTimer.py | Python | gpl-2.0 | 32,081 | 0.032511 | import os
from enigma import eEPGCache, getBestPlayableServiceReference, \
eServiceReference, iRecordableService, quitMainloop, eActionMap
from Components.config import config
from Components.UsageConfig import defaultMoviePath
from Components.TimerSanityCheck import TimerSanityCheck
from Screens.MessageBox import M... | def log(self, code, msg):
self.log_entries.append((int(time()), code, msg))
print "[TIMER]", msg
def calculateFilename(self):
service_name = self.service_ref.getServiceName()
begin_date = strftime("%Y%m%d %H%M", localtime(self.begin))
print "begin_date: ", begin_date
print "service_name: ", service_name
... | "description: ", self.description
filename = begin_date + " - " + service_name
if self.name:
if config.recording.filename_composition.value == "short":
filename = strftime("%Y%m%d", localtime(self.begin)) + " - " + self.name
elif config.recording.filename_composition.value == "long":
filename += " - ... |
jiafengwu0301/App_BackEnd | api/views.py | Python | apache-2.0 | 1,474 | 0.003392 | from rest_framework import generics, permissions, views, response,status
from .models import Account
from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \
UpdateAccountSerializ | er, AccountRetrieveSerializer
# Create your views here.
class AccountCreateView(generics.CreateAPIView):
queryset = Account.objects.all()
serializer_class = AccountCreateSerializer
permission_classes = [permissions.AllowAny]
class AccountListView(generics.ListAPIView):
queryset = Account.objects.a... | permission_classes = [permissions.IsAuthenticated]
class AccountRetrieveView(generics.RetrieveAPIView):
queryset = Account.objects.all()
serializer_class = AccountRetrieveSerializer
class UpdateAccountView(generics.UpdateAPIView):
queryset = Account.objects.all()
serializer_class = UpdateAccountSer... |
shirtsgroup/InterMol | intermol/molecule.py | Python | mit | 823 | 0 | class Molecule(object):
"""An abstract molecule object. """
def __init__(self, name=None):
"""Initialize the molecule
Args:
name (str): name of the molecule
"""
if not name:
name = "MOL"
self.name = name
self._atoms = list()
def add_... | atom (Atom): the atom to add into the molecule
"""
self._atoms.append(atom)
@property
def atoms(self):
"""Return an orderedset of atoms. """
return self. | _atoms
def __repr__(self):
return "Molecule '{}' with {} atoms".format(self.name, len(self.atoms))
def __str__(self):
return "Molecule{} '{}' with {} atoms".format(
id(self), self.name, len(self.atoms))
|
ratoaq2/Flexget | flexget/plugins/exit/__init__.py | Python | mit | 37 | 0 | """Plugins for "exit" task phas | e."""
| |
ktbyers/pynet-ons-jan17 | napalm_example/test_ios_cfg.py | Python | apache-2.0 | 1,143 | 0.000875 | #!/usr/bin/env python
from getpass import getpass
from pprint import pprint as pp
from napalm_base import get_network_driver
host = '184.105.247.70'
username = 'pyclass'
password = getpass()
optional_args = {}
driver = get_network_driver('ios')
device = driver(host, username, password, optional_args=optional_args)
p... | >Load config change (replace) - commit"
device.load_replace_candidate(filename='pynet_rtr1. | txt')
print device.compare_config()
device.commit_config()
print
raw_input("Hit any key to continue: ")
#device.rollback()
|
lsst-ts/ts_wep | python/lsst/ts/wep/task/RefCatalogInterface.py | Python | gpl-3.0 | 5,449 | 0.000184 | # This file is part of ts_wep.
#
# Developed for the LSST Telescope and Site Systems.
# This product includes software developed by the LSST Project
# (https://www.lsst.org).
# See the COPYRIGHT file at the top-level directory of this distribution
# for details of code ownership.
#
# This program is free software: you ... | he pieces of the
reference catalog that overlap the pointing.
"""
# HTM depth specifies the resolution of HTM grid that covers the sky.
# DM G | en3 ingests refernce catalogs with an HTM depth of 7.
htmIdx = HtmIndexer(depth=7)
centerPt = lsst.geom.SpherePoint(
self.boresightRa, self.boresightDec, lsst.geom.degrees
)
htmIds = htmIdx.getShardIds(
centerPt, lsst.geom.Angle(radius, lsst.geom.degrees)
... |
cassinius/right-to-forget-data | src/plots/plotting.py | Python | apache-2.0 | 13,050 | 0.020307 | import os, csv
import numpy as np
import matplotlib.pyplot as plt
from src.plots.plots_blur import gradient_fill
MODE = 'anonymization'
# MODE = 'perturbation'
# MODE = 'outliers'
# OUTLIER_TARGET = ''
OUTLIER_TARGET = 'outliers/'
# OUTLIER_TARGET = 'random_comparison/'
# OUTLIER_TARGET = 'original/'
# OUTLIER_TARG... | ax=ax_bottom_std,
# marker=markers[idx],
color='green',
label='standard deviation')
# ax_bottom.plot(std_devs)
ax_bottom_std.axis([0, max(x), 19000, 24000])
ax_bottom_std.locator_params(nbins=18, axis='x')
ax_bottom_std.set_xticklabels(x_labels)
ax_bo... | d.set_ylabel('Std.Dev.', color="g")
ax_bottom_size = ax_bottom_std.twinx()
gradient_fill(np.array(x),
np.array(list(map(float, sizes))),
y_min=float(min_size),
y_max=float(max_size),
|
czervenka/gap | gap/templates/tests/test_webapp.py | Python | apache-2.0 | 300 | 0 | from gap.utils.tests | import WebAppTestBase
class TestApp(WebAppTestBase):
def test_welcome(self):
resp = self.get('/')
self.assertEquals(resp.status_code, 200)
self.assertEquals(resp.content_type, 'text/html')
self.assertTrue('<b>Example project</b>' in re | sp,)
|
2ndQuadrant/ansible | lib/ansible/module_utils/vmware_rest_client.py | Python | gpl-3.0 | 13,483 | 0.001483 | # -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
... | exception=REQUESTS_IMP_ERR)
if not HAS_PYVMOMI:
self.module.fail_json(msg=missing_required_lib('PyVmomi'),
exception=PYVMOMI_IMP_ERR)
if not HAS_VSPHERE:
self.module.fail_json(
msg=missing_required_lib('vSphere Automa... | exception=VSPHERE_IMP_ERR)
@staticmethod
def vmware_client_argument_spec():
return dict(
hostname=dict(type='str',
fallback=(env_fallback, ['VMWARE_HOST'])),
username=dict(type='str',
fallback=(env_fallback, ['VMWARE_USER'... |
ifwe/wxpy | src/tests/wxPythonTests/testTopLevelWindow.py | Python | mit | 4,148 | 0.008679 | """Unit tests for wx.TopLevelWindow.
Methods yet to test for wx.TopLevelWindow:
__init__, CenterOnScreen, CentreOnScreen, EnableCloseButton, GetDefaultItem, GetIcon,
GetTmpDefaultItem, Iconize, IsActive, IsAlwaysMaximized, IsIconized,
MacGetMetalAppearance, MacSetMetalAppearance, RequestUserAttention, Restore, SetDefa... | testControl.ShowFullScreen(True))
self.assert_(not self.testControl.ShowFullScreen(True))
self.assert_(self.testControl.ShowFullScreen(False))
self.assert_(not self.testControl.ShowFullScreen(False))
'''
def testMaximize(s | elf):
"""Maximize, IsMaximized"""
self.testControl.Maximize()
self.assert_(self.testControl.IsMaximized())
self.testControl.Maximize(False)
self.assert_(not self.testControl.IsMaximized())
self.testControl.Maximize(True)
self.assert_(self.testControl.IsMaximized()... |
UK992/servo | tests/wpt/web-platform-tests/service-workers/service-worker/resources/navigation-redirect-body.py | Python | mpl-2.0 | 246 | 0.004065 | import os
filename = os.path.basename(__file__)
|
def main(request, response):
if request.method == 'POST':
return 302, [('Location', './%s?red | irect' % filename)], ''
return [('Content-Type', 'text/plain')], request.request_path
|
kaaustubh/pjsip | tests/pjsua/scripts-pesq/200_codec_speex_8000.py | Python | gpl-2.0 | 537 | 0.01676 | # $Id: 200_codec_speex_8000.py 20 | 63 2008-06-26 18:52:16Z nanang $
#
from inc_cfg import *
ADD_PARAM = ""
if (HAS_SND_DEV == 0):
ADD_PARAM += "--null-audio"
# Call with Speex/8000 codec
test_param = TestParam(
"PESQ codec Speex NB",
[
InstanceParam("UA1", ADD_PARAM + " --max-calls=1 --add-codec speex/8000 --clock-rate 8000 --play-file wavs/i... | io --max-calls=1 --add-codec speex/8000 --clock-rate 8000 --rec-file wavs/tmp.8.wav --auto-answer 200")
]
)
pesq_threshold = 3.0
|
tkzeng/molecular-design-toolkit | moldesign/exceptions.py | Python | apache-2.0 | 1,118 | 0.002683 | # Copyright 2016 Autodesk Inc.
#
# Licensed under the Apache Li | cense, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law | or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class ConvergenceFailure(Exception):
... |
ThinkboxSoftware/Deadline | Custom/events/Zabbix/API/pyzabbix/__init__.py | Python | apache-2.0 | 5,406 | 0.00148 | import httpretty
import logging
import requests
import json
class _NullHandler(logging.Handler):
def emit(self, record):
pass
logger = logging.getLogger(__name__)
logger.addHandler(_NullHandler())
class ZabbixAPIException(Exception):
""" generic zabbix api exception
code list:
... | ts >= 2.4 you can set it as tuple: "(connect, read)" which is used to set individual connect and read timeouts.)
"""
| if session:
self.session = session
else:
self.session = requests.Session()
# Default headers for all requests
self.session.headers.update({
'Content-Type': 'application/json-rpc',
'User-Agent': 'python/pyzabbix'
})
... |
cr33dog/pyxfce | xfconf/xfconf.py | Python | bsd-3-clause | 46 | 0.021739 | #!/usr/bin/env | python
from _xf | conf import *
|
manashmndl/dfvfs | tests/vfs/compressed_stream_file_system.py | Python | apache-2.0 | 2,758 | 0.002538 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the compressed stream file system implementation."""
import os
import unittest
from dfvfs.lib import definitions
from dfvfs.path import compressed_stream_path_spec
from dfvfs.path import os_path_spec
from dfvfs.resolver import context
from dfvfs.vfs import compre... | ath spe | cification functionality."""
file_system = compressed_stream_file_system.CompressedStreamFileSystem(
self._resolver_context)
self.assertNotEqual(file_system, None)
file_system.Open(path_spec=self._compressed_stream_path_spec)
self.assertTrue(file_system.FileEntryExistsByPathSpec(
self.... |
imron/scalyr-agent-2 | tests/unit/builtin_monitors/mysql_monitor_test.py | Python | apache-2.0 | 2,104 | 0.000951 | # Copyright 2019 Scalyr Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
#
# author: Imron Alston <[email protected]>
from __future__ import absolute_import
from __future__ import print_function
__author__ = "imron... | tCase):
def _import_mysql_monitor(self):
import scalyr_agent.builtin_monitors.mysql_monitor # NOQA
self.assertTrue(True)
def test_min_python_version(self):
if sys.version_info[:2] < (2, 7):
self.assertRaises(UnsupportedSystem, lambda: self._import_mysql_monitor())
... |
gregvonkuster/tools-iuc | tools/ena_upload/dump_yaml.py | Python | mit | 1,252 | 0 | import sys
import yaml
def fetch_table_data(table_path):
data_dict = {}
with open(table_path) as table_to_load:
# load headers
headers = table_to_load.readline().strip('\n').split('\t')
row_id = 0
for line in table_to_load. | readlines():
# print(line)
line_data = line.strip('\n').split('\t')
row_dict | = {}
for col_num in range(len(headers)):
col_name = headers[col_num]
row_dict[col_name] = line_data[col_num]
data_dict[row_id] = row_dict
row_id += 1
return data_dict
all_data_dict = {}
print('YAML -------------')
studies_table_path = sys.ar... |
yumingfei/virt-manager | virtManager/details.py | Python | gpl-2.0 | 134,336 | 0.001399 | #
# Copyright (C) 2006-2008, 2013 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, o... | T_NAME,
EDIT_ACPI,
EDIT_APIC,
EDIT_CLOCK,
EDIT_MACHTYPE,
EDIT_SECURITY,
EDIT_DESC,
EDIT_VCPUS,
EDIT_CPUSET,
EDIT_CPU,
EDIT_TOPOLOGY,
EDIT_MEM,
EDIT_AUTOSTART,
EDIT_BOOTORDER,
EDIT_BOOTMENU,
EDIT_KERNEL,
EDIT_INIT,
EDIT_DISK_R | O,
EDIT_DISK_SHARE,
EDIT_DISK_CACHE,
EDIT_DISK_IO,
EDIT_DISK_BUS,
EDIT_DISK_SERIAL,
EDIT_DISK_FORMAT,
EDIT_DISK_IOTUNE,
EDIT_SOUND_MODEL,
EDIT_SMARTCARD_MODE,
EDIT_NET_MODEL,
EDIT_NET_VPORT,
EDIT_NET_SOURCE,
EDIT_GFX_PASSWD,
EDIT_GFX_TYPE,
EDIT_GFX_KEYMAP,
EDIT_VIDEO_MODEL,
EDIT_WATCHDOG_MODEL,
EDIT_WATCHDOG_ACTI... |
SAOImageDS9/SAOImageDS9 | ttkthemes/setup.py | Python | gpl-3.0 | 1,699 | 0.001177 | """
Author: RedFantom
License: GNU GPLv3
Copyright (c) 2017-2018 RedFantom
"""
import os
from tkinter import TkVersion
from setuptools import setup
if TkVersion <= 8.5:
message = "This version of ttkthemes does not support Tk 8.5 and earlier. Please install a later version."
raise Runt | imeError(message)
def read(fname):
return open(os.path.join(os | .path.dirname(__file__), fname)).read()
setup(
name="ttkthemes",
packages=["ttkthemes"],
package_data={"ttkthemes": ["themes/*", "png/*", "gif/*", "advanced/*"]},
version="3.2.2",
description="A group of themes for the ttk extensions of Tkinter with a Tkinter.Tk wrapper",
author="The ttkthemes... |
slogan621/tscharts | tschartslib/medications/medications.py | Python | apache-2.0 | 8,744 | 0.01075 | #(C) Copyright Syd Logan 2017-2020
#(C) Copyright Thousand Smiles Foundation 2017-2020
#
#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 req... | data)
ret = x.send(timeout=30)
self.assertEqual(ret[0], 200)
self.assertTrue("id" in ret[1])
x = GetMedications(host, port, token); #test get a medication by its id
x.setId(int(ret[1]["id"]))
ret = x.send(timeout=30)
self.assertEqual(ret[0], 200)
ret = r... | AAAA")
x = DeleteMedications(host, port, token, id)
ret = x.send(timeout=30)
self.assertEqual(ret[0], 200)
x = GetMedications(host, port, token)
x.setId(id)
ret = x.send(timeout = 30)
self.assertEqual(ret[0], 404)
data = {}
data["... |
flav-io/flavio | flavio/statistics/test_likelihood.py | Python | mit | 13,195 | 0.00773 | import unittest
import flavio
from .likelihood import *
from flavio.classes import *
from flavio.statistics.probability import *
import numpy.testing as npt
import voluptuous as vol
import os
import tempfile
class TestMeasurementLikelihood(unittest.TestCase):
def test_class(self):
o = Observable( 'test_ob... | = Likelihood(pa | r, ['m_b', 'm_c'], ['test_obs'])
# npt.assert_array_equal(pl.get_central, [4.2, 1.2])
# self.assertEqual(len(pl.get_random), 2)
# test likelihoods
chi2_central = -2 * pl.log_prior_fit_parameters({'m_b': 4.2, 'm_c': 1.2})
chi2_2s = -2 * pl.log_prior_fit_parameters({'m_b': 4.6, 'm_... |
jrbourbeau/cr-composition | comptools/__init__.py | Python | mit | 1,516 | 0.00066 |
__version__ = '0.0.1'
import os
from .base import (get_config_paths, check_output_dir, ComputingEnvironemtError,
get_training_features, partition)
from .cluster import localized
from . import simfunctions
from .simfunctions import level3_sim_file_batches, level3_sim_GCD_file
from . import dataf | unctions
from .datafunctions import level3_data_file_batches, level3_data_GCD_file
from .io import (load_data, load_sim, apply_quality_cuts,
dataframe_to_X_y, load_trained_model)
from .composition_encoding import (get_comp_list, comp_to_label, label_to_comp,
decode_co... | iciencies
from .plotting import get_color_dict, plot_steps, get_colormap, get_color
from .pipelines import get_pipeline
from .model_selection import (get_CV_frac_correct, cross_validate_comp,
get_param_grid, gridsearch_optimize)
from .spectrumfunctions import (get_flux, model_flux, counts_... |
butterscotchstallion/limnoria-plugins | IMDB/config.py | Python | mit | 1,389 | 0.00576 | ###
# Copyright (c) 2015, butterscotchstallion
# All rights reserved.
#
#
###
import supybot.conf as conf
import supybot.registry as registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('IMDB')
except:
# Placeholder that allows to run the plugin on a bot
# wi... | put of a search query.""")))
# alternative template:
# $title ($year - $director) :: [i:$imdbRating r:$tomatoMeter m:$metascore] $plot :: http://imdb.com/title/$imdbID
conf.registerGlobalValue(IMDB, 'noResultsMessage',
registry.String("No results for that qu | ery.", _("""This message is sent when there are no results""")))
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
|
shackra/thomas-aquinas | notestno/test_openwindow.py | Python | bsd-3-clause | 3,333 | 0.003302 | # coding: utf-8
# This file is part of Thomas Aquinas.
#
# Thomas Aquinas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Thomas Aq... | ene):
def __init__(self, scenemanager, initialmapfile):
AbstractScene.__init__(self, scenemanager, initialmapfile)
self.clock = sfml.Clock()
self.timelapsed = 0
def on_draw(self, window):
wi | ndow.draw(self)
self.timelapsed += self.clock.restart().milliseconds
if self.timelapsed >= 10000.0:
self.scenemanager.exitgame()
def on_event(self, event):
pass
def reset(self):
self.timelapsed = 0
def __str__(self):
return "<Scene: Vacía>"
class Scene... |
LLNL/spack | var/spack/repos/builtin/packages/snap/package.py | Python | lgpl-2.1 | 1,642 | 0.000609 | # 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 Snap(MakefilePackage):
"""SNAP serves as a proxy application to model
the performance ... | i', default=True, description='Build with MPI support')
depends_on('mpi', when='+mpi')
build_directory = 'src'
def edit(self, spec, prefix):
with working_dir(self.build_directory):
makefile = FileFilter('Makefile')
if '~opt' in spec:
makefile.filter('OPT = ... | ('MPI = yes', 'MPI = no')
if '~openmp' in spec:
makefile.filter('OPENMP = yes', 'OPENMP = no')
makefile.filter('FFLAGS =.*', 'FFLAGS =')
def install(self, spec, prefix):
mkdirp(prefix.bin)
install('src/gsnap', prefix.bin)
install_tree('qasnap', prefix... |
MikkCZ/kitsune | kitsune/wiki/events.py | Python | bsd-3-clause | 13,208 | 0.000151 | import difflib
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse as django_reverse
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy
from bleach import clean
from tidings.events import InstanceEvent, Event... | Event):
"""Event fired when any revision in a certain locale is ready for review"""
# Our event_type suffices to limit our scope, so we don't bother
# setting content_type.
event_type = 'reviewable wiki in locale'
def _mails(self, users_and_watches):
revision = sel... | u'{title} is ready for review ({creator})')
url = reverse('wiki.review_revision',
locale=document.locale,
args=[document.slug, revision.id])
context = context_dict(revision)
context['revision_url'] = add_utm(url, 'wiki-ready-review')
context['... |
johntauber/MITx6.00.2x | Unit3/Lecture8Exercise1.py | Python | mit | 532 | 0.005639 |
def clt():
""" Flips a coin to generate a sample.
Modifies meanOfMeans and stdOfMeans defined before the function
| to get the means and stddevs based on the sample means.
Does not return anything """
for sampleSize in sampleSizes:
sampleMeans = []
for t in range(20):
sample = flipCoin(sampleSize)
sampleMeans.append | (getMeanAndStd(sample)[0])
meanOfMeans.append(getMeanAndStd(sampleMeans)[0])
stdOfMeans.append(getMeanAndStd(sampleMeans)[1]) |
ONSdigital/eq-survey-runner | app/views/flush.py | Python | mit | 2,659 | 0.002256 | from flask import Blueprint, Response, request, session, current_app
from sdc.crypto.encrypter import encrypt
from sdc.crypto.decrypter import decrypt
from app.authentication.user import User
from app.globals import (get_answer_store, get_metadata, get_questionnaire_store,
get_completed_block... | us=200)
return Response(status=404)
return Response(status=403)
def _submit_data(user):
answer_store = get_answer_store(user)
if answer_store:
metadata = get_metadata(user)
collection_metadata = get_c | ollection_metadata(user)
schema = load_schema_from_metadata(metadata)
completed_blocks = get_completed_blocks(user)
routing_path = PathFinder(schema, answer_store, metadata, completed_blocks).get_full_routing_path()
message = convert_answers(metadata, collection_metadata, schema, answer... |
jmesteve/saas3 | openerp/addons_extra/l10n_es_account_invoice_sequence/__openerp__.py | Python | agpl-3.0 | 2,298 | 0.00743 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2011 NaN Projectes de Programari Lliure, S.L. All Rights Reserved.
# http://www.NaN-tic.com
# Copyright (c) 2013 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com)
# ... | "description": """
Este módulo separa los números de las facturas de los de los asientos. Para
ello, convierte el campo number de 'related' a campo de texto normal, y le
asigna un valor según una nueva secuencia definida en el diario
correspondiente.
Su uso es obligatorio para España, ya que legalmente las factur... | numeración única y continua, lo que no es compatible con el sistema que
utiliza OpenERP por defecto.
**AVISO**: Hay que configurar las secuencias correspondientes para todos los
diarios de ventas, compras, abono de ventas y abono de compras utilizados
después de instalar este módulo.
""",
"depends" : [
... |
jespino/urwintranet | urwintranet/ui/__init__.py | Python | apache-2.0 | 62 | 0.016129 | # -*- coding: u | tf-8 -*-
"""
urwintranet.ui
~~~~ | ~~~~~~~~
"""
|
blairg23/Apocalypse-Defense | src/apocalypsedefense/python-prototype/driver.py | Python | mit | 2,354 | 0.016143 | '''
Author: Blair Gemmer
Purpose: Runs the main game loop, creates characters, upgrades characters
'''
from GameEngine import *
#Game variables:
GameRunning = True
height = 500
width = 500
#Create survivors:
w = Gun()
w.range = width
s1 = Survivor(w)
x = 50
y = 100
p = Point(x,y)
s1.position = p
s1.name = 'Fred'
s2... | for positions in steps:
# print 'position: ' + str(positions)
plot(positions[0],positions[1], 'ro-')
for steps in survivorPlot:
for positions in step | s:
# print 'position: ' + str(positions)
plot(positions[0],positions[1], 'bo-')
title('With RandomWalk() and DirectedWalk() without Zombie SightRange')
legend()
show()
print 'we made it'
|
dbracewell/pyHermes | tweet_analyze.py | Python | apache-2.0 | 1,469 | 0.003404 | import csv
import regex as re
import gensim
import pandas as pd
hashtag_pattern = re.compile('#[^\s\p{P}]+')
dictionary = gensim.corpora.Di | ctionary()
texts = []
with open('/home/dbb/PycharmProjects/twitter_crawler/music.csv') as rdr:
csv = csv.reader(rdr)
for row in csv:
if len(row) > 0:
text = row[0]
ta | gs = [t.lower() for t in hashtag_pattern.findall(text)]
if len(tags) > 0:
texts.append(dictionary.doc2bow(tags, allow_update=True))
lda_model = gensim.models.LdaModel(corpus=texts, id2word=dictionary, alpha='auto', num_topics=50, iterations=500)
for i in range(lda_model.num_topics):
pr... |
dimagi/commcare-hq | corehq/apps/app_manager/migrations/0017_migrate_case_search_relevant.py | Python | bsd-3-clause | 745 | 0 | from django.core.management import call_command
from django.db import migrations
from corehq.toggles import SYNC_SEARCH_CASE_CLAIM
from corehq.util.django_migrations import skip_on_fresh_install
@skip_on_fresh_install
def _migrat | e_case_search_relevant(apps, schema_editor):
for domain in sorted(SYNC_SEARCH_CASE_CLAIM.get_enabled_domains()):
call_command('migrate_case_search_relevant', domain=domain)
class Migration(migrations.Migration) | :
dependencies = [
('app_manager', '0016_alter_exchangeapplication'),
]
operations = [
migrations.RunPython(_migrate_case_search_relevant,
reverse_code=migrations.RunPython.noop,
elidable=True),
]
|
tmaiwald/OSIM | OSIM/Modeling/Testbenches/VBIC_Kennlinien_TBs/VBIC_NPN_TB.py | Python | bsd-2-clause | 2,279 | 0.017113 | import matplotlib.pyplot as plt
from OSIM.Modeling.Components.NPN_Vertical_Bipolar_Intercompany_Model.VBIC_Currents.IRCI import *
from OSIM.Modeling.Components.Resistor import Resistor
from OSIM.Modeling.Components.VoltageSource import VoltageSource
from OSIM.Modeling.CircuitSystemEquations import CircuitSystemEquation... | %G"%(e))
print("C: %G"%(c))
npn.IT.debugPrint()
#x = raw_input()
sol = 0
#print(TBSys.curNewtonIteration)
#a = raw_input()
| I[cidx][eidx] = sol
# ax.plot_surface(B, C, I, rstride=8, cstride=8, alpha=0.3)
ax.plot_wireframe(B, C, I, rstride=5, cstride=5, alpha=0.3)
#cset = ax.contour(B, C, I, zdir='x', offset=BMAX, cmap=cm.coolwarm)
ax.set_xlabel('E')
ax.set_xlim(EMIN, EMAX)
ax.set_ylabel('C')
ax.set_ylim(CMIN, CMAX)
ax.set_zlabel('I')
ax... |
Nefry/taurus | tests/mocks.py | Python | apache-2.0 | 5,148 | 0.000389 | """ test """
import logging
import os
import tempfile
import sys
import random
from bzt.engine import Engine, Configuration, FileLister
from bzt.utils import load_class
from bzt.engine import Provisioning, ScenarioExecutor, Reporter, AggregatorListener
from bzt.modules.aggregator import ResultsReader
from tests import... | ults[-1]["ts"] >= data["ts"]:
raise Assertio | nError("TS sequence wrong: %s>=%s" % (self.results[-1]["ts"], data["ts"]))
logging.info("Data: %s", data)
self.results.append(data)
def download_progress_mock(blocknum, blocksize, totalsize):
pass
class ResultChecker(AggregatorListener):
def __init__(self, callback):
super(ResultChec... |
mpkato/mobileclick | setup.py | Python | mit | 1,565 | 0.017891 | # -*- coding:utf-8 -*-
from setuptools import setup
setup(
name = "mobileclick",
description = "mobileclick provides baseline methods and utility scripts for the NTCIR-12 MobileClick-2 task",
author = "Makoto P. Kato",
author_email = "[email protected]",
license = "MIT Lice... | d=mobileclick.scripts.mobileclick_lang_model_summarization_method:main',
'mobileclick_lang_model_two_layer_summarization_method=mobileclick.scripts.mobileclick_lang_model_two_layer_summa | rization_method:main',
],
},
tests_require=['nose']
)
|
hk4n/milk | tests/resources/test_plugins/testplugin3.py | Python | mit | 177 | 0 | from milk | .plugin import Plugin
class testplugin3(Plugin):
def __init__(self, config):
for key, value in config.items():
print("%s: %s" | % (key, value))
|
rahulunair/nova | nova/scheduler/weights/disk.py | Python | apache-2.0 | 1,534 | 0 | # Copyright (c) 2015 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 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 imp... |
Ghini/ghini.desktop | bauble/plugins/garden/test_import_pocket_log.py | Python | gpl-2.0 | 22,436 | 0.001649 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Mario Frasca <[email protected]>.
# Copyright 2018 Tanager Botanical Garden <[email protected]>
#
# This file is part of ghini.desktop.
#
# ghini.desktop is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | tely_identified_existing_species(self):
# prepare T0
fam = Family(epithet='Myrtaceae')
gen = Genus(epithet='Eugenia', family=fam)
s | pe = Species(epithet='stipitata', genus=gen)
self.session.add_all([fam, gen, spe])
self.session.commit()
# test T0
a = self.session.query(Accession).filter_by(code='2018.0001').first()
self.assertEquals(a, None)
eugenia = self.session.query(Genus).filter_by(epithet='Eugen... |
kobotoolbox/formpack | tests/fixtures/grouped_translated/__init__.py | Python | gpl-3.0 | 297 | 0 | # | coding: utf-8
'''
grouped_translated
'''
from ..load_fixture_json import load_fixture_json
DATA = {
'title': 'Animal identification survey with translations and groups',
'id_string': 'grouped_translated',
'versions': [
load_fi | xture_json('grouped_translated/v1'),
],
}
|
mperignon/anuga-sedtransport | file_conversion/generic_dem2pts.py | Python | gpl-2.0 | 6,790 | 0.008542 | # external modules
import numpy as num
# ANUGA modules
import anuga.utilities.log as log
from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a, \
netcdf_float
from generic_asc2dem import generic_asc2dem
def generic_dem2pts(name_in, name_out=None... | len(dem)
if verbose:
log.critical('There are %d values in the raster' % totalnopoints)
log.critical('There are %d values in the clipped raster'
% clippednopoints)
log.critical('There are %d NODATA_values in the clipped raster' % nn)
ou | tfile.createDimension('number_of_points', nopoints)
outfile.createDimension('number_of_dimensions', 2) #This is 2d data
# Variable definitions
outfile.createVariable('points', netcdf_float, ('number_of_points',
'number_of_dimensions'))
outfile.createV... |
rholy/dnf | dnf/package.py | Python | gpl-2.0 | 6,052 | 0.002148 | # package.py
# Module defining the dnf.Package class.
#
# Copyright (C) 2012-2013 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version... | um compatibility method
def evr_lt(self, pkg):
return self.evr_cmp(pkg) < 0
# yum compatibility method
def getDiscNum(self):
return self.medianr
# yum compatibility method
def localPkg(self):
""" Package's location in the filesystem.
For packages in remote repo... | return self.location
if self.baseurl:
path = os.path.join(self.baseurl, self.location)
if path.startswith("file://"):
path = path[7:]
return path
loc = self.location
if not self.repo.local:
loc = os.path.basename(loc)
re... |
Pugsworth/ScratchPad | ScratchPad.py | Python | mit | 3,907 | 0.041976 | import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .subli... | ;
global g_last_view;
g_last_view = self.view;
class ScratchpadEvent(sublime_plugin.EventListener):
def on_load(self, view):
global g_current_file;
if g_current_file != None and os.path.normcase(g_current_file.file_name) == os.path.normcase(view.file_name()):
window = view.window();
window.run_command(... | window.active_view() != g_last_view:
window.focus_view(g_last_view);
g_last_view = None;
g_current_file = None;
|
gallifrey17/eden | modules/tests/inv/send_item.py | Python | mit | 3,148 | 0.0054 | """ Sahana Eden Module Automated Tests - INV001 Send Items
@copyright: 2011-2012 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software w... | ded 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 AUTHORS OR COPYRIGHT
HOLDERS BE LIAB... |
dundeemt/SoCo | examples/commandline/discover.py | Python | mit | 175 | 0 | from __future__ import print_fun | ction
import soco
""" Prints the name of eac | h discovered player in the network. """
for zone in soco.discover():
print(zone.player_name)
|
kaarolch/ansible | lib/ansible/inventory/yaml.py | Python | gpl-3.0 | 6,401 | 0.002656 | # Copyright 2016 RedHat, 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
# (at your option) any later version.
#
# Ansible i... | ys to correspond to groups, iterate over them
# to get host, vars and subgroups (which we iterate over recursivelly | )
for group_name in data.keys():
self._parse_groups(group_name, data[group_name])
# Finally, add all top-level groups as children of 'all'.
# We exclude ungrouped here because it was already added as a child of
# 'all' at the time it was created.
for group in self.gr... |
cdoremus/udacity-python_web_development-cs253 | src/unit5/blog_datastore_factory.py | Python | apache-2.0 | 683 | 0.010249 | '''
Created on Apr 30, 2012
@author: h87966
'''
from unit5.blog_datastore_memory import BlogMemory | DataStore
from unit5.blog_datastore_appengine import BlogAppengineDataStore
class BlogDataStoreFactory():
'''
classdocs
'''
storage_implementations = {'memory':BlogMemoryDataStore(),
'appengine':BlogAppengineDataStore()}
def __init__(se | lf, storage_impl='appengine'):
'''
Constructor
'''
self.storage = self.storage_implementations[storage_impl]
def set_storage(self, blog_storage):
self.storage = blog_storage
def get_storage(self):
return self.storage
|
ppruitt/site | site/paulpruitt_net/settings.py | Python | mit | 2,273 | 0.00396 | " | ""
Django settings for paulpruitt_net project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, .... | os.path.dirname(os.path.realpath(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application d... |
tsukinowasha/ansible-lint-rules | rules/ShellAltService.py | Python | mit | 567 | 0.001764 | from ansiblelint import AnsibleLintRule
class ShellAltService(AnsibleLintRule):
| id = 'E507'
shortdesc = 'Use service module'
description = ''
tags = ['shell']
def matchtask(self, file, task):
if task['action']['__ansible_module__'] not in ['shell', 'command']:
return False
args = task['action']['__ansible_arguments__']
if 'service' in args:
... | return False
|
malongge/selenium-pom | tests/test_index_page.py | Python | apache-2.0 | 3,269 | 0.002478 | import time
import pytest
from pages.index_page import IndexPage
from .base import BaseTest
class TestIndexPage(BaseTest):
@pytest.fixture(autouse=True)
def _go_to_index_page(self, request, base_url, selenium, login):
_, pg = login
# self.home_pg = pg
index_pg = IndexPag... | 行的时候,鼠标不要放到轮播图上, 否则会影响测试结果
links = []
for _ in btns:
link = index_pg.get_focus_pic_img_link()
links.append(link)
time.sleep(4)
| for index, value in enumerate(links[:-1]):
assert links[index] != links[index + 1], '轮播第 {} 张链接地址为 {} 应该在 4s 后轮播, 但未检测到有轮播'.format(index, value)
# @pytest.mark.flaky(reruns=1)
# def test_index_focus_pic_auto_run(self, base_url, selenium, login):
# _, pg = login
# index_pg... |
ivanamihalek/tcga | tcga/01_somatic_mutations/old_tcga_tools/007_mutation_type_cleanup.py | Python | gpl-3.0 | 5,786 | 0.01158 | #!/usr/bin/python
#
# This source code is part of tcga, a TCGA processing pipeline, written by Ivana Mihalek.
# Copyright (C) 2014-2016 Ivana Mihalek.
#
# 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 Foun... | s_informative(aa_change)):
return [checks, fixed_row]
id = fields['id']
hugo_symbol = fields ['hugo_symbol']
start_ | position = fields['start_position']
end_position = fields['end_position']
tumor1 = fields['tumor_seq_allele1']
tumor2 = fields['tumor_seq_allele2']
norm1 = fields['match_norm_seq_allele1']
norm2 = fields['match_norm_seq_allele2']
reference = fields['reference_allele']
... |
cernops/nova | nova/virt/libvirt/imagebackend.py | Python | apache-2.0 | 45,765 | 0.000284 | # Copyright 2012 Grid Dynamics
# 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... | .source_type = "b | lock"
info.source_dev = self.path
else:
info.source_type = "file"
info.source_file = self.path
info.driver_format = self.driver_format
if driver_type:
info.driver_type = driver_type
else:
if self.driver_forma... |
joh12041/route-externalities | preprocessing/grid_creation.py | Python | mit | 3,570 | 0.003641 | import os
import json
import argparse
from math import ceil, floor
from geojson import Polygon, Feature, FeatureCollection, dump
from shapely.geometry import shape, Point
"""
Code adapted from answer to question here:
http://gis.stackexchange.com/questions/54119/creating-square-grid-polygon-shapefile-with-python
"""
... | ]['COUNTY'])
except:
pass
count += 1
boundary = shape(feature['geometry'])
bb = boundary.bounds
xmin = bb[0] # most western point
xmax = bb[2] # most eastern poin | t
ymin = bb[1] # most southern point
ymax = bb[3] # most northern point
gridHeight = 0.001
gridWidth = 0.001
xmin = floor(xmin * 10**SCALE) / 10**SCALE
ymax = ceil(ymax * 10**SCALE) / 10**SCALE
grid("{0}.geojson".format(os.path.join(args.output_folder, feature... |
SiLab-Bonn/monopix_daq | monopix_daq/scans/en_tune.py | Python | gpl-2.0 | 7,608 | 0.024842 | #!/usr/bin/env python
import os,sys,time
import numpy as np
import bitarray
import tables as tb
import logging
import yaml
import matplotlib.pyplot as plt
import monopix_daq.scan_base as scan_base
import monopix_daq.analysis.interpreter as interpreter
local_configuration={"exp_time": 1.0,
"cnt_t... | ttrs.firmware)
## DAC Configuration page
dat=yaml.load(f.root.meta_data.at | trs.dac_status)
dat.update(yaml.load(f.root.meta_data.attrs.power_status))
plotting.table_1value(dat,page_title="Chip configuration")
## Pixel Configuration page (before tuning)
dat=yaml.load(f.root.meta_data.attrs.pixel_conf_before)
... |
mick-d/nipype | nipype/interfaces/c3.py | Python | bsd-3-clause | 1,785 | 0.00112 | # -*- coding: utf-8 -*-
"""The ants module provides basic functions for interfacing with ants functions.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/dat... | tk %s", position=5)
fsl2ras = traits.Bool(argstr='-fsl2ras', position=4)
class C3dAffineToolOutputSpec(TraitedSpec):
itk_transform = File(exists=True)
class C3dAffineTool(SEMLikeCommandLine):
"""Converts fsl-style Affine registration into ANTS compatible itk format
Example
=======
>>> from... | ts.itk_transform = 'affine.txt'
>>> c3.inputs.fsl2ras = True
>>> c3.cmdline # doctest: +ALLOW_UNICODE
'c3d_affine_tool -src cmatrix.mat -fsl2ras -oitk affine.txt'
"""
input_spec = C3dAffineToolInputSpec
output_spec = C3dAffineToolOutputSpec
_cmd = 'c3d_affine_tool'
_outputs_filenames = ... |
lrks/python-escpos | escpos/printer.py | Python | gpl-3.0 | 5,425 | 0.005346 | #!/usr/bin/python
"""
@author: Manuel F Martinez <[email protected]>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GNU GPL v3
"""
import usb.core
import usb.util
import serial
import socket
from .escpos import *
from .constants import *
from .exceptions import *
class Usb(Escpos):
... | ze
@param timeout : Read/Write timeout
@param parity : Parity checking
@param stopbits : Number of stop b | its
@param xonxoff : Software flow control
@param dsrdtr : Hardware flow control (False to enable RTS/CTS)
"""
self.devfile = devfile
self.baudrate = baudrate
self.bytesize = bytesize
self.timeout = timeout
self.parity = parity
self.stopbits ... |
AwesomeTTS/awesometts-anki-addon | awesometts/service/naverclovapremium.py | Python | gpl-3.0 | 5,322 | 0.003946 | # -*- coding: utf-8 -*-
# AwesomeTTS text-to-speech add-on for Anki
# Copyright (C) 2010-Present Anki AwesomeTTS Development Team
#
# 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 versi... | voice_data))
return voice_list
def get_voice_list(self):
voice_list = [(voice.get_key(), voice.get_description()) for voice in self.get_voices()]
voice_list.sort(key=lambda x: x[1])
return voice_list
def get_voice_for_key(self, key) -> StandardVoice:
voice = [vo... | ons(self):
return [
dict(key='voice',
label="Voice",
values=self.get_voice_list(),
transform=lambda value: value),
dict(
key='speed',
label="Speed",
values=(-5, 5),
transfo... |
apruden/genwiki | genwiki/model.py | Python | lgpl-3.0 | 5,404 | 0.002036 | import codecs
import os
import re
import json
from . import WIKI_DIR
from collections import defaultdict
def _get_filename(slug):
return os.path.join(WIKI_DIR, '%s.md' % (slug,))
class Index(object):
def __init__(self):
self.texts, self.words = {}, set()
self.finvindex = defaultdict(set)
... | lse None
self.slug = str(Post.build_slug(self.title))
self.tags = filter(None, tags.split(',') if isinstance(tags, basestring) else tags if tags else [])
self. | created = str(created) if created else None
self.modified = str(modified) if modified else None
def __cmp__(self, other):
if not other:
return -1
return (int(self.created > other.created) or -1) if self.created != other.created else 0
def serialize(self):
buf = ['<... |
upgradeadvice/fofix-grisly-virtualenv | FoFiX/Menu.py | Python | gpl-2.0 | 21,146 | 0.02199 | #####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä ... | self.sub_menu_x = .44
if self.sub_menu_y == None:
self.sub_m | enu_y = .14
elif engine.data.theme == 1:
if self.sub_menu_x == None:
self.sub_menu_x = .38
if self.sub_menu_y == None:
self.sub_menu_y = .15
elif engine.data.theme == 2:
if self.sub_menu_x == None:
self.sub_menu_x = .25
if sel |
jlopezbi/rhinoUnfolder | rhino_unwrapper/weight_functions.py | Python | gpl-3.0 | 536 | 0.009328 | import rhinoscriptsy | ntax as rs
import random as rand
def edgeAngle(myMesh, edgeIndex):
#TODO: make myMesh function which findes angel between two faces of a given edge
faceIdxs = myMesh.getFacesForEdge(edgeI | ndex)
if (len(faceIdxs) == 2):
faceNorm0 = myMesh.face_normal(faceIdxs[0])
faceNorm1 = myMesh.face_normal(faceIdxs[1])
return rs.VectorAngle(faceNorm0, faceNorm1)
else:
return None
def uniform(mesh, edgeIndex):
return 1
def random(mesh, edgeIndex):
return rand.random()
|
gjbex/vsc-tools-lib | vsc/pbs/qstat.py | Python | lgpl-3.0 | 4,075 | 0.000491 | # | !/usr/bin/env python
'''Utilities to deal with PBS torque qstat'''
from vsc.utils import walltime2seconds
from vsc.pbs.job import PbsJob
class QstatParser(object):
'''Parser for full PBS torque qstat output'''
def __init__(self, config):
'''constructor'''
self._config = config
self._j... | stat_file):
'''parse a file that contains qstat -f output'''
qstat_output = ''.join(qstat_file.readlines())
return self.parse(qstat_output)
def parse_record(self, record):
'''parse an individual job record'''
job = None
resource_specs = {}
resources_used = {}... |
kingvuplus/boom | lib/python/Screens/Rc.py | Python | gpl-2.0 | 3,561 | 0.001966 | from Components.Pixmap import MovingPixmap, MultiPixmap
from Tools.Directories import resolveFilename, SCOPE_SKIN
from xml.etree.ElementTree import ElementTree
from Components.config import config, ConfigInteger
from Compon | ents.RcModel import rc_model
from boxbranding import getBoxType
config.misc.rcused = ConfigInteger(default=1)
class Rc:
def __init__(self):
self['rc'] = MultiPixmap()
self['arrowdown'] = MovingPixmap()
self['arrowdown2'] = MovingPixmap()
self['arrowu | p'] = MovingPixmap()
self['arrowup2'] = MovingPixmap()
config.misc.rcused = ConfigInteger(default=1)
self.isDefaultRc = rc_model.rcIsDefault()
self.rcheight = 500
self.rcheighthalf = 250
self.selectpics = []
self.selectpics.append((self.rcheighthalf, ['arro... |
dandxy89/rf_helicopter | pytests.py | Python | mit | 5,028 | 0.000199 | # Purpose: Test Script to Ensure that as the complexity of the Scripts Grows functionality can be checked
#
# Info: Uses py.test to test each of the track building functions are working
#
# Running the Test from the COMMAND LINE: py.test test.py
#
# Developed as part of the Software Agents Course at City Universi... | "Test_Track.npy"))
loaded_track = np.load(os.path.join(os.getcwd(),
"Tests",
"Test_Track.npy"))
assert l | oaded_track.shape == world.track.shape, \
"Loading Track into World Failed"
|
khushboo9293/postorius | src/postorius/tests/test_auth_decorators.py | Python | gpl-3.0 | 8,684 | 0.000345 | # -*- coding: utf-8 -*-
# Copyright (C) 2012-2015 by the Free Software Foundation, Inc.
#
# This file is part of Postorius.
#
# Postorius 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... | list.return_value = self.mock_list
# prepare request
request = self.request_factory.get('/lists/foolist.example.org/'
'settings/')
request.user = User.objects.create_user('les cl', '[email protected]',
| 'pwd')
return_value = dummy_function(request,
list_id='foolist.example.org')
self.assertEqual(return_value, True)
class ListModeratorRequiredTest(unittest.TestCase):
"""Tests the list_owner_required auth decorator... |
sionide21/HackerTracker | tests/event_tests.py | Python | mit | 4,529 | 0.000883 | import csv
import unittest
from datetime import datetime, timedelta
from hackertracker import event
from hackertracker.database import Model, Session
from sqlalchemy import create_engine
class TestEvents(unittest.TestCase):
def setUp(self):
engine = create_engine('sqlite:///:memory:', echo=True)
M... | e.track(attrs=dict(hello="world", when="now"))
e.track(attrs=dict(hello="goodbye", location="office"))
Session.commit()
csv_file = list(csv.reader(e.export_csv().splitlines() | ))
self.assertEqual(csv_file[0], ["When", "hello", "location", "size", "when"])
self.assertEqual(csv_file[1], [str(o.when), "", "office", "16", ""])
self.assertEqual(len(csv_file), 4)
def earlier(**kwargs):
return datetime.utcnow() - timedelta(**kwargs)
|
fredericklussier/ObservablePy | .vscode/.ropeproject/config.py | Python | mit | 4,037 | 0 | # The default ``config.py``
# flake8: noqa
def set_prefs(prefs):
"""This function is called before opening the project"""
# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_fil... | '.hg', '.svn', '_svn', '.git', '.tox']
# Specifies which file | s should be considered python files. It is
# useful when you have scripts inside your project. Only files
# ending with ``.py`` are considered to be python files by
# default.
# prefs['python_files'] = ['*.py']
# Custom source folders: By default rope searches the project
# for finding sourc... |
msincenselee/vnpy | vnpy/trader/gateway.py | Python | mit | 29,138 | 0.002194 | """
"""
import sys
from abc import ABC, abstractmethod
from typing import Any, Sequence, Dict, List, Optional, Callable
from copy import copy,deepcopy
from logging import INFO, DEBUG, ERROR
from datetime import datetime
from vnpy.event import Event, EventEngine
from .event import (
EVENT_TICK,
EVENT_BAR,
... | def on_trade(self, trade: TradeData) -> None:
"""
Trade event push.
| Trade event of a specific vt_symbol is also pushed.
"""
self.on_event(EVENT_TRADE, trade)
# self.on_event(EVENT_TRADE + trade.vt_symbol, trade)
def on_order(self, order: OrderData) -> None:
"""
Order event push.
Order event of a specific vt_orderid is also pushed.
... |
qedsoftware/commcare-hq | corehq/apps/locations/tests/test_location_fixtures.py | Python | bsd-3-clause | 14,654 | 0.002115 | import mock
import os
from xml.etree import ElementTree
from corehq.util.test_utils import flag_enabled
from datetime import datetime, timedelta
from django.test import TestCase
from casexml.apps.phone.models import SyncLog
from casexml.apps.phone.tests.utils import create_restore_user
from corehq.apps.domain.shortcu... | self.user.set_location(self.locations['Boston'].couch_location)
location_type = self.locations['Boston'].location_type
location_type.expand_from_root = True
location_type.save()
self._assert_fixture_has_locations(
'expand_from_root',
['Massachusetts', 'Suf... | an', 'Queens', 'Brooklyn']
)
def test_expand_from_root_to_county(self, uses_locations):
self.user.set_location(self.locations['Massachusetts'].couch_location)
location_type = self.locations['Massachusetts'].location_type
location_type.expand_from_root = True
location_type.ex... |
coderanger/brix | templates/legacy_region.py | Python | apache-2.0 | 3,676 | 0.000272 | #
# Author:: Noah Kantrowitz <[email protected]>
#
# Copyright 2014, Balanced, 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... | 'AvailabilityZone': 'us-west-1b',
'CidrBlock': '10.3.216.0/20',
}
def srta_RouteAssocB(self):
"""Association between the AZ B subnet and the route table."""
return {
'RouteTableId': self.rtb_RouteTableB(),
'SubnetId': Ref(self.subnet_SubnetB()),
... | anced API production stack."""
return {
'TemplateName': 'balanced_api',
'Parameters': {
'Env': 'production',
'ChefEnv': 'production',
'Capacity': 4,
},
}
def app_BalancedApiTest(self):
"""Balanced API test s... |
xodus7/tensorflow | tensorflow/python/estimator/training_test.py | Python | apache-2.0 | 85,718 | 0.003955 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | r import estimator as estimator_lib
from tensorflow.python.estimator import exporter as exporter_lib
from tensorflow.python.estimator import model_fn as model_fn_lib
from tensorflow.python.estimator import run_ | config as run_config_lib
from tensorflow.python.estimator import training
from tensorflow.python.estimator.canned import dnn
from tensorflow.python.estimator.canned import prediction_keys
from tensorflow.python.estimator.export import export as export_lib
from tensorflow.python.feature_column import feature_column
from... |
SasView/sasmodels | example/model.py | Python | bsd-3-clause | 1,240 | 0.012097 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from bumps.names import *
from sasmodels.core import load_model
from sasmodels.bumps_model import Model, Experiment
from sasmodels.data impor | t load_data, set_beam_stop, set_top
""" IMPORT THE DATA USED """
radial_data = load_data('DEC07267.DAT')
set_b | eam_stop(radial_data, 0.00669, outer=0.025)
set_top(radial_data, -.0185)
kernel = load_model("ellipsoid")
model = Model(kernel,
scale=0.08,
radius_polar=15, radius_equatorial=800,
sld=.291, sld_solvent=7.105,
background=0,
theta=90, phi=0,
theta_pd=15, theta_pd_n=40, theta_pd_nsigma=3,
rad... |
froyobin/ironic | ironic/drivers/modules/ilo/deploy.py | Python | apache-2.0 | 25,377 | 0.000355 | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 applicabl... | "image %(image)s for generating boot ISO for % | (node)s"),
{'image': image_uuid, 'node': task.node.uuid})
return
# NOTE(rameshg87): Functionality to share the boot ISOs created for
# similar instances (instances with same deployed image) is
# not implemented as of now. Creation/Deletion of such a shared boot ISO
# will requ... |
CatalansMB/War1714 | src/ID_strings.py | Python | gpl-2.0 | 30,810 | 0.000032 | str_no_string = 0
str_empty_string = 1
str_yes = 2
str_no = 3 |
str_blank_string = 4
str_error_string = 5
str_s0 = 6
str_blank_s1 = 7
str_reg1 = 8
str_s50_comma_s51 = 9
str_s50_and_s51 = 10
str_s52_comma_s51 = 11
str_s52_and_s51 = 12
str_msg_battle_won = 13
str_charge = 14
str_color = 15
str_hold_fire = 16
str_blunt_hold_fire = 17
str_finished = 18
str_delivered_damage = 19
str_ar... | tr_battle_lost = 24
str_kingdom_1_adjective = 25
str_kingdom_2_adjective = 26
str_kingdom_3_adjective = 27
str_kingdom_4_adjective = 28
str_kingdom_5_adjective = 29
str_kingdom_6_adjective = 30
str_credits_1 = 31
str_credits_2 = 32
str_credits_3 = 33
str_credits_4 = 34
str_credits_5 = 35
str_credits_6 = 36
str_credits_... |
openaid-IATI/OIPA | OIPA/solr/activity_sector/tasks.py | Python | agpl-3.0 | 883 | 0 | # If on Python 2.X
from __future__ import print_function
import pysolr
from django.conf import settings
from solr.activity_sector.indexing import ActivitySectorIndexing
from solr.tasks import BaseTaskIndexing
solr = pysolr.Solr(
'{url}/{core}'.format(
url=settings.SOLR.get('url'),
core=settings.S... | cores').get('activity-sector')
), always_commit=True, timeout=180
)
class ActivitySectorTaskIndexing(BaseTaskIndexing):
indexing = ActivitySectorIndexing
solr = solr
def run_from_activity(self, activity):
for sectors in activity.activitysector_set.all():
self | .instance = sectors
self.run()
def delete(self):
if settings.SOLR.get('indexing'):
self.solr.delete(q='iati_identifier:{iati_identifier}'.format(
iati_identifier=self.instance.activity.iati_identifier))
|
esteve/rosidl | rosidl_parser/test/test_field.py | Python | apache-2.0 | 2,122 | 0 | # Copyright 2014 Open Source Robotics Foundation, 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... | ssert_raises(TypeError):
Field('type', 'foo') |
with assert_raises(NameError):
Field(type_, 'foo bar')
type_ = Type('bool[2]')
field = Field(type_, 'foo', '[false, true]')
assert field.default_value == [False, True]
type_ = Type('bool[]')
field = Field(type_, 'foo', '[false, true, false]')
assert field.default_value == [False,... |
NcLang/vimrc | sources_non_forked/YouCompleteMe/python/ycm/diagnostic_interface.py | Python | mit | 9,546 | 0.036141 | # Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | kept_signs += [ placed_signs[ placed_signs.index( sign ) ] ]
return new_signs, kept_signs, next_sign_id
def _PlaceNewSigns( kept_signs, new_signs ):
placed_signs = kept_signs[:]
for sign in new_signs:
# Do not set two signs on the same line, it will screw up storing sign
# locations.
if sig... | continue
vimsupport.PlaceSign( sign.id, sign.line, sign.buffer, sign.is_error )
placed_signs.append(sign)
return placed_signs
def _UnplaceObsoleteSigns( kept_signs, placed_signs ):
for sign in placed_signs:
if sign not in kept_signs:
vimsupport.UnplaceSignInBuffer( sign.buffer, sign.id )
def _... |
chippey/gaffer | python/GafferRenderMan/__init__.py | Python | bsd-3-clause | 2,499 | 0.014406 | ##########################################################################
#
# Copyright (c) 2013, Image Engine Desig | n Inc. All rights reserved.
# Copyright (c) 2013, John Haddon. 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
# copyrigh... | s and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Ha... |
tracer9/Applied_Math | Homework_4.py | Python | apache-2.0 | 3,155 | 0.032013 | # -*- coding: utf-8 -*-
"""
Applied Mathematics for Computer Science.
Homework4 -- L-M Algorithm.
@author: LiBin 11531041
@date: 2016 - 5 - 23.
"""
#%% Objective: Assuming given type of the certain function
# " fun(x) = a*exp(-b*t) ", input data "x1,...x10", and output data "y1,..y10",
# using t... | te the f_x, where f(x) = 1/2 * sum( F_x .* 2)
def f_x( x, y, a, b ):
temp = a* np.exp(-b * x) - y
result = np.sum( np.power( temp, 2) ) /2
return result
#%%
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
x = np.matrix([0.... | 18.15, 15.36, 14.10, 12.89, 9.32, 7.45, 5.24, 3.01, 1.85])
mu = 0.01
epsilon = 1e-6
max_iter = 50
a=10
b=0.5
#%%
a_trend = []
b_trend = []
f_trend = []
for loop in range(max_iter):
J = J_x( x, a, b )
F = F_x( x, y, a, b )
## step - 2
g = J.T * F
G = J.T * J
## step - 3
... |
percyfal/snakemakelib-core | snakemakelib/sample/tests/test_sampleorganization.py | Python | mit | 154 | 0.012987 | # Copyright (C) 2015 by Per Unneberg
import | pytest
from snakemakelib.sample. | organization import sample_org
def test_sample_org():
print (sample_org)
|
project-icp/bee-pollinator-app | src/icp/apps/beekeepers/migrations/0014_update_hive_scale_id_help_text.py | Python | apache-2.0 | 579 | 0.001727 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('beekeepers', '0013_update_queen_source_options'),
]
operations = [
migrations.AlterField(
model_name='monthlysur... | _id',
field=models.CharFi | eld(help_text='If you have an automated scale associated with this colony, please enter the hive scale brand and ID number here.', max_length=255, null=True, blank=True),
),
]
|
mlperf/training_results_v0.7 | Google/benchmarks/bert/implementations/bert-research-TF-tpu-v4-512/run_squad.py | Python | apache-2.0 | 46,112 | 0.008696 | """Run BERT on SQuAD 1.1 and SQuAD 2.0."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import math
import os
import random
from language.bert import modeling
from language.bert import optimization
from language.bert import... | on)
if self.start_position:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
... | _mask,
segment_ids,
start_position=None,
end_position=None,
is_impossible=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_... |
myt00seven/svrg | para_gpu/train_vgg.py | Python | mit | 6,897 | 0.00232 | import sys
import time
from multiprocessing import Process, Queue
import yaml
import numpy as np
import zmq
import pycuda.driver as drv
#sys.path.append('./lib')
from tools import (save_weights, load_weights,
save_momentums, load_momentums)
from train_funcs import (unpack_configs, adjust_learning_r... | pshot_freq'] == 0:
save_weights(layers, config['weights_dir'], epoch)
np.save(config['weights_dir'] + 'lr_' + str(epoc | h) + '.npy',
learning_rate.get_value())
save_momentums(vels, config['weights_dir'], epoch)
print('Optimization complete.')
if __name__ == '__main__':
with open('config.yaml', 'r') as f:
config = yaml.load(f)
with open('spec_1gpu.yaml', 'r') as f:
config... |
zstackorg/zstack-woodpecker | integrationtest/vm/monitor/5min_alert_vm_mem_free.py | Python | apache-2.0 | 2,881 | 0.005207 | '''
Test about monitor trigger on vm memory free ratio in five minutes
@author: Songtao,Haochen
'''
import os
import test_stub
import random
import time
import zstacklib.utils.ssh as ssh
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
i... | ,360)
status_problem, status_ok = test_stub.query_trigger_in_loop(trigger,80)
test_util.action_logger('Trigger old status: %s triggered. Trigger new status: %s recovered' % (status_problem, status_ok ))
if status_problem != 1 or status_ok != 1:
|
test_util.test_fail('%s Monitor Test failed, expected Problem or OK status not triggered' % test_item)
mail_list = test_stub.receive_email()
keywords = "fired"
mail_flag = test_stub.check_email(mail_list, keywords, trigger, vm_uuid)
if mail_flag == 0:
test_util.test_fail('Failed ... |
Kshitij-Dhakal/programmingBasics | Project Euler/14.py | Python | gpl-3.0 | 390 | 0.010256 | import operator
def func(n):
if n not in dict:
if (n % 2 == 0):
l = 1 + func(n / 2)
else:
l = 1 + func(3 * n + 1)
dict[n] = l
return dict[n]
else:
return dict[n]
if __name__ == '__main__':
dict = {1: 1}
for i in range(1, | 1000000):
| func(i)
print(max(dict.items(), key=operator.itemgetter(1))[0])
|
berquist/PyQuante | Tests/h2_sto3g.py | Python | bsd-3-clause | 404 | 0.039604 | #!/usr/bin/env python
"H2 using Gaussians"
from PyQuante.Ints import | getbasis,getints
from PyQuante.hartree_fock import rhf
from PyQuante.Molecule import M | olecule
energy = -1.082098
name = "H2"
def main():
h2 = Molecule('h2',atomlist=[(1,(0,0,0.6921756113231793)),(1,(0,0,-0.6921756113231793))])
en,orbe,orbs = rhf(h2,basis="sto3g")
return en
if __name__ == '__main__':
print main()
|
willthames/ansible-lint | lib/ansiblelint/rules/MetaChangeFromDefaultRule.py | Python | mit | 1,254 | 0 | # Copyright (c) 2018, Ansible Project
from ansiblelint.rules import AnsibleLintRule
class MetaChangeFromDefaultRule | (AnsibleLintRule):
id = '703'
shortdesc = 'meta/main.yml default values should be changed'
field_defaults = [
('author', 'your name'),
('description', 'your description'),
| ('company', 'your company (optional)'),
('license', 'license (GPLv2, CC-BY, etc)'),
('license', 'license (GPL-2.0-or-later, MIT, etc)'),
]
description = (
'meta/main.yml default values should be changed for: ``{}``'.format(
', '.join(f[0] for f in field_defaults)
... |
fkie-cad/iva | tests/test_cpe_matching/test_cpe_sorter.py | Python | lgpl-3.0 | 6,349 | 0.007245 | import unittest
from matching.cpe_sorter import *
unsorted_cpes = [{'wfn': {'version': '4.0', 'target_sw': 'android_marshmallow'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.0:beta:~~~android_marshmallow~~'},
{'wfn': {'version': '1.0.1.2', 'target_sw... | value_with\:double_points:internet_explorer:4.3.2:beta | :~~~linux~~'},
{'wfn': {'version': '2010', 'target_sw': 'linux'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta'},
{'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'},
'uri_binding': 'cpe:/a... |
Tisseo/navitia | source/jormungandr/jormungandr/scenarios/tests/journey_compare_tests.py | Python | agpl-3.0 | 42,334 | 0.001842 | # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | 422T0800")
journey1.duration | = 25 * 60
journey1.nb_transfers = 1
journey1.sections.add()
journey1.sections.add()
journey1.sections.add()
journey1.sections.add()
journey1.sections[0].type = response_pb2.PUBLIC_TRANSPORT
journey1.sections[0].duration = 5 * 60
journey1.sections[1].type = response_pb2.TRANSFER
journ... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_v1_generated_job_service_create_hyperparameter_tuning_job_sync.py | Python | apache-2.0 | 2,381 | 0.0021 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | name = "display_name_value"
hyperparameter_tuning_job.study_spec.metrics.metric_id = "metric_id_value"
hyperparameter_tuning_job.study_spec.metrics.goal = "MINIMIZE"
hyperparameter_tuning_job.study_spec.parameters.double_value_spec.min_value = 0.96
hyperparameter_tuning_job.stu | dy_spec.parameters.double_value_spec.max_value = 0.962
hyperparameter_tuning_job.study_spec.parameters.parameter_id = "parameter_id_value"
hyperparameter_tuning_job.max_trial_count = 1609
hyperparameter_tuning_job.parallel_trial_count = 2128
hyperparameter_tuning_job.trial_job_spec.worker_pool_specs.con... |
efornal/pulmo | app/migrations/0031_add_field_url_to_servers.py | Python | gpl-3.0 | 1,551 | 0.003868 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0030_add_field_service_to_connections'),
]
operations = [
migrations.AddField(
model_name='productionserv... | model_name='productionconnectionsource',
name='service',
field=models.CharField(max_length=200, null=True, verbose_name='Servicio', blank=True),
),
| migrations.AlterField(
model_name='productionconnectiontarget',
name='service',
field=models.CharField(max_length=200, null=True, verbose_name='Servicio', blank=True),
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.