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
orchidinfosys/odoo
openerp/addons/test_new_api/tests/test_new_fields.py
Python
gpl-3.0
19,841
0.000504
# # test cases for new-style fields # from datetime import date, datetime from openerp.exceptions import AccessError, except_orm from openerp.tests import common from openerp.tools import mute_logger class TestNewFields(common.TransactionCase): def test_00_basics(self): """ test accessing new fields """...
d check again messages discussion1.name = 'Talking about stuff...' check_
stored(discussion1) # switch message from discussion, and check again discussion2 = discussion1.copy({'name': 'Another discussion'}) message2 = discussion1.messages[0] message2.discussion = discussion2 check_stored(discussion2) # create a new discussion with messages, a...
rbardaji/oceanobs
mooda/waterframe/plot/plot_timebar.py
Python
mit
2,204
0.001361
""" Implementation of WaterFrame.plot_bar(key, ax=None, average_time=None)""" import datetime def plot_timebar(self, keys, ax=None, time_interval_mean=None): """ Make a bar plot of the input keys. The bars are positioned at x with date/time. Their dimensions are given by height. Parameters ...
: matplotlib.axes object, optional (ax = None) It is used to add the plot to an input axes object. time_interval_mean: str, optional (time_interval_mean = None) It calculates an average value of a time interval. You can find all of the re
sample options here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html Returns ------- ax: matplotlib.AxesSubplot Axes of the plot. """ def format_year(x): return datetime.datetime.\ strptime(x, '%Y-%m-%d %H:%M:%S').str...
asuiu/pyxtension
py2/pyxtension/racelib.py
Python
gpl-2.0
1,107
0.001807
#!/usr/bin/python # coding:utf-8 # Author: ASU --<[email protected]> # Purpose: Concurrent utility classes (name coming from RACEconditionLIBrary) # Created: 11/26/2015 import time __author__ = 'ASU' class ContextLock(): def __init__(self, lock): """ :param lock: :type lock: thread.Lo...
aceback): self.__lock.release() return False class TimePerformanceLogger: """ Used to measure the performance of a code block run within a With Statement Context Manager ""
" def __init__(self, logger): """ :param logger: logger function tha would get argument number of seconds :type logger: (basestring) -> None """ self._logger = logger def __enter__(self): self._t1 = time.time() def __exit__(self, exc_type, exc_value, traceb...
Adamtaranto/subset-fasta-by-name
fastsub/cmd_line.py
Python
mit
2,575
0.03534
#!/usr/bin/env python #python 2.7.5 requires biopython #fastsub #Version 1.0.0 Adam Taranto, Sep 2017 #Contact, Adam Tarant
o, [email protected] ################################################################################################# # Takes a multi-fasta file and a list of sequence names, prints named sequences to a new fasta. # ################################################################################################...
file readNames = fs.getTargetNames(args.nameFile, args) # Create dictionary of all sequences SeqMaster = fs.readFasta(args.inFasta) # Write to cluster files if OrthoMCL mode. if args.OrthoMCLMode: fs.orthomode(readNames, SeqMaster,outdir, args.nameFile) # Write each seq from namefile to individual fasta. # If...
googleapis/python-storage
tests/conformance/conftest.py
Python
apache-2.0
3,881
0.001031
# 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 agreed to in writing, s...
s and # limitations under the License. import os import random import uuid import pytest from google.auth.credentials import A
nonymousCredentials from google.cloud import storage from google.cloud.exceptions import NotFound """Environment variable or default host for Storage testbench emulator.""" _HOST = os.environ.get("STORAGE_EMULATOR_HOST", "http://localhost:9000") """Emulated project information for the storage testbench.""" _CONF_TE...
chasetb/sal
server/migrations/0016_auto_20151026_0851.py
Python
apache-2.0
4,470
0.002908
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('server', '0015_auto_20150819_1501'), ] operations = [ migrations.AlterField( model_name='apikey', na...
erField(default=0, db_index=True), ), migrations.AlterField( model_name='machine', name='serial', field=models.CharField(unique=True, max_length=100, db_index=True), ), migrations.AlterField( model_name='machinegroup', name='key...
migrations.AlterField( model_name='osqueryresult', name='hostidentifier', field=models.CharField(db_index=True, max_length=255, null=True, blank=True), ), migrations.AlterField( model_name='osqueryresult', name='name', field=...
isle2983/bitcoin
qa/rpc-tests/nulldummy.py
Python
mit
6,648
0.00722
#!/usr/
bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test NULLDUMMY softfork. Connect to a single node. Generate 2 blocks (sav
e the coinbases for later). Generate 427 more blocks. [Policy/Consensus] Check that NULLDUMMY compliant transactions are accepted in the 430th block. [Policy] Check that non-NULLDUMMY transactions are rejected before activation. [Consensus] Check that the new NULLDUMMY rules are not enforced on the 431st block. [Policy...
willimoa/pydal
tests/base.py
Python
bsd-3-clause
7,487
0.000669
# -*- coding: utf-8 -*- from ._compat import unittest from ._adapt import DEFAULT_URI, drop, IS_MSSQL, IS_IMAP, IS_GAE, IS_TERADATA, IS_ORACLE from pydal import DAL, Field from pydal._compat import PY2 @unittest.skipIf(IS_IMAP, "Reference not Null unsupported on IMAP") @unittest.skipIf(IS_ORACLE, "Reference Not Null...
self.assertRaises(Exception, db.ttt.insert, vv="pydal") # The following is mandatory for backends as PG to close the aborted transaction db.commit() drop(db.ttt)
drop(db.tt) db.close() @unittest.skipIf(IS_IMAP, "Reference Unique unsupported on IMAP") @unittest.skipIf(IS_GAE, "Reference Unique unsupported on GAE") @unittest.skipIf(IS_ORACLE, "Reference Unique unsupported on Oracle") class TestReferenceUNIQUE(unittest.TestCase): # 1:1 relation def testRun(...
GaloisInc/saw-script
saw-remote-api/python/tests/saw/test_points_to_at_type.py
Python
bsd-3-clause
1,590
0.00566
from pathlib import Path import unittest from saw_client import * from saw_client.exceptions import VerificationError from saw_client.crucible import cry, cry_f from saw_client.llvm import Contract, LLVMType, PointerType, void, i32, array_ty from typing import Union class FPointsToContract(Contract): def __init__...
arget_type = self.check_x_type) self.execute_func(p) self.points_to(p, cry_f("{x} # {x}")) self.returns(void) class PointsToAtTypeTest(unittest.TestCase): def test_points_to_at_type(self): connect(reset_server=True) if __name__ == "__main__": view(LogResults()) bc...
ath('tests','saw','test-files', 'points_to_at_type.bc')) mod = llvm_load_module(bcname) result = llvm_verify(mod, "f", FPointsToContract(None)) self.assertIs(result.is_success(), True) result = llvm_verify(mod, "f", FPointsToContract(array_ty(2, i32))) self.assertIs(result.is_s...
stephane-caron/pymanoid
pymanoid/ik.py
Python
gpl-3.0
18,284
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2020 Stephane Caron <[email protected]> # # This file is part of pymanoid <https://github.com/stephane-caron/pymanoid>. # # pymanoid is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public Lic...
motion when approaching the knee singularity, despite the robot being able to move faster with a fully extended knee. """ DEFAULT_GAINS = { 'COM': 0.85, 'CONTACT': 0.85, 'DOF': 0.85, 'MIN_ACCEL': 0.85, 'MIN_CAM': 0.85, 'MIN_VEL': 0.85, 'PENDULUM':...
ULT_WEIGHTS = { 'CONTACT': 1., 'COM': 1e-2, 'POSE': 1e-3, 'MIN_ACCEL': 1e-4, 'MIN_CAM': 1e-4, 'DOF': 1e-5, 'POSTURE': 1e-6, 'MIN_VEL': 1e-6, } def __init__(self, robot, active_dofs=None, doflim_gain=0.5): super(IKSolver, self).__init__() ...
MieszkoGulinski/dungeons-of-xml
dungeons_cli.py
Python
mit
414
0.055556
#!/usr/bin/env python3 # CLI interface in Python 3 import xml.etree.ElementTree as ET def loadMap(): pathToFile
=input("File name: ") pathToFile="testbench.xml" try: xmlFile=ET.parse(pathToFile) except ET.ParseError as e:
print("Error parsing XML:",str(e)) return 0 except FileNotFoundError: print("File does not exist") return 0 def main(): # return 0 if __name__ == '__main__': main()
Micromeritics/report-models-python
micromeritics/constants.py
Python
gpl-3.0
519
0.015414
"""This module defines physical constants that are used for the report models. In most cases this is
a local wrapper for the scipy physical constants VOLGASTP: Volume of one mole of gas at STP (cm^3) AVOGADRO: Avegadro's number. Number of molecules in a mole. NM2_M2: Conversion factor from nm^2 to m^2. """ import scipy.constants import numpy VOLGASTP = pow(10,6) * scipy.constants.physical_constants['molar vol...
selfsk/nodeset.core
src/nodeset/core/observer.py
Python
mit
1,039
0.013474
from twisted.internet import defer from nodeset.common import log from nodeset.core import config class Observer(object): def __init__(self, callable, *args, **kwargs): self.callable = callable self.args = args self.kwargs = k
wargs #print "-- %s, %s" % (self.args, self.kwargs) self.assertfunc = lambda x: True def setAssert(self, assertfunc): self.assertfunc = assertfunc def run(self, *args, **kwargs): a = tuple(list(args) + list(self.args)) kw = dict(kwargs.items() +...
def twist(self, observers, eventDict): defers = [] if config.Configurator['verbose']: log.msg("twist carousel %s, %s" % (observers, eventDict)) for i in observers: defers.append(defer.maybeDeferred(i.run, eventDict)) ...
adamfisk/littleshoot-client
server/appengine/littleshoot/util.py
Python
gpl-2.0
3,265
0.009495
import itertools from google.appengine.ext import db from google.appengine.ext.db import StringProperty import logging import urllib import models import time def expired(startTime, period): return time.time() - startTime > period def isMac(request): return request.META['HTTP_USER_AGENT'].find('Mac') !=...
limewire") { params.source = result.source; } if (CommonUtils.inGroup()) { params.groupName = CommonUtil
s.getGroupName(); } var fileUrl = Constants.DOWNLOAD_URL + encodeURIComponent(result.title) + "?"+ dojo.objectToQuery(params); """
pedrovanzella/bstar-tree
table_datablock.py
Python
lgpl-3.0
7,201
0.004305
import attr import struct import math import re import copy from datablock import Datablock from record import Record from rowid import Rowid @attr.s class TableDatablock(Datablock): header = attr.ib(default=[]) records = attr.ib(default=[]) def get_data(self): """ Convert header and reco...
s if(i+2 < len(self.header)): space_between = self.header[i+2]-(self.header[i]+self.header[i+1]) if(self.header[i+1] == 0): #If header wanted is deleted, ignore header space space
_between += 4 if(space_needed <= space_between): return self.header[i]+self.header[i+1] #Check for space in the end if(self.records_size() -(self.header[last_offset]+self.header[last_offset+1]) >= space_needed): return self.header[last_offset]+self.heade...
FlaminMad/processControl
processControl/dev/yic.py
Python
mit
563
0.039076
# -*- coding: utf-8 -*- """
Created on Wed May 04 22:38:40 2016 @autho
r: Alex """ import numpy as np class yic: def __init__(self): self.struct = np.array([[0],[0],[0]]) self.score = np.array([[0],[0],[0]]) self.fit = np.array([[0],[0],[0]]) return def yic(self, y, u, na, nb, nk): for i in range(0, na+1): for ...
caseydavenport/calico-docker
tests/st/utils/network.py
Python
apache-2.0
3,537
0.000283
# Copyright (c) 2015-2016 Tigera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
t exist, no problem. pass # Create the network, cmd = "docker network create %s %s %s %s" % \ (driver_option, ipam_option, subnet_option, name) docker_net_create = partial(host.execute, cmd) self.uuid = retry_until_success(docker_net_create) def delete(sel...
fied, defaults to the host used to create the network. :return: Nothing """ if not self.deleted: host = host or self.init_host host.execute("docker network rm " + self.name) self.deleted = True def disconnect(self, host, container): """ Di...
cortext/crawtextV2
~/venvs/crawler/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/__init__.py
Python
mit
3,405
0
"""A collection of modules for building different kinds of tree from HTML documents. To create a treebuilder for a new type of tree, you need to do implement several things: 1) A set of classes for various types of elements: Document, Doctype, Comment, Element. These must implement the interface of _base.treebuilders...
if implementation is None: from xml.dom import minidom implementation = minidom # NEVER cache here, caching is done in the dom submodule return dom.getDomModule(implementation, **kwargs).TreeBuilder elif treeType == "lxml": from . impo...
from . import etree if implementation is None: implementation = default_etree # NEVER cache here, caching is done in the etree submodule return etree.getETreeModule(implementation, **kwargs).TreeBuilder else: raise ValueError("""Unrecognised treeb...
Swall0w/clib
clib/links/model/__init__.py
Python
mit
225
0
from clib.links.model import recognition from clib.links.model import superresolution from clib.links.model import vae from clib.links.model
import yolo from clib.links.model import recur
rent from clib.links.model import gan
lamestation/LEAM
media/gfx_font6x8.py
Python
gpl-3.0
165
0.018182
impo
rt pygame sprite = {} sprite['image'] = pygame.image.load("test/font6x8_normal_w.png") sprite['width'] = 6 sprite['height'] = 8 def Addr(): return
sprite
NixaSoftware/CVis
venv/lib/python2.7/site-packages/pandas/core/window.py
Python
apache-2.0
68,731
0.000029
""" provide a generic structure to support window functions, similar to how we have a Groupby object """ from __future__ import division import warnings import numpy as np from collections import defaultdict from datetime import timedelta from pandas.core.dtypes.generic import ( ABCSeries, ABCDataFrame, ...
dex as ndarrays Returns ------- tuple of (index, index_as_ndarray) """ if self.is_freq_type: if index is None: index = self._on return index, index.asi8 return index, index def _prep_values(self, values=None, kill_inf=True, h...
lling functions error on float32 data # make sure the data is coerced to float64 if is_float_dtype(values.dtype): values = _ensure_float64(values) elif is_integer_dtype(values.dtype): values = _ensure_float64(values) elif needs_i8_conversion(values.dtype): ...
matthagy/pbd
pbd/state.py
Python
apache-2.0
8,749
0.005715
##-*- Mode: python -*- ## state.py - Persistance State of Simulation ## -------------------------------------------------------------------------- ## Copyright (C) 2009, Matthew Hagy ([email protected]) ## All rights reserved. ## ## This program is free software: you can redistribute it and/or modify ## it under the term...
int) if len(value.shape)!=1: raise TypeError return value validate
_tags.info = 'a 1 dimensional integer array specifying particle tags' def validate_neighbors(op, name, value): value = numpy.asarray(value, int) if not (len(value.shape)==2 and value.shape[1]==2): raise TypeError return value validate_neighbors.info = 'an integer array of shape (N,2) where N is nu...
futurepr0n/Books-solutions
Python-For-Everyone-Horstmann/Chapter2-Programming-with-Numbers-and-Strings/P2.6.py
Python
mit
510
0.003929
# Write a program that prompts the user for a measurement in meters and then con­ # verts it to miles, feet, and inches. measurementMeters = float(input("Enter the measurement in meters: "
)) measurementMiles = measurementMeters * 0.000621371192 measur
ementFeet = measurementMeters * 3.2808399 measurementInches = measurementMeters * 39.3700787 print("Measurement in miles: %f" % measurementMiles) print("Measurement in feet: %.2f" % measurementFeet) print("Measurement in inches: %.2f" % measurementInches)
pandas-dev/pandas
pandas/tests/tseries/offsets/test_business_quarter.py
Python
bsd-3-clause
12,465
0
""" Tests for the following offsets: - BQuarterBegin - BQuarterEnd """ from __future__ import annotations from datetime import datetime import pytest from pandas._libs.tslibs.offsets import QuarterOffset from pandas.tests.tseries.offsets.common import ( Base, assert_is_on_offset, assert_offset_equal, ) ...
datetime(2007, 1, 1): datetime(2007, 4, 2), datetime(2007, 4, 15): datetime(2007, 7, 2), datetime(2007, 7, 1): datetime(2007, 7, 2), datetime(2007, 4, 1): datetime(2007, 4, 2), datetime(2007, 4, 2): datetime(2007, 7, 2), datetime(2008, ...
erBegin(startingMonth=2), { datetime(2008, 1, 1): datetime(2008, 2, 1), datetime(2008, 1, 31): datetime(2008, 2, 1), datetime(2008, 1, 15): datetime(2008, 2, 1), datetime(2008, 2, 29): datetime(2008, 5, 1), datetime(2008, 3, 15)...
bernardopires/django-tenant-schemas
tenant_schemas/cache.py
Python
mit
510
0
from django.db import connection def make_key(key, key_prefix, versio
n): """ Tenant aware function to generate a cache key. Constructs the key used by all other methods. Prepends the tenant `schema_name` and `key_prefix'. """ return '%s:%s:%s:%s' % (connection.schema_name, key_prefix, version, key) def reverse_key(key): """ Tenant aware function to rev...
RSE_KEY_FUNCTION setting. """ return key.split(':', 3)[3]
SoftwareKing/zstack-utility
consoleproxy/consoleproxy/console_proxy_agent.py
Python
apache-2.0
9,939
0.006439
from zstacklib.utils import plugin from zstacklib.utils import http from zstacklib.utils import shell from zstacklib.utils import log from zstacklib.utils import jsonobject from zstacklib.utils import daemon from zstacklib.utils import linux from zstacklib.utils import filedb from zstacklib.utils import lock i...
ct): def __init__(self, success=True, error=None): self.success = success self.error = error if error else ''
class AgentCommand(object): def __init__(self): pass class EstablishProxyCmd(AgentCommand): def __init__(self): super(EstablishProxyCmd, self).__init__() self.token = None self.targetHostname = None self.targetPort = None self.proxyHostname = None ...
heroandtn3/syncx
file_monitor.py
Python
gpl-2.0
1,978
0.003539
from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer import time import logging import os class FileHandler(): """ Handler to use when monitor a directory. """ def on_created(self, src_path, is_directory): logging.info('On created: "%s
", directory: %s', src_path, is_directory) def on_deleted(self, src_path, is_directory): logging.info('On deleted: "%s", directory: %s', src_path, is_directory) def on_modified(self, src_path, is_directory): logging.info('On modified: "%s", directory: %s', src_path, is_directory) def on_m...
%s', src_path, dest_path, is_directory) class XFileSystemEventHandler(FileSystemEventHandler): """ Custom FileSystemEvent class. """ def __init__(self, file_handler): super(XFileSystemEventHandler, self).__init__() self.handler = file_handler def on_created...
ystk/debian-audit
system-config-audit/src/key_list_dialog.py
Python
gpl-2.0
5,086
0.00059
# Key list dialog. # # Copyright (C) 2008 Red Hat, Inc. All rights reserved. # 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. This program is distributed in the hope that it # will be...
at Author: Miloslav Trmac <[email protected]> from gettext import gettext as _ import audit import gtk import gobject from dialog_base import DialogBase from key_dialog import KeyDialog import util __all__ = ('KeyListDialog') class KeyListDialog(DialogBase): '''Key list dialog.'''
_glade_widget_names = ('keys_add', 'keys_delete', 'keys_down', 'keys_edit', 'keys_list', 'keys_up') def __init__(self, parent): DialogBase.__init__(self, 'key_list_dialog', parent) self.keys_store = gtk.ListStore(gobject.TYPE_STRING) self.keys_list.set_mode...
benjolitz/trollius-redis
examples/benchmarks/speed_test.py
Python
bsd-2-clause
1,736
0
#!/usr/bin/env python """ Benchmark how long it takes to set 10,000 keys
in the database. """ from __future__ import print_function import trollius as asyncio from trollius import From import logging import trollius_redis import time from six.moves import range if __name__ == '__main__': loop = asyncio.get_event_loop() # Enable logging logging.getLogger().addHandler(logging.S...
ndler()) logging.getLogger().setLevel(logging.WARNING) def run(): connection = yield From(trollius_redis.Pool.create( host=u'localhost', port=6379, poolsize=50)) try: # === Benchmark 1 == print( u'1. How much time does it take to set 10,000 v...
theguardian/OrielPy
orielpy/notifiers/tweet.py
Python
gpl-2.0
4,510
0.009091
import cherrystrap import orielpy from cherrystrap import logger, formatter from orielpy import common # parse_qsl moved to urlparse module in v2.6 try: from urllib.parse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import oauth2 as oauth import twitter class T...
(content.decode('UTF-8'))) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a toke
n with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token.get('oauth_token')) logger.info('Access Token secret: %s' % access_token.get('oauth_token_secret')) orielpy.TWITTER_TOKEN = access...
mrquim/repository.mrquim
script.module.pycryptodome/lib/Crypto/SelfTest/Signature/test_dss.py
Python
gpl-2.0
28,054
0.002139
# # SelfTest/Signature/test_dss.py: Self-test for DSS signatures # # =================================================================== # # Copyright (c) 2014, Legrandin <[email protected]> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted pr...
def t2l(hexstring): ws = hexstring.replace(" ", "").replace("\n", "") return long(ws, 16) def load_hash_by_name(hash_name): return __import__("Crypto.Hash." + hash_name, globals(), locals(), ["new"]) class TestKey(object): pass class TestVector(object): pass class StrRNG: def __init__...
self._idx = 0 # Fix required to get the right K (see how randint() works!) self._randomness = long_to_bytes(bytes_to_long(randomness) - 1, length) def __call__(self, n): out = self._randomness[self._idx:self._idx + n] self._idx += n return out class FIPS_DSA_Tests(unit...
crosslinks/XlinkAnalyzer
pytests/pyt_TestOldFormatPolI.py
Python
gpl-2.0
1,687
0.004149
import chimera import XlaGuiTests import xlinkanalyzer as xla # for this test to run do: # chimera --pypath ~/devel/XlinkAnalyzer --pypath ~/devel/pyxlinks/ run.py <name of this file> RUNME = True description = "Tests gui class" class TestPolI(XlaGuiTests.XlaBaseTest): def setUp(self): mPaths = ['Pol...
self.assertEqual(10, len(self.g.configFrame.config.dataItems)) self.assertSetEqual(set([u'A190', u'A135', u'AC40', u'A14', u'ABC27', u'ABC23', u'A4
3', u'ABC14.5', u'A12', u'ABC10beta', u'AC19', u'ABC10alpha', u'A49', u'A34.5']), set(self.g.configFrame.config.getSubunitNames())) self.assertEqual(1, len(xFrame.getXlinkDataMgrs())) xmgr = xFrame.getXlinkDataMgrs()[0] self.assertEqual(171, len(xmgr.pbg.pseudoBonds)) xFra...
Drrechu/rna2d
tests/TestConnections.py
Python
gpl-3.0
610
0.009836
# To change this license header, choose License Headers in Project Properties. # To change this template f
ile, choose Tools | Templates # and open the template in the editor. import unittest from context import src class NewTestCase(unittest.TestCase): def test_connections_handling(self): assert src.rna2d.connection_dict_creator("....(((..[[...))).]]") == {0: None, 1: None, 2: None, 3: None, 4: 16, 5: ...
12: None, 13: None, 14: 6, 15: 5, 16: 4, 17: None, 18: None, 19: None} if __name__ == '__main__': unittest.main()
jeffery9/mixprint_addons
report_webkit/__openerp__.py
Python
agpl-3.0
3,813
0.00236
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com) # All Right Reserved # # Author : Nicolas Bessi (Camptocamp) # # WARNING: This program as such is intended to be used by professional # programmers who ...
Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## { 'name': 'Webkit Report Engine', 'description': """ This module adds a new Report Engine based on WebKit library (wkhtmltopdf) to support rep...
== The module structure and some code is inspired by the report_openoffice module. The module allows: ------------------ - HTML report definition - Multi header support - Multi logo - Multi company support - HTML and CSS-3 support (In the limit of the actual WebKIT version) - JavaScript suppor...
cool-RR/cute-wing-stuff
scripts/selecting_stuff.py
Python
mit
6,144
0.007324
# Copyright 2009-2014 Ram Rachum. # This program is distributed under the MIT license. ''' This module defines scripts for selecting stuff. See their documentation for more information. ''' from __future__ import with_statement import bisect import re import _ast import os.path, sys sys.path += [ os.path.dirna...
_parse(string).body except SyntaxError: return False else: if len(nodes) != 1: return False else: (node,) = nodes return type(node) == _ast.Expr variable_name_pattern_text = r'[a-zA-Z_][0-9a-zA-Z_]*' dotted_name_pattern = re.compile( r'\.?^%...
(variable_name_pattern_text, variable_name_pattern_text) ) def _is_dotted_name(string): '''Is `string` a dotted name?''' assert isinstance(string, str) return bool(dotted_name_pattern.match(string.strip())) whitespace_characters = ' \n\r\t\f\v' def _is_whitespaceless_name(st...
chris-allan/openmicroscopy
components/tools/OmeroWeb/omeroweb/webgateway/urls.py
Python
gpl-2.0
11,852
0.010631
# # webgateway/urls.py - django application url handling configuration # # Copyright (c) 2007, 2008, 2009 Glencoe Software, Inc. All rights reserved. # # This software is distributed under the terms described by the LICENCE file # you can find at the root of the distribution bundle, which states you are # free to use...
ndering settings. Params in render_thumbnail/<iid>/<w>/<h> a
re: - iid: Image ID - w: Optional max width - h: Optional max height """ render_roi_thumbnail = (r'^render_roi_thumbnail/(?P<roiId>[^/]+)/?$', 'webgateway.views.render_roi_thumbnail') """ Returns a thumbnail jpeg of the OMERO ROI. See L{views.render_roi_thumbnail}. Uses current rendering settings. ...
warwick-one-metre/environmentd
warwick/observatory/environment/constants.py
Python
gpl-3.0
1,389
0
# # This file is part of environmentd # # environmentd 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. # # environmentd is distributed ...
ge(cls, error_code): """Returns a human readable string describin
g an error code""" if error_code in cls._messages: return cls._messages[error_code] return 'error: Unknown error code {}'.format(error_code)
sgarrity/bedrock
tests/pages/firefox/whatsnew/whatsnew_60.py
Python
mpl-2.0
626
0.001597
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from selenium.webdriver.common.by import By from pages.firefox.base import FirefoxBasePage class FirefoxWhatsNew60Pag...
e): URL_TEMPLATE = '/{locale}/firefox/60.0/whatsnew/all/{params}' _account_button_locator = (By.CSS_SELECTOR, '.content-main .js-fxa-product-button') @property def is_account_button_displayed(self):
return self.is_element_displayed(*self._account_button_locator)
pbs/powwow
powwow/apps/models.py
Python
bsd-3-clause
467
0.006424
from django.db import models SETTING_NAME = ( ('conf_space', 'Confl
uence Space Key'), ('conf_page', 'Confluence Page'), ('jira_project', 'JIRA Project Code Name'), ('github_project', 'GitHub Project'), ) class AppSettings(models.Model): name = models.CharField(max_length=50, primary_key=True, choices=SETTING_NAME) content = models.CharField...
verbose_name_plural = "settings"
bastianh/evelink
tests/test_char.py
Python
mit
39,606
0.001793
import mock from tests.compat import unittest from tests.utils import APITestCase import evelink.api as evelink_api import evelink.char as evelink_char API_RESULT_SENTINEL = evelink_api.APIResult(mock.sentinel.api_result, 12345, 67890) class CharTestCase(APITestCase): def setUp(self): super(CharTestC...
): self.api.get.return_value = self.make_api_result("char/wallet_balance.xml") result, current, expires = self.char.wallet_bal
ance() self.assertEqual(current, 12345) self.assertEqual(expires, 67890) self.assertEqual(result, 209127923.31) self.assertEqual(self.api.mock_calls, [ mock.call.get('char/AccountBalance', params={'characterID': 1}), ]) @mock.patch('evelink.char.parse_wa...
jamespcole/home-assistant
homeassistant/components/whois/sensor.py
Python
apache-2.0
4,299
0
""" Get WHOIS information for a given host. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.whois/ """ from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeass...
s']) if 'updated_date' in response: update_date = res
ponse['updated_date'] if isinstance(update_date, list): attrs[ATTR_UPDATED] = update_date[0].isoformat() else: attrs[ATTR_UPDATED] = update_date.isoformat() if 'registrar' in response: attrs[ATTR_REGISTRAR] = response['...
plotly/python-api
packages/python/plotly/plotly/graph_objs/bar/unselected/_textfont.py
Python
mit
5,177
0.000966
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Textfont(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "bar.unselected" _path_str = "bar.unselected.textfont" _valid_props = {"color"} # colo...
nstructor or an instance of :class:`plotly.graph_objs.bar.unselected.Textfont` color
Sets the text font color of unselected points, applied only when a selection exists. Returns ------- Textfont """ super(Textfont, self).__init__("textfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return ...
aemal/westcat
annotator/save.py
Python
agpl-3.0
616
0.008117
from django.http import H
ttpResponse from django.db import connection def save_ajax(request): cursor = connection.cursor() cursor.execute("INSERT INTO codings_values (coding_id,field_id,intval) VALUES (34,"+request.POST.get("fieldID", "")+","+request.POST.get("fieldValueID", "")+")") ''' cursor.execute("SELECT col1, col2 FROM...
ponse(row[0]) else: return HttpResponse("No Record") ''' return HttpResponse("Done!"+request.POST.get("fieldID", "")+"--"+request.POST.get("fieldValueID", ""))
botswana-harvard/edc-sms
edc_sms/wsgi.py
Python
gpl-2.0
391
0
""" WSGI config for edc_sms project. It exposes the WSGI callable as a module-level variable named ``application``. For
more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODUL
E', 'edc_sms.settings') application = get_wsgi_application()
xu6148152/Binea_Python_Project
FluentPython/object_reference_mutability_recycling/weakref_test.py
Python
mit
647
0.003091
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import weakref a_set = {0, 1} wref = weakref.ref(a_set) print(wref) print(wref()) a_set = {2, 3, 4} print(wref()) print(wref() is None) print(wref() is None) class Cheese: def __init__(self, kind):
self.kind = kind def __repr__(self): return 'Cheese(%r)' % self.kind import weakref stock = weakref.WeakKeyDictionary() catalog = [Cheese('Red Leicester'), Cheese('Tilsit'), Cheese('Brie'), Cheese('Parmesan')] for cheese in catalog: stock[cheese
.kind] = cheese print(sorted(stock.keys())) del catalog print(stock.keys()) del cheese print(sorted(stock.keys()))
yangleo/cloud-github
openstack_dashboard/dashboards/project/routers/extensions/extraroutes/tables.py
Python
apache-2.0
2,682
0
# Copyright 2015, Thales Services SAS # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
cy.PolicyTargetMixin, tables.LinkAction): name = "create" verbose_name = _("Add Static Route") url = "horizon
:project:routers:addrouterroute" classes = ("ajax-modal",) icon = "plus" policy_rules = (("network", "update_router"),) def get_link_url(self, datum=None): router_id = self.table.kwargs['router_id'] return reverse(self.url, args=(router_id,)) class RemoveRouterRoute(policy.PolicyTarge...
houshengbo/nova_vmware_compute_driver
nova/api/openstack/compute/views/limits.py
Python
apache-2.0
3,495
0.000286
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright
2010-2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.o
rg/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...
azariven/BioSig_SEAS
SEAS_Aux/Visualizer/Spec_Gui.py
Python
gpl-3.0
24,054
0.018458
""" This Module is the graphic user interface wrapper for accessing the all small molecules database Current Problems: Compatibility issues and quick fix: Issues with upgraded version of matplotlib: for ubuntu: sudo apt-get install tk-dev libpng-dev libffi-dev dvipng texlive-...
ructure added jdx_file reader and eliminated redundancy Things to do, legends for plot config files, comments add spectra analysis tools like area under curve, etc rescrape nist rework database, recreate spectra table in db_interact
add a scroll bar to structure frame pip install packaging plot info button and method to save spectra image understand dpi image naming Code Ownership: Sara Seager, Zhuchang Zhan """ VERSION = "0.3.3.1" # System Default Packages import os import sys import shutil import numpy as np from Tkinter...
davidam/python-examples
gtk/cellrenderedcombo.py
Python
gpl-3.0
2,560
0.001564
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
ple") self.set_default_size(200, 200) liststore_manufacturers = Gtk.ListStore(str) manufacturers = ["Sony", "LG", "Panasonic", "Toshiba", "Nokia", "Samsung"] for item in manufacturers: liststore_manufacturers.append([item]) self.liststore_hardware = Gtk...
lf.liststore_hardware.append(["DVD Player", "Sony"]) treeview = Gtk.TreeView(model=self.liststore_hardware) renderer_text = Gtk.CellRendererText() column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0) treeview.append_column(column_text) renderer_combo = Gtk.CellRende...
manjunaths/tensorflow
tensorflow/tensorboard/plugins/debugger/plugin_test.py
Python
apache-2.0
3,406
0.002936
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
thon.platform import test from tensorflow.tensorboard.plugins.debugger import plugin as debugger_plugin class FakeRequest(object): """A fake shell of a werkzeug request. We fake instead of using a real request because the real request requires a WSGI environment. """ def __init__(self, method, post_data):...
The uppercase method of the request, ie POST. post_data: A dictionary of POST data. """ self.method = method self.form = post_data class DebuggerPluginTest(test.TestCase): def setUp(self): self.debugger_plugin = debugger_plugin.DebuggerPlugin() self.unused_run_paths = {} self.unused_l...
rigdenlab/ample
ample/util/version.py
Python
bsd-3-clause
145
0
__version_info__ = (1,
5, 5) __version__ = '.'.join(str(v) for v in __version_info__) __git_revno__ = "3b9cd7076b27f40eda31c1194e50801878
237e90"
bvnayak/pvl
setup.py
Python
bsd-3-clause
1,274
0
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme =
open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='pvl', version='0.2.0', description='Python implementation of PVL (Parameter Value Language)', long_descrip
tion=readme + '\n\n' + history, author='The PlanetaryPy Developers', author_email='[email protected]', url='https://github.com/planetarypy/pvl', packages=[ 'pvl', ], package_dir={'pvl': 'pvl'}, include_package_data=True, install_requires=[ 'pytz', ...
OpenSoccerManager/opensoccermanager
uigtk/mainscreen.py
Python
gpl-3.0
1,395
0
#!/usr/bin/env python3 # This file is part of OpenSoccerManager. # # OpenSoccerManager 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 ver...
r # more details. # # You should have received a copy of the GNU Gene
ral Public License along with # OpenSoccerManager. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gtk import data import uigtk.information import uigtk.menu import uigtk.widgets class MainScreen(Gtk.Grid): ''' Main shell of the in-game window containing menus and information bar. ...
ratoaq2/Flexget
flexget/plugins/input/tail.py
Python
mit
6,794
0.002502
from __future__ import unicode_literals, division, absolute_import import os import re import logging from sqlalchemy import Column, Integer, Unicode from flexget import options, plugin from flexget.db_schema import versioned_base from flexget.entry import Entry from flexget.event import event from flexget.manager im...
ug('search field: %s regexp: %s' % (field, regexp)) match = re.search(regexp, line)
if match: # check if used field detected, in such case start with new entry if field in used: if entry.isvalid(): log.info('Found field %s again before entry was completed. \ ...
Xopherus/redis-url-py
test_redis_url.py
Python
bsd-2-clause
1,467
0.001363
import redis_url import unittest class RedisUrlTestSuite(unittest.TestCase): def test_redis_parse_localhost(self): self.assertEqual( redis_url.parse('redis://localhost:6379/0?cluster=false'), { 'host': 'localhost', 'port': 6379, 'db'...
dis_parse_cluster_localhost(self): self.assertEqual( redis_url.parse('redis://localhost:6379?cluster=true'), { 'host': 'localhost', 'port': 6379, 'password': None } ) def test_redis_parse_cluster_skip_full_coverage_...
ster=true&skip_full_coverage_check=true'), { 'host': 'localhost', 'port': 6379, 'password': None, 'skip_full_coverage_check': True, } ) if __name__ == '__main__': unittest.main()
Rawtechio/oscar
oscar/collection/migrations/0002_missed_notes.py
Python
mit
436
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-21 11:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(mi
grations.Migration): dependencies = [ ('collection', '0001_initial'), ] operations = [ migrations.AddField( model_name='missed',
name='notes', field=models.TextField(blank=True), ), ]
xuru/pyvisdk
pyvisdk/enums/virtual_machine_flag_info_monitor_type.py
Python
mit
248
0
#######
################################# # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum VirtualMachineFlagInfoMonitorType = Enum( 'debug', 'release
', 'stats', )
betterlife/flask-psi
manage.py
Python
mit
184
0
#!/usr/bin/env python import sys args = ' '.jo
in(sys.argv[1:]) print(f"""Deprecated as of commit
959939b771. Use flask utility script instead: $ flask {args} """) raise SystemExit(1)
shanot/imp
modules/multi_state/.imp_info.py
Python
gpl-3.0
34
0
{ "name": "IMP.multi_state" }
CTPUG/wafer
wafer/management/commands/wafer_speaker_tickets.py
Python
isc
1,984
0
import sys import csv from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from wafer.talks.models import ACCEPTED, PROVISIONAL class Command(BaseCommand): help = ("List speakers and associated tickets. By default, only lists" " speakers for provisionall...
ckets (for all talks)') parser.add_argument('--accepted', action="store_true", help='List speakers and tickets (for' ' fully accepted talks)') def _speaker_tickets(self, options): people = get_user_model().objects.filter( talk...
ilter out the speakers from ordinary # accounts if options['all']: titles = [x.title for x in person.talks.all()] elif options['accepted']: titles = [x.title for x in person.talks.filter(status=ACCEPTED)] else: ...
KousikaGanesh/purchaseandInventory
openerp/addons/account_followup/report/account_followup_print.py
Python
agpl-3.0
6,338
0.007258
# -*- 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...
self._lines_get, 'get_text': self._get_text }) def _ids_to_objects(self, ids): pool = pooler.get_pool(self.cr.dbname) all_lines = [] for line in pool.get('account_followup.stat.by.partner').browse(self.cr, self.uid, ids): if line not in all_lines: ...
by_partner_line): return self._lines_get_with_partner(stat_by_partner_line.partner_id, stat_by_partner_line.company_id.id) def _lines_get_with_partner(self, partner, company_id): pool = pooler.get_pool(self.cr.dbname) moveline_obj = pool.get('account.move.line') moveline_ids = movel...
sonofeft/Tk_Nosy
setup.py
Python
gpl-3.0
4,543
0.003962
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/tk_nosy """ # Always prefer setuptools over distutils try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages # To use a consi...
ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3....
ust specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['.hg', '.tox', 'docs', 'tests']), # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires...
bccp/nbodykit
nbodykit/algorithms/tests/test_threeptcf.py
Python
gpl-3.0
5,475
0.006758
from runtests.mpi import MPITest from nbodykit.lab import * from nbodykit import setup_logging from numpy.testing import assert_allclose, assert_array_equal import os setup_logging("debug") # The test result data (threeptcf_sim_result.dat) is computed with # Daniel Eisenstein's # C++ implementation on the same input ...
s, edges, BoxSize=BoxSize, w
eight='w') # load the result from file truth = numpy.empty((8,8,11)) with open(os.path.join(data_dir, 'threeptcf_sim_result.dat'), 'r') as ff: for line in ff: fields = line.split() i, j = int(fields[0]), int(fields[1]) truth[i,j,:] = list(map(float, fields[2:])) ...
mph-/lcapy
lcapy/impedancemixin.py
Python
lgpl-2.1
1,622
0.006782
from .expr import expr from .immittancemixin import ImmittanceMixin from .quantity import Quantity class ImpedanceMixin(Quantity, ImmittanceMixin): quantity = 'impedance' quantity_label = 'Impedance' quantity_units = 'ohm' is_impedance = True is_immittance = True is_ratio = True # Immitta...
n admittance(1 / self) @property def Z(self): """Impedance.""" return self def __rtruediv__(self, x):
"""Reverse true divide""" x = expr(x) if x.is_constant: from .admittance import admittance return admittance(x.expr / self.expr) return super(ImpedanceMixin, self).__rtruediv__(x) def cpt(self): from .oneport import R, C, L, Z f...
cgstudiomap/cgstudiomap
main/eggs/python_stdnum-1.2-py2.7.egg/stdnum/ch/uid.py
Python
agpl-3.0
3,006
0
# uid.py - functions for handling Swiss business identifiers # coding: utf-8 # # Copyright (C) 2015 Arthur de Jong # # 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; either # version 2.1 o...
wiki/Unternehmens-Identifikationsnummer >>> validate('CHE-100.155.212') 'CHE100155212' >>> validate('CHE-100.155.213') Traceback (most recent call last): ... InvalidChecksum: ... >>> format('CHE100155212') 'CHE-100.155.212' """ from stdnum.exceptions import * from stdnum.util import clean def compact(number): ...
ert the number to the minimal representation. This strips surrounding whitespace and separators.""" return clean(number, ' -.').strip().upper() def calc_check_digit(number): """Calculate the check digit for organisations. The number passed should not have the check digit included.""" weights = (5,...
535521469/crawler_sth
scrapy/nbsc/spiders/tjbz_spider.py
Python
bsd-3-clause
311
0.013201
# -
*- coding:utf-8 -*- ''' Created on 2013-3-6 @author: corleone 统计标准 ''' from scrapy.spider import BaseSpider class Tjbz_Spider(BaseSpider): name = "nbsc" url = "http://www.stats.gov.cn/tjbz/" start_urls = [ "http://www.stats.gov.cn/tjbz/", # 20
02-12-31 ]
ktan2020/legacy-automation
win/Lib/site-packages/wx-3.0-msw/wx/py/parse.py
Python
mit
5,270
0.020683
"""parse.py is a utility that allows simple checking for line continuations to give the shell information about where text is commented and where it is not and also how to appropriately break up a sequence of commands into separate multi-line commands... """ __author__ = "David N. Mashburn <david.n.mashburn@gmai...
#print
'Incomplete Syntax!!' return ['Incomplete Syntax Error',i] if newIndent and not ignoreErrors: #print 'Incomplete Indentation!' return ['Incomplete Indentation Error',i] # Note that if one of these errors above gets thrown, the best solution is to pass the resulting block...
morrigan/user-behavior-anomaly-detector
src/helpers.py
Python
mit
6,242
0.003364
#!/usr/bin/python import numpy, os, time, math from sklearn.preprocessing import MinMaxScaler, StandardScaler, normalize import ConfigParser import os.path from sklearn.metrics import mean_squared_error from keras.preprocessing import sequence import json, time def ConfigSectionMap(settings_file, section): Confi...
ataset)): rmse = math.sqrt(mean_squared_error(dataset[i][0], predictions[i])) rmse_totals.append(rmse) return rmse_totals """ Convert an array of values into a dataset matrix """ def convert_to_timeseries(dataset, look_back=3): dataX, dataY = [], [] for i in range(len(dataset) - look_...
dataY.append(b) dataX, dataY = numpy.array(dataX), numpy.array(dataY) # reshape input to be [samples, time steps, features] #dataX = numpy.reshape(dataX, (dataX.shape[0], look_back, dataX.shape[1])) return dataX, dataY def get_real_predictions(dataset): dataX, dataY = [], [] for i in range(...
dpogue/korman
korman/nodes/node_softvolume.py
Python
gpl-3.0
6,912
0.002459
# This file is part of Korman. # # Korman 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. # # Korman is distributed i...
, context, layout): layout.prop(self, "inside_strength") layout.prop(self, "outside_strength") def propagate(self, softvolume): softvolume.insideStrength = self.ins
ide_strength / 100 softvolume.outsideStrength = self.outside_strength / 100 class PlasmaSoftVolumeReferenceNode(idprops.IDPropObjectMixin, PlasmaNodeBase, bpy.types.Node): bl_category = "SV" bl_idname = "PlasmaSoftVolumeReferenceNode" bl_label = "Soft Region" bl_width_default = 150 output...
theonion/pageview-client
example/app/models.py
Python
mit
157
0
f
rom django.db import models class Article(mode
ls.Model): title = models.CharField(max_length=255) body = models.TextField(default="", blank=True)
BT-csanchez/hr
__unported__/hr_webcam/__openerp__.py
Python
agpl-3.0
1,567
0
# -*- coding:utf-8 -*- # # # Copyright (C) 2013 Michael Telahun Makonnen <[email protected]>. # All Rights Reserved. # # This program 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, eit...
out even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.or
g/licenses/>. # # { 'name': 'Capture employee picture with webcam', 'version': '1.0', 'category': 'Generic Modules/Human Resources', 'description': """ HR WebCam ========= Capture employee pictures with an attached web cam. """, 'author': 'Michael Telahun Makonnen <[email protected]>', '...
lukecwik/incubator-beam
sdks/python/apache_beam/dataframe/transforms_test.py
Python
apache-2.0
14,277
0.006934
# # 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 us...
ession({input_placeholder: input})) check_correct(expected, actual_deferred) with beam.Pipeline() as p: input_pcoll = p | beam.Create([input.iloc[::2], input.iloc[1::2]]) input_df = convert.to_dataframe(input_pcoll, proxy=empty) output_df = func(input_df) output_proxy = output_df._exp...
self.assertTrue( output_proxy.iloc[:0].equals(expected.iloc[:0]), ( 'Output proxy is incorrect:\n' f'Expected:\n{expected.iloc[:0]}\n\n' f'Actual:\n{output_proxy.iloc[:0]}')) else: self.assertEqual(type(output_proxy), type(expe...
hgascon/pulsar
pulsar/core/sippy/SipResponse.py
Python
bsd-3-clause
2,860
0.018531
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
r(name = 'cseq', body = cseq)) self.appendHeader(SipHeader(name = 'server')) if body != None: self.setBody(body) def setSL(self, startline): sstartline = startline.split(None, 2) if len(sstartline) == 2: # Some brain-damaged UAs don't include reason in some c...
ver, scode = sstartline self.reason = 'Unspecified' else: self.sipver, scode, self.reason = startline.split(None, 2) self.scode = int(scode) if self.scode == 100 or self.scode >= 400: self.ignorebody = True def setSCode(self, scode, reason): self....
CtrlC-Root/ssh-ldap-utils
ssh_ldap_utils/authorized_keys.py
Python
mit
2,487
0
from __future__ import absolute_import, print_function import os import pwd import grp import sys import subprocess from .command import Command class AuthorizedKeysCommand(Command): """ Get authorized keys for a user using NSS and SSSD. """ @staticmethod def configure_parser(parser): "...
sh helper!", file=sys.stderr) sys.exit(1) # determine the users we need to retrieve keys for users = set([self.args.user]) if self.args.include_group: try: # retrieve the user's passwd entry user_passwd = pwd.getpwnam(self.args.user) ...
file=sys.stderr) sys.exit(1) try: # retrieve the user's primary group user_group = grp.getgrgid(user_passwd[3]) except KeyError as e: print( "failed to retrieve user's primary group: {0}".fo...
zygmuntz/kaggle-advertised-salaries
optional/cols_dimensionality.py
Python
mit
1,451
0.071675
'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue wo...
', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = ma...
ze ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n...
akshara775/PerfKitBenchmarker-master-2
perfkitbenchmarker/providers/azure/util.py
Python
apache-2.0
1,611
0.003724
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
IES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for working with Azure resources.""" import
logging from perfkitbenchmarker import vm_util AZURE_PATH = 'azure' EXPECTED_VERSION = '0.9.9' def CheckAzureVersion(): """Warns the user if the Azure CLI isn't the expected version.""" version_cmd = [AZURE_PATH, '-v'] try: stdout, _, _ = vm_util.IssueCommand(version_cmd) except OSError: # IssueComm...
github/codeql
python/ql/test/3/library-tests/modules/package_members/test_package/__init__.py
Python
mit
56
0.017857
f
rom .module1 import *
from .module4 import * import sys
scheib/chromium
tools/perf/benchmarks/dromaeo.py
Python
bsd-3-clause
675
0.005926
# Copyright 2013 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. from benchmarks import press fr
om telemetry import benchmark from page_sets import dromaeo_pages @benchmark.Info(component='Blink>Bindings', emails=['[email protected]', '[email protected]', 'harak
[email protected]']) # pylint: disable=protected-access class DromaeoBenchmark(press._PressBenchmark): @classmethod def Name(cls): return 'dromaeo' def CreateStorySet(self, options): return dromaeo_pages.DromaeoStorySet()
pratapvardhan/pandas
pandas/tests/io/test_gbq.py
Python
bsd-3-clause
4,286
0
import pytest from datetime import datetime import pytz import platform import os import numpy as np import pandas as pd from pandas import compat, DataFrame from pandas.compat import range pandas_gbq = pytest.importorskip('pandas_gbq') PROJECT_ID = None PRIVATE_KEY_JSON_PATH = None PRIVATE_KEY_JSON_CONTENTS = None...
times = [datetime.now(pytz.timezone('US/Arizona')) for t in range(test_size)] return DataFrame({'bools': bools[0], 'flts': flts[0], 'ints': ints[0], 'strs': strs[0], 'times': times[0]}, inde...
eAccountKeyPath(object): @classmethod def setup_class(cls): # - GLOBAL CLASS FIXTURES - # put here any instruction you want to execute only *ONCE* *BEFORE* # executing *ALL* tests described below. _skip_if_no_project_id() _skip_if_no_private_key_path() clean_gb...
klmitch/nova
nova/tests/unit/fake_requests.py
Python
apache-2.0
1,670
0
# 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, softwa
re # 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. """Fakes relating to the `requests` module.""" import requ...
xuwei0455/design_patterns
Builder.py
Python
mit
1,476
0.000678
# -*- coding: utf-8 -*- """ Builder pattern """ class Director(object): def __init__(self): self.builder = None def construct_building(self): self.builder.new_fridge() self.builder.build_main() self.builder.build_box() def get_building(self): return self.build...
Little' class Fridge(object): """ Product """ def __init__(self): self.main = None self.box = None def __repr__(self): return 'Fridge: {0.main} in Box: {0.box}'.format(self) if __name__ == "__main__": director = Director() director.builder = BuilderBig() dire...
building = director.get_building() print(building) director.builder = BuilderSmall() director.construct_building() building = director.get_building() print(building)
markuz/makuz_youtube_downloader
libmyd/variables.py
Python
gpl-3.0
1,053
0.005698
# This file is part of the markuz_youtube_downlaoder project # # Copyright (c) 2011 Marco Antonio Islas Cruz # # markuz_youtube_downlaoder 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 th...
lin St, Fifth Floor, Boston, MA 02110-1301 USA ''' Variables to be used in the program. Created on Jul 26, 2011 @author: Marco Antonio Islas Cruz ''' #Before going on, you should create your own youtu
be developer_key, #Get one at http://code.google.com/apis/youtube/dashboard/ YOUTUBE_DEVELOPER_KEY =
FredLoney/nipype
examples/smri_freesurfer.py
Python
bsd-3-clause
1,804
0
#!/usr/bin/env python """ ================ sMRI: FreeSurfer ================ This script, smri_freesurfer.py, demonstrates the ability to call reconall on a set of subjects and then make an average subject. python smri_freesurfer.py Import necessary modules from nipype. """ import os import nipype.pipeline.eng...
id'], outfields=['struct']), name='datasource', iterfield=['subject_id']) datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = dict(struct=[['
subject_id', 'struct']]) datasource.inputs.subject_id = subject_list """ Run recon-all """ recon_all = pe.MapNode(interface=ReconAll(), name='recon_all', iterfield=['subject_id', 'T1_files']) recon_all.inputs.subject_id = subject_list if not os.path.exists(subjects_dir): os.mkdir(subjects_d...
jobiols/odoo-addons
point_of_sale_fast_close/models/__init__.py
Python
agpl-3.0
173
0
# For copyright and license notic
es, s
ee __manifest__.py file in module root from . import pos_session from . import account_bank_statement from . import pos_order_inherit
hsr-ba-fs15-dat/opendatahub
src/main/python/hub/formats/interlis_model.py
Python
mit
6,028
0.002157
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import re from hub.formats import Format, Formatter from hub.structures.file import File from hub.structures.frame import OdhType class InterlisModelFormat(Format): name = 'INTERLIS1Model' label = 'INTERLIS 1 Modell' description...
'!! Unbekannter Typ' if type == OdhType.TEXT: max_length = self.df[name].str.len().max() if self.df[name].any() else 10 ili_type = 'TEXT*{}'.format(int(max_length)) elif type in (OdhType.INTEGER, OdhType.BIGINT, OdhType.SMALLINT): min = self.df[...
min = -self.next_nines(-min) if min and min < 0 else 0 max = self.df[name].max() max = self.next_nines(max) if max and max > 0 else 0 ili_type = '[{} .. {}]'.format(min, max) elif type == OdhType.FLOAT: max = self.df[name].max() ...
Pikecillo/genna
external/4Suite-XML-1.0.2/test/Xml/Xslt/Core/test_number_sort.py
Python
gpl-2.0
16,145
0.000805
#Based on the XSLT spec: http://docs.local/REC-xslt-19991116.html#sorting and #http://docs.local/REC-xslt-19991116.html#number from Xml.Xslt import test_harness source_1="""<?xml version="1.0" encoding="utf-8"?> <employees> <employee> <name> <id>1024</id> <given>James</given> <family>Clark</fa...
li><li>Mike Olson</li><li>James Doe</li><li>Mike Doe</li><li>Uche Ogbuji</li></ul>""" sheet_5 = """<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <!-- Some number formatting tests --> ...
xsl:text> <xsl:apply-templates/> </xsl:template> <xsl:template match="*"> <xsl:number format="==>I.A.1.a.i. " level="multiple" count="*[not(name()='comment')]"/> <xsl:value-of select="concat(name(), ': ' , @name, '&#10;')"/> <xsl:apply-templates select="*"/> </xsl:template> <xsl:template match...
xunilrj/sandbox
courses/MITx/MITx 6.86x Machine Learning with Python-From Linear Models to Deep Learning/project5/rl/agent_dqn.py
Python
apache-2.0
6,756
0.003552
"""Tabular QL agent""" import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm import framework import utils DEBUG = False GAMMA = 0.5 # discounted factor TRAINING_EP = 0.5 # epsilon-greedy parameter for ...
dictionary)) if for_training: # update Q-function. deep_q_learning(current_state_vector, next_action_index, next_object_index, reward, next_state_vector, terminal) if not for_training: # update reward epi_reward += (G...
reward def run_epoch(): """Runs one epoch and returns reward averaged over test episodes""" rewards = [] for _ in range(NUM_EPIS_TRAIN): run_episode(for_training=True) for _ in range(NUM_EPIS_TEST): rewards.append(run_episode(for_training=False)) return np.mean(np.array(rewards)...
dl1ksv/gnuradio
gr-analog/python/analog/qa_probe_avg_mag_sqrd.py
Python
gpl-3.0
2,618
0
#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import math from gnuradio import gr, gr_unittest, analog, blocks def avg_mag_sqrd_c(x, alpha): y = [0, ] for xi in x: tmp = alpha * (xi.r...
d(tmp) return y class test_probe_avg_mag_sqrd(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None d
ef test_c_001(self): alpha = 0.0001 src_data = [ 1.0 + 1.0j, 2.0 + 2.0j, 3.0 + 3.0j, 4.0 + 4.0j, 5.0 + 5.0j, 6.0 + 6.0j, 7.0 + 7.0j, 8.0 + 8.0j, 9.0 + 9.0j, 10.0 + 10.0j] expec...
rossella/neutron
quantum/openstack/common/jsonutils.py
Python
apache-2.0
5,314
0
# 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 #...
but since this is a recursive function, we could have cyclical data structures. To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are hashable. Instead we just tra
ck the depth of the object inspections and don't go too deep. Therefore, convert_instances=True is lossy ... be aware. """ nasty = [inspect.ismodule, inspect.isclass, inspect.ismethod, inspect.isfunction, inspect.isgeneratorfunction, inspect.isgenerator, inspect.istraceback, insp...
yunity/yunity-core
karrot/groups/migrations/0009_group_timezone.py
Python
agpl-3.0
505
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-31 19:38 from __future__ import unicode_literals from django.db import migrations import timezone_field.fields class Migration(migrations.Migration): dependencies = [ ('groups', '0008_group_public_description'), ] operations = [ ...
ns.AddF
ield( model_name='group', name='timezone', field=timezone_field.fields.TimeZoneField(default='Europe/Berlin'), ), ]
ajylee/gpaw-rtxs
doc/tutorials/rpa/gs_graph.py
Python
gpl-3.0
1,358
0.005891
from ase import * from ase.units import Ha from ase.dft import monkhorst_pack from ase.parallel import paropen from ase.lattice.hexagonal import Graphite from gpaw import * from gpaw.response.cell import get_primitive_cell, set_Gvectors kpts = monkhorst_pack((12,12,4)) kpts += np.array([1/24., 1/24., 1/8.]) a = 2.46 ...
d = 3.34 max_cut = 250 ds = [2.9, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 4.0, 5.0, 6.0, 12.0] for d in ds: calc = G
PAW(h=0.18, xc='PBE', #kpts=(12,12,4), kpts=kpts, maxiter=300, mixer=Mixer(beta=0.1, nmaxold=5, weight=50.0), txt='gs_%s.txt' % d, parallel={'domain': 1}, idiotproof=False) bulk = Graphit...
facetothefate/contrail-controller
src/vnsw/contrail-vrouter-api/setup.py
Python
apache-2.0
624
0.001603
# # Copyright (c) 2014 Juniper Networks, Inc. # import setuptools def requirements(filename): with open(filename) as f: lines = f.read().splitlines() return lines setuptools.setup( name='contrail-vrouter-api', version='1.0', packages=setuptools.find_packages(), # metadata author...
ists.opencontrail.org", license="Apache Software License", url="http://www.opencontrail.org/", install_requires=requirements('requirements.txt'), test_suite='contrail_vrouter_api.tests', tests_requi
re=requirements('test-requirements.txt'), )
srinivasanmit/all-in-all
G4G/sets.py
Python
gpl-3.0
2,377
0.0122
# Python program to demonstrate differences # between normal and frozen set # Same as {"a", "b","c"} normal_set = set(["a", "b","c"]) # Adding an element to normal set is fine normal_set.add("d") print("Normal Set") print(normal_set) # A frozen set frozen_set = frozenset(["e", "f", "g"]) print("Frozen Set") p...
issubset(set4) print("Set3 is subset of Set4") else : # set3 == set4 print("Set3 is same as Set4") # displaying relation between set4 and set3 if set4 < set3: # set4.issubset(set3) print("Set4 is subset of Set3") print("\n") # difference between set3 and set4 set5 = set3 - set4 print("Elements in Se...
ot in Set4: Set5 = ", set5) print("\n") # checkv if set4 and set5 are disjoint sets if set4.isdisjoint(set5): print("Set4 and Set5 have nothing in common\n") # Removing all the values of set5 set5.clear() print("After applying clear on sets Set5: ") print("Set5 = ", set5)
Venskiy/chat
restapi/serializers.py
Python
mit
1,638
0.001832
from django.contrib.auth.models import User, Group from rest_framework import serializers from chat.models import Chat, Message class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username') class ChatSerializer(serializers.ModelSerializer): ...
ta: model = Chat fields = ('id', 'last_message', 'last_message_sender_id', 'last_message_timestamp', 'last_message_is_read', 'interlocutor_id', 'interlocutor_username', 'is_interlocutor_typing') class MessageSerializer(serializers.ModelSerializer): sender_userna...
ername', 'timestamp', 'is_read')
kevin-coder/tensorflow-fork
tensorflow/python/distribute/parameter_server_strategy.py
Python
apache-2.0
22,870
0.006384
# Copyright 2018 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...
the License. # ============================================================================== """Classes implementing a multi-worker ps DistributionStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy from tensorflow.python.distribute...
istribute import distribute_lib from tensorflow.python.distribute import input_lib from tensorflow.python.distribute import mirrored_strategy from tensorflow.python.distribute import multi_worker_util from tensorflow.python.distribute import numpy_dataset from tensorflow.python.distribute import values from tensorflow....
gietal/Stocker
stocker3/Indicators_test.py
Python
mit
618
0.006472
import pandas as pd import Indicators as indicators import DataProvider as data import datetime def test_mstar(): start_date = datetime.datetime(2017, 12, 1) end_date = datetime.datetime(2018, 1, 1) df = data.read_mor
ningstar('SPY', start_date, end_date, clean=True) print df def test_vortex():
start_date = datetime.datetime(2012, 7, 19) end_date = datetime.datetime(2012, 8, 29) df = data.read_morningstar('SPY', start_date, end_date, clean=True) vi = indicators.rolling_vortex(df.High, df.Low, df.Close) print vi if __name__ == "__main__": test_vortex()
timthelion/FreeCAD
src/Mod/Fem/Init.py
Python
lgpl-2.1
2,560
0.009375
# FreeCAD init script of the Fem module # (c) 2001 Juergen Riegel #*************************************************************************** #* (c) Juergen Riegel ([email protected]) 2002 * #* * #* This file i...
he FreeCAD CAx development system. * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Softw...
n. * #* for detail see the LICENCE text file. * #* * #* FreeCAD is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warran...
machinelady/client_python
prometheus_client/core.py
Python
apache-2.0
16,613
0.001324
#!/usr/bin/python from __future__ import unicode_literals import copy import re import time import types try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: # Python 3 unicode = str from functools import wraps from threading import Lock _METRIC_NAME_RE = re.compile(r'^[a-zA-Z_:][...
self._collectors
= set() self._lock = Lock() def register(self, collector): '''Add a collector to the registry.''' with self._lock: self._collectors.add(collector) def unregister(self, collector): '''Remove a collector from the registry.''' with self._lock: self...
veltri/DLV2
tests/parser/grounding.backjump.2.test.py
Python
apache-2.0
703
0
input = """ % By this example we can check % a) the correcteness of the jumps-arrays % b) the correctness of the use of indexLastSolution and % c) how we eliminate the duplicates of the rule % ok | -ok ok | -ok :- p(A,B), q(E,F), r(F,E), t(A), s(B,A). p(1,2). p(2,1). p(3,1). q(3,4). r(4,3). t(1). s(1,2...
this example we can check % a) the correcteness of the jumps-arrays % b) the correctness of the use of indexLastSolution and % c) how we eliminate the duplicates of the rule % ok | -ok ok | -ok :- p(A,B), q(E,F), r(F,E), t(A), s(B,A). p(1,2). p(2,1). p
(3,1). q(3,4). r(4,3). t(1). s(1,2). t(3). s(1,3). t(2). """
phenoxim/nova
nova/virt/vmwareapi/host.py
Python
apache-2.0
4,514
0.000222
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # Copyright (c) 2012 VMware, 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/lic...
str(about_info.version)) data["hypervisor_hostname"] = self._host_name data["supported_instances"] = [ (obj_fields.Architecture.I686, obj_fields.HVType.VMWARE, obj_fields.VMMode.HVM), (obj_fields.Architecture.X86_64, obj_fields.HVType.VM...
return data def _set_host_enabled(self, enabled): """Sets the compute host's ability to accept new instances.""" ctx = context.get_admin_context() service = objects.Service.get_by_compute_host(ctx, CONF.host) service.disabled = not enabled service.disabled_reason = 'set ...